package org.gcube.portlets.user.geoportaldataentry.server; import static org.gcube.application.geoportal.client.GeoportalAbstractPlugin.mongoConcessioni; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.gcube.application.geoportal.common.rest.MongoConcessioni; import org.gcube.application.geoportal.common.rest.TempFile; import org.gcube.application.geoportal.common.utils.StorageUtils; import org.gcube.contentmanagement.blobstorage.transport.backend.RemoteBackendException; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class ServiceUtil. * * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) * * Jan 28, 2021 */ public class ServiceUtil { private static Logger LOG = LoggerFactory.getLogger(ServiceUtil.class); /** * Gets the instance mongo concessioni. * * @return the instance mongo concessioni */ public MongoConcessioni getInstanceMongoConcessioni() { return mongoConcessioni().build(); } /** * Creates the temp file on storage. * * @param is the is * @param fileName the file name * @return the temp file */ public TempFile createTempFileOnStorage(InputStream is, String fileName) { LOG.debug("createTempFileOnStorage called"); StorageUtils storage = new StorageUtils(); TempFile toUpload = null; try { LOG.info("calling putOntoStorage the stream with the fileName: " + fileName); toUpload = storage.putOntoStorage(is, fileName); } catch (RemoteBackendException | FileNotFoundException e) { LOG.error("Error when uploading stream on Storage: ", e); } return toUpload; } /** * To tem files. * * @param listFileUploaded the list file uploaded * @return the list */ public List toTemFiles(List listFileUploaded) { LOG.debug("toTemFiles called"); if (listFileUploaded == null || listFileUploaded.isEmpty()) return null; // Building TempFile List files = new ArrayList(listFileUploaded.size()); for (FileUploaded fileUploaded : listFileUploaded) { FileInputStream fis; try { fis = new FileInputStream(fileUploaded.getTempSystemPath()); // Creating TempFile TempFile storageTempFile = createTempFileOnStorage(fis, fileUploaded.getFileName()); files.add(storageTempFile); } catch (FileNotFoundException e) { LOG.error("Error on loading temp file with path: " + fileUploaded.getTempSystemPath(), e); } } return files; } /** * To JSON. * * @param the generic type * @param report the report * @return the string */ public String toJSON(Object theObj) { LOG.debug("toJSON called"); try { if(theObj instanceof Serializable) { return org.gcube.application.geoportal.client.utils.Serialization.write(theObj); } throw new Exception("The input object is not serializable"); } catch (Exception e) { LOG.warn("Error on deserializing: ", e); return null; } } }