Many correction of the cover, data ...

This commit is contained in:
Edouard DUPIN 2024-03-17 23:43:56 +01:00
parent e1d9da70c8
commit 530d254bf2
15 changed files with 405 additions and 61 deletions

View File

@ -84,7 +84,7 @@ public class DataResource {
return filePath;
}
public static String getFileData(final long tmpFolderId) {
public static String getFileDataOld(final long tmpFolderId) {
final String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data";
try {
createFolder(ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator);
@ -93,22 +93,24 @@ public class DataResource {
}
return filePath;
}
public static String getFileData(final UUID uuid) {
final String stringUUID = uuid.toString();
final String part1 = stringUUID.substring(0, 2);
final String part2 = stringUUID.substring(2, 4);
final String part3 = stringUUID.substring(4);
final String finalPath = part1 + File.separator + part2 + File.separator + part3;
final String finalPath = part1 + File.separator + part2;
String filePath = ConfigBaseVariable.getMediaDataFolder() + "_uuid" + File.separator + finalPath + File.separator;
try {
createFolder(filePath);
} catch (final IOException e) {
e.printStackTrace();
}
filePath += "data";
filePath += part3;
return filePath;
}
public static String getFileMetaData(final UUID uuid) {
return getFileData(uuid) + ".json";
}
public static Data getWithSha512(final String sha512) {
LOGGER.info("find sha512 = {}", sha512);
@ -154,7 +156,6 @@ public class DataResource {
try {
injectedData = DataAccess.insert(injectedData);
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
@ -167,7 +168,7 @@ public class DataResource {
}
public static void modeFileOldModelToNewModel(final long id, final UUID uuid) throws IOException {
String mediaCurentPath = getFileData(id);
String mediaCurentPath = getFileDataOld(id);
String mediaDestPath = getFileData(uuid);
LOGGER.info("src = {}", mediaCurentPath);
LOGGER.info("dst = {}", mediaDestPath);
@ -243,7 +244,7 @@ public class DataResource {
return sb.toString();
}
public Data getSmall(final Long id) {
public Data getSmall(final UUID id) {
try {
return DataAccess.get(Data.class, id);
} catch (final Exception e) {
@ -281,7 +282,7 @@ public class DataResource {
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Operation(description = "Get back some data from the data environment", tags = "SYSTEM")
public Response retrieveDataId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
@PathParam("id") final Long id) throws Exception {
@PathParam("id") final UUID id) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
// logger.info("===================================================");
LOGGER.info("== DATA retrieveDataId ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
@ -290,7 +291,7 @@ public class DataResource {
if (value == null) {
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
}
return buildStream(ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
return buildStream(getFileData(id), range, value.mimeType);
}
@GET
@ -301,7 +302,7 @@ public class DataResource {
@Operation(description = "Get a thumbnail of from the data environment (if resize is possible)", tags = "SYSTEM")
// @CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
public Response retrieveDataThumbnailId(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
@PathParam("id") final Long id) throws Exception {
@PathParam("id") final UUID id) throws Exception {
// GenericContext gc = (GenericContext) sc.getUserPrincipal();
// logger.info("===================================================");
// logger.info("== DATA retrieveDataThumbnailId ? {}", (gc==null?"null":gc.user));
@ -310,7 +311,7 @@ public class DataResource {
if (value == null) {
return Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
}
final String filePathName = ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data";
final String filePathName = getFileData(id);
final File inputFile = new File(filePathName);
if (!inputFile.exists()) {
return Response.status(404).entity("{\"error\":\"media Does not exist: " + id + "\"}").type("application/json").build();
@ -360,7 +361,7 @@ public class DataResource {
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Operation(description = "Get back some data from the data environment (with a beautifull name (permit download with basic name)", tags = "SYSTEM")
public Response retrieveDataFull(@Context final SecurityContext sc, @QueryParam(HttpHeaders.AUTHORIZATION) final String token, @HeaderParam("Range") final String range,
@PathParam("id") final Long id, @PathParam("name") final String name) throws Exception {
@PathParam("id") final UUID id, @PathParam("name") final String name) throws Exception {
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
// logger.info("===================================================");
LOGGER.info("== DATA retrieveDataFull ? id={} user={}", id, (gc == null ? "null" : gc.userByToken));
@ -369,7 +370,7 @@ public class DataResource {
if (value == null) {
Response.status(404).entity("media NOT FOUND: " + id).type("text/plain").build();
}
return buildStream(ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
return buildStream(getFileData(id), range, value.mimeType);
}
/** Adapted from http://stackoverflow.com/questions/12768812/video-streaming-to-ipad-does-not-work-with-tapestry5/12829541#12829541

View File

@ -13,6 +13,7 @@ public class FailExceptionCatcher implements ExceptionMapper<FailException> {
@Override
public Response toResponse(final FailException exception) {
LOGGER.warn("Catch FailException:");
final RestErrorResponse ret = build(exception);
LOGGER.error("Error UUID={}", ret.uuid);
// Not display backtrace ==> this may be a normal case ...

View File

@ -13,6 +13,7 @@ public class InputExceptionCatcher implements ExceptionMapper<InputException> {
@Override
public Response toResponse(final InputException exception) {
LOGGER.warn("Catch InputException:");
final RestErrorResponse ret = build(exception);
LOGGER.error("Error UUID={} ==> '{}'=>'{}'", ret.uuid, exception.missingVariable, exception.getLocalizedMessage());
// exception.printStackTrace();

View File

@ -13,6 +13,7 @@ public class SystemExceptionCatcher implements ExceptionMapper<SystemException>
@Override
public Response toResponse(final SystemException exception) {
LOGGER.warn("Catch SystemException:");
final RestErrorResponse ret = build(exception);
LOGGER.error("Error UUID={}", ret.uuid);
exception.printStackTrace();

View File

@ -736,6 +736,8 @@ public class DataAccess {
Long uniqueSQLID = null;
UUID uniqueSQLUUID = null;
final String tableName = AnnotationTools.getTableName(clazz, options);
Field primaryKeyField = null;
boolean generateUUID = false;
// real add in the BDD:
try {
// boolean createIfNotExist = clazz.getDeclaredAnnotationsByType(SQLIfNotExists.class).length != 0;
@ -746,6 +748,30 @@ public class DataAccess {
boolean firstField = true;
int count = 0;
for (final Field field : clazz.getFields()) {
// static field is only for internal global declaration ==> remove it ..
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
continue;
}
if (AnnotationTools.isPrimaryKey(field)) {
primaryKeyField = field;
if (primaryKeyField.getType() != UUID.class) {
break;
}
generateUUID = true;
count++;
final String name = AnnotationTools.getFieldName(field);
if (firstField) {
firstField = false;
} else {
query.append(",");
}
query.append(" `");
query.append(name);
query.append("`");
break;
}
}
for (final Field field : clazz.getFields()) {
// static field is only for internal global declaration ==> remove it ..
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
@ -804,15 +830,21 @@ public class DataAccess {
LOGGER.warn("generate the query: '{}'", query.toString());
// prepare the request:
final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);
Field primaryKeyField = null;
final CountInOut iii = new CountInOut(1);
UUID uuid = null;
if (generateUUID) {
firstField = false;
uuid = UUID.randomUUID();
addElement(ps, uuid, iii);
iii.inc();
}
for (final Field elem : clazz.getFields()) {
// static field is only for internal global declaration ==> remove it ..
if (java.lang.reflect.Modifier.isStatic(elem.getModifiers())) {
continue;
}
if (AnnotationTools.isPrimaryKey(elem)) {
primaryKeyField = elem;
continue;
}
final DataAccessAddOn addOn = findAddOnforField(elem);
@ -849,23 +881,36 @@ public class DataAccess {
throw new SQLException("Creating node failed, no rows affected.");
}
// Retrieve uid inserted
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
if (primaryKeyField.getType() == UUID.class) {
// uniqueSQLUUID = generatedKeys.getObject(1, UUID.class);
final byte[] tmpid = generatedKeys.getBytes(1);
uniqueSQLUUID = UuidUtils.asUuid(tmpid);
} else {
uniqueSQLID = generatedKeys.getLong(1);
}
if (generateUUID) {
// we generate the UUID, otherwise we can not retrieve it
uniqueSQLUUID = uuid;
} else {
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
if (primaryKeyField.getType() == UUID.class) {
// uniqueSQLUUID = generatedKeys.getObject(1, UUID.class);
/*
final Object obj = generatedKeys.getObject(1);
final BigInteger bigint = (BigInteger) generatedKeys.getObject(1);
uniqueSQLUUID = UuidUtils.asUuid(bigint);
final UUID generatedUUID = (UUID) generatedKeys.getObject(1);
System.out.println("UUID généré: " + generatedUUID);
*/
final Object obj = generatedKeys.getObject(1);
final byte[] tmpid = generatedKeys.getBytes(1);
uniqueSQLUUID = UuidUtils.asUuid(tmpid);
} else {
uniqueSQLID = generatedKeys.getLong(1);
}
} else {
throw new SQLException("Creating node failed, no ID obtained (1).");
} else {
throw new SQLException("Creating node failed, no ID obtained (1).");
}
} catch (final Exception ex) {
LOGGER.error("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating node failed, no ID obtained (2).");
}
} catch (final Exception ex) {
LOGGER.error("Can not get the UID key inserted ... ");
ex.printStackTrace();
throw new SQLException("Creating node failed, no ID obtained (2).");
}
if (primaryKeyField != null) {
if (primaryKeyField.getType() == Long.class) {
@ -1106,7 +1151,10 @@ public class DataAccess {
}
static void addElement(final PreparedStatement ps, final Object value, final CountInOut iii) throws Exception {
if (value instanceof final Long tmp) {
if (value instanceof final UUID tmp) {
final byte[] dataByte = UuidUtils.asBytes(tmp);
ps.setBytes(iii.value, dataByte);
} else if (value instanceof final Long tmp) {
LOGGER.debug("Inject Long => {}", tmp);
ps.setLong(iii.value, tmp);
} else if (value instanceof final Integer tmp) {

View File

@ -5,15 +5,23 @@ import java.lang.reflect.ParameterizedType;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.AnnotationTools;
import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.dataAccess.CountInOut;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.DataAccessAddOn;
import org.kar.archidata.dataAccess.DataFactory;
import org.kar.archidata.dataAccess.LazyGetter;
import org.kar.archidata.dataAccess.QueryOptions;
import org.kar.archidata.dataAccess.addOn.model.TableCoversLongLong;
import org.kar.archidata.dataAccess.addOn.model.TableCoversLongUUID;
import org.kar.archidata.dataAccess.addOn.model.TableCoversUUIDLong;
import org.kar.archidata.dataAccess.addOn.model.TableCoversUUIDUUID;
import org.kar.archidata.dataAccess.options.OverrideTableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -88,8 +96,8 @@ public class AddOnDataJson implements DataAccessAddOn {
if (!rs.wasNull()) {
final ObjectMapper objectMapper = new ObjectMapper();
if (field.getType() == List.class) {
ParameterizedType listType = (ParameterizedType) field.getGenericType();
Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];
final ParameterizedType listType = (ParameterizedType) field.getGenericType();
final Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];
if (listClass == Long.class) {
final Object dataParsed = objectMapper.readValue(jsonData, new TypeReference<List<Long>>() {});// field.getType());
field.set(data, dataParsed);
@ -120,6 +128,12 @@ public class AddOnDataJson implements DataAccessAddOn {
field.set(data, dataParsed);
return;
}
if (listClass == UUID.class) {
final Object dataParsed = objectMapper.readValue(jsonData, new TypeReference<List<UUID>>() {});// field.getType());
field.set(data, dataParsed);
return;
}
LOGGER.warn("Maybe fail to translate Model in datajson list: List<{}>", listClass.getCanonicalName());
}
final Object dataParsed = objectMapper.readValue(jsonData, field.getType());
field.set(data, dataParsed);
@ -131,4 +145,143 @@ public class AddOnDataJson implements DataAccessAddOn {
final boolean createIfNotExist, final boolean createDrop, final int fieldId) throws Exception {
DataFactory.createTablesSpecificType(tableName, field, mainTableBuilder, preActionList, postActionList, createIfNotExist, createDrop, fieldId, JsonValue.class);
}
public static void addLink(final Class<?> clazz, final Long id, final String column, final Long remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongLong data = DataAccess.get(TableCoversLongLong.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
public static void addLink(final Class<?> clazz, final Long id, final String column, final UUID remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongUUID data = DataAccess.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
public static void addLink(final Class<?> clazz, final UUID id, final String column, final UUID remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
public static void addLink(final Class<?> clazz, final UUID id, final String column, final Long remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
data.covers = new ArrayList<>();
}
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
return;
}
}
data.covers.add(remoteKey);
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
public static void removeLink(final Class<?> clazz, final UUID id, final String column, final Long remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<Long> newList = new ArrayList<>();
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
public static void removeLink(final Class<?> clazz, final UUID id, final String column, final UUID remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
public static void removeLink(final Class<?> clazz, final Long id, final String column, final Long remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongLong data = DataAccess.get(TableCoversLongLong.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<Long> newList = new ArrayList<>();
for (final Long elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
public static void removeLink(final Class<?> clazz, final Long id, final String column, final UUID remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TableCoversLongUUID data = DataAccess.get(TableCoversLongUUID.class, id, new OverrideTableName(tableName));
if (data.covers == null) {
return;
}
final List<UUID> newList = new ArrayList<>();
for (final UUID elem : data.covers) {
if (elem.equals(remoteKey)) {
continue;
}
newList.add(elem);
}
data.covers = newList;
DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));
}
/*
public static <TYPE> void addLink(final Class<TYPE> clazz, final Object localKey, final String column, final Object remoteKey) throws Exception {
final String tableName = AnnotationTools.getTableName(clazz);
final TYPE data = DataAccess.get(clazz, localKey); // TODO: add filter of the "column"
// find the field column:
// add the remoteKey in the list:
// post new data in the DB
final String linkTableName = generateLinkTableName(this.tableName, this.column);
final LinkTable insertElement = new LinkTable(this.localKey, this.remoteKey);
DataAccess.insert(insertElement, new OverrideTableName(linkTableName));
}*/
}

View File

@ -0,0 +1,28 @@
package org.kar.archidata.dataAccess.addOn.model;
import java.util.List;
import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.GenericData;
import jakarta.persistence.Column;
import jakarta.persistence.Id;
public class TableCoversLongLong extends GenericData {
public TableCoversLongLong() {
// nothing to do...
}
public TableCoversLongLong(final Long id, final List<Long> covers) {
this.id = id;
this.covers = covers;
}
@Column(nullable = false)
@Id
public Long id;
@DataJson()
@Column(nullable = false)
public List<Long> covers;
}

View File

@ -0,0 +1,29 @@
package org.kar.archidata.dataAccess.addOn.model;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.GenericData;
import jakarta.persistence.Column;
import jakarta.persistence.Id;
public class TableCoversLongUUID extends GenericData {
public TableCoversLongUUID() {
// nothing to do...
}
public TableCoversLongUUID(final Long id, final List<UUID> covers) {
this.id = id;
this.covers = covers;
}
@Column(nullable = false)
@Id
public Long id;
@DataJson()
@Column(nullable = false)
public List<UUID> covers;
}

View File

@ -0,0 +1,29 @@
package org.kar.archidata.dataAccess.addOn.model;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.GenericData;
import jakarta.persistence.Column;
import jakarta.persistence.Id;
public class TableCoversUUIDLong extends GenericData {
public TableCoversUUIDLong() {
// nothing to do...
}
public TableCoversUUIDLong(final UUID id, final List<Long> covers) {
this.id = id;
this.covers = covers;
}
@Column(nullable = false)
@Id
public UUID id;
@DataJson()
@Column(nullable = false)
public List<Long> covers;
}

View File

@ -0,0 +1,29 @@
package org.kar.archidata.dataAccess.addOn.model;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.GenericData;
import jakarta.persistence.Column;
import jakarta.persistence.Id;
public class TableCoversUUIDUUID extends GenericData {
public TableCoversUUIDUUID() {
// nothing to do...
}
public TableCoversUUIDUUID(final UUID id, final List<UUID> covers) {
this.id = id;
this.covers = covers;
}
@Column(nullable = false)
@Id
public UUID id;
@DataJson()
@Column(nullable = false)
public List<UUID> covers;
}

View File

@ -15,8 +15,7 @@ public class CORSFilter implements ContainerResponseFilter {
// System.err.println("filter cors ..." + request.toString());
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "*");
// "Origin, content-type, Content-type, Accept, authorization, mime-type, filename");
response.getHeaders().add("Access-Control-Allow-Headers", "Origin, content-type, Content-type, Accept, Authorization, mime-type, filename");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD");
}

View File

@ -2,6 +2,9 @@ package org.kar.archidata.filter;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
@ -11,8 +14,11 @@ import jakarta.ws.rs.ext.Provider;
@Provider
@PreMatching
public class OptionFilter implements ContainerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(OptionFilter.class);
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
LOGGER.warn("Receive message from: [{}] {}", requestContext.getMethod(), requestContext.getUriInfo().getPath());
if (requestContext.getMethod().contentEquals("OPTIONS")) {
requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build());
}

View File

@ -15,10 +15,11 @@ import java.util.List;
import java.util.UUID;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.kar.archidata.api.DataResource;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryAnd;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.addOn.AddOnDataJson;
import org.kar.archidata.dataAccess.options.Condition;
import org.kar.archidata.dataAccess.options.ReadAllColumn;
import org.kar.archidata.model.Data;
@ -66,16 +67,6 @@ public class DataTools {
return filePath;
}
public static String getFileData(final long tmpFolderId) {
final String filePath = ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data";
try {
createFolder(ConfigBaseVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator);
} catch (final IOException e) {
e.printStackTrace();
}
return filePath;
}
public static Data getWithSha512(final String sha512) {
try {
return DataAccess.getWhere(Data.class, new Condition(new QueryCondition("sha512", "=", sha512)), new ReadAllColumn());
@ -124,7 +115,7 @@ public class DataTools {
return null;
}
final String mediaPath = getFileData(out.id);
final String mediaPath = DataResource.getFileData(out.id);
LOGGER.info("src = {}", tmpPath);
LOGGER.info("dst = {}", mediaPath);
Files.move(Paths.get(tmpPath), Paths.get(mediaPath), StandardCopyOption.ATOMIC_MOVE);
@ -220,7 +211,7 @@ public class DataTools {
return data;
}
public static <T> Response uploadCover(final Class<T> clazz, final Long id, String fileName, final InputStream fileInputStream, final FormDataContentDisposition fileMetaData) {
public static <CLASS_TYPE, ID_TYPE> Response uploadCover(final Class<CLASS_TYPE> clazz, final ID_TYPE id, String fileName, final InputStream fileInputStream, final FormDataContentDisposition fileMetaData) {
try {
// correct input string stream :
fileName = multipartCorrection(fileName);
@ -231,7 +222,7 @@ public class DataTools {
LOGGER.info(" - file_name: ", fileName);
LOGGER.info(" - fileInputStream: {}", fileInputStream);
LOGGER.info(" - fileMetaData: {}", fileMetaData);
final T media = DataAccess.get(clazz, id);
final CLASS_TYPE media = DataAccess.get(clazz, id);
if (media == null) {
return Response.notModified("Media Id does not exist or removed...").build();
}
@ -261,7 +252,13 @@ public class DataTools {
}
// Fist step: retrieve all the Id of each parents:...
LOGGER.info("Find typeNode");
AddOnManyToMany.addLink(clazz, id, "cover", data.id);
if (id instanceof final Long idLong) {
AddOnDataJson.addLink(clazz, idLong, "covers", data.id);
} else if (id instanceof final UUID idUUID) {
AddOnDataJson.addLink(clazz, idUUID, "covers", data.id);
} else {
throw new IOException("Fail to add Cover can not detect type...");
}
return Response.ok(DataAccess.get(clazz, id)).build();
} catch (final Exception ex) {
System.out.println("Cat ann unexpected error ... ");

View File

@ -1,10 +1,17 @@
package org.kar.archidata.tools;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.UUID;
public class UuidUtils {
public static UUID asUuid(final BigInteger bigInteger) {
final long mostSignificantBits = bigInteger.longValue();
final long leastSignificantBits = bigInteger.shiftRight(64).longValue();
return new UUID(mostSignificantBits, leastSignificantBits);
}
public static UUID asUuid(final byte[] bytes) {
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long firstLong = bb.getLong();

View File

@ -74,19 +74,26 @@ export type RESTRequestType = {
queries?: object,
};
/**
* This service permit to add some data like token and authorization..
*/
export function RESTRequest({ restModel, restConfig, data, params, queries }: RESTRequestType): Promise<ModelResponseHttp> {
function removeTrailingSlashes(input: string): string {
return input.replace(/\/+$/, '');
}
function removeLeadingSlashes(input: string): string {
return input.replace(/^\/+/, '');
}
export function RESTUrl({ restModel, restConfig, data, params, queries }: RESTRequestType): string {
// Create the URL PATH:
let generateUrl = `${restConfig.server}/${restModel.endPoint}`;
let generateUrl = `${removeTrailingSlashes(restConfig.server)}/${removeLeadingSlashes(restModel.endPoint)}`;
if (params !== undefined) {
for (let key of Object.keys(params)) {
generateUrl = generateUrl.replaceAll(`{${key}}`, `${params[key]}`);
}
}
if (queries === undefined && (restConfig.token === undefined || restModel.tokenInUrl !== true)) {
return generateUrl;
}
const searchParams = new URLSearchParams();
if (queries !== undefined) {
const searchParams = new URLSearchParams();
for (let key of Object.keys(queries)) {
const value = queries[key];
if (Array.isArray(value)) {
@ -97,11 +104,16 @@ export function RESTRequest({ restModel, restConfig, data, params, queries }: RE
searchParams.append(`${key}`, `${value}`);
}
}
if (restConfig.token !== undefined && restModel.tokenInUrl === true) {
searchParams.append('Authorization', `Bearer ${restConfig.token}`);
}
generateUrl += "?" + searchParams.toString();
}
if (restConfig.token !== undefined && restModel.tokenInUrl === true) {
searchParams.append('Authorization', `Bearer ${restConfig.token}`);
}
return generateUrl + "?" + searchParams.toString();
}
export function RESTRequest({ restModel, restConfig, data, params, queries }: RESTRequestType): Promise<ModelResponseHttp> {
// Create the URL PATH:
let generateUrl = RESTUrl({ restModel, restConfig, data, params, queries });
let headers: any = {};
if (restConfig.token !== undefined && restModel.tokenInUrl !== true) {
headers['Authorization'] = `Bearer ${restConfig.token}`;
@ -111,7 +123,10 @@ export function RESTRequest({ restModel, restConfig, data, params, queries }: RE
}
if (restModel.requestType !== HTTPRequestModel.GET) {
// if Get we have not a content type, the body is empty
headers['Content-Type'] = restModel.contentType;
if (restModel.contentType !== HTTPMimeType.MULTIPART) {
// special case of multi-part ==> no content type otherwise the browser does not set the ";bundary=--****"
headers['Content-Type'] = restModel.contentType;
}
}
let body = data;
if (restModel.contentType === HTTPMimeType.JSON) {