fi.evolver.ai.vaadin.entity.ChatAttachment Maven / Gradle / Ivy
package fi.evolver.ai.vaadin.entity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import fi.evolver.utils.GzipUtils;
import jakarta.persistence.*;
@Entity
@Table(name="chat_attachment")
public class ChatAttachment {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private long id;
@Column(name="mime_type")
private String mimeType;
@Column(name="data")
private byte[] data;
@Column(name="creation_time")
private LocalDateTime creationTime;
@Column(name="provider")
private String provider;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="chat_id")
private Chat chat;
public ChatAttachment() {}
public ChatAttachment(String mimeType, byte[] data, String provider, Chat chat) {
this.mimeType = mimeType;
this.data = compressData(data);
this.creationTime = LocalDateTime.now();
this.provider = provider;
this.chat = chat;
}
public byte[] getData() {
return decompressData(data);
}
public String getMimeType() {
return mimeType;
}
private static byte[] compressData(byte[] data) {
return GzipUtils.zip(data);
}
private static byte[] decompressData(byte[] data) {
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = gzipInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
gzipInputStream.close();
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
catch (IOException e) {
e.printStackTrace();
}
return new byte[0];
}
@Override
public String toString() {
return "ChatAttachment [id=" + id + ", chat=" + chat.getChatId() + ", mimeType=" + mimeType + ", data=" +
Arrays.toString(getData()) + ", creationTime=" + creationTime + ", provider=" + provider + "]";
}
}