geoportal-data-entry-app/src/test/java/org/gcube/application/Service_Tests.java

232 lines
7.6 KiB
Java

package org.gcube.application;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Properties;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.gcube.application.geoportal.common.model.JSONPathWrapper;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.document.access.Access;
import org.gcube.application.geoportal.common.model.document.access.AccessPolicy;
import org.gcube.application.geoportalcommon.geoportal.GeoportalClientCaller;
import org.gcube.application.geoportalcommon.geoportal.ProjectsCaller;
import org.gcube.application.geoportalcommon.geoportal.UseCaseDescriptorCaller;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.user.geoportaldataentry.server.MongoServiceUtil;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploadedRemote;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.client.Random;
public class Service_Tests {
private static final String GCUBE_CONFIG_PROPERTIES_FILENAME = "gcube_config.properties";
// APP Working Directory + /src/test/resources must be the location of
// gcube_config.properties
private static String gcube_config_path = String.format("%s/%s",
System.getProperty("user.dir") + "/src/test/resources", GCUBE_CONFIG_PROPERTIES_FILENAME);
private static String CONTEXT;
private static String TOKEN;
private UseCaseDescriptorCaller clientUCD = null;
private ProjectsCaller clientPrj = null;
private static String PROFILE_ID = "profiledConcessioni";
private static String PROJECT_ID = "644a66e944aad51c80409a3b";
private static String MY_LOGIN = "francesco.mangiacrapa";
public static final String JSON_$_POINTER = "$";
private static final Logger LOG = LoggerFactory.getLogger(Service_Tests.class);
/**
* Read context settings.
*/
public static void readContextSettings() {
try (InputStream input = new FileInputStream(gcube_config_path)) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
CONTEXT = prop.getProperty("CONTEXT");
TOKEN = prop.getProperty("TOKEN");
// get the property value and print it out
System.out.println("CONTEXT: " + CONTEXT);
System.out.println("TOKEN: " + TOKEN);
} catch (IOException ex) {
ex.printStackTrace();
}
}
//@Before
public void init() {
readContextSettings();
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
clientPrj = GeoportalClientCaller.projects();
clientUCD = GeoportalClientCaller.useCaseDescriptors();
}
//@Test
public void deleteFileSet_ServiceTest() throws Exception {
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
boolean ignore_errors = false;
String path = "$.abstractRelazione.filesetIta";
Project doc = clientPrj.getProjectByID(PROFILE_ID, PROJECT_ID);
// JSONPathWrapper wrapper = new JSONPathWrapper(doc.getTheDocument().toJson());
// List<String> matchingPaths = wrapper.getMatchingPaths(path);
//
// LOG.info("matchingPaths is: " + matchingPaths);
//
// String error = null;
// if (matchingPaths.isEmpty()) {
// error = "No Registered FileSet found at " + path;
// if (!ignore_errors) {
// throw new WebApplicationException(error, Response.Status.BAD_REQUEST);
// }
// }
// if (matchingPaths.size() > 1 && !ignore_errors) {
// error = "Multiple Fileset (" + matchingPaths.size() + ") matching " + path;
// if (!ignore_errors)
// throw new WebApplicationException(error, Response.Status.BAD_REQUEST);
// }
//
// if (error != null && ignore_errors) {
// LOG.info("Error detected {}. Ignoring it and returning input doc", error);
//
// }
//
// List<Object> listPath = wrapper.getByPath(path);
// LOG.info("List path: " + listPath);
// RegisteredFileSet fs = Serialization.convert(listPath.get(0), RegisteredFileSet.class);
// LOG.info("Going to delete {}", fs);
LOG.info("Going to delete {}", path);
Project newDoc = clientPrj.deleteFileset(PROFILE_ID, PROJECT_ID, path, true, true);
LOG.info("newDoc {}", newDoc);
}
//@Test
public void registerFileSet() throws Exception {
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
Project theProject = clientPrj.getProjectByID(PROFILE_ID, PROJECT_ID);
MongoServiceUtil mongoService = new MongoServiceUtil();
Access access = new Access();
access.setLicense("CC-BY");
access.setPolicy(AccessPolicy.OPEN);
String sectionJSONPath = "$.abstractRelazione";
String fieldName = "filesetIta";
String fieldDefinition = "$.abstractRelazione._children[?(@.filesetIta)]";
String theFileName = "Application_Profile_for_CSW_2.0-2.pdf";
String theFileURL = "https://data.dev.d4science.org/shub/E_bnN2aDJZZUMySy9peE9ScEVLNVFNWjBOZWx0cXQ2UUFkQ2E3Rjc1S29EelJIMEJGbDRoczBnbHVPWHczZTNQTw==";
FileUploadedRemote file = new FileUploadedRemote();
file.setUrl(theFileURL);
file.setFileName(theFileName);
File input = null;
File output = null;
try {
File tempDir = Files.createTempDirectory("GEOPORTAL_REPLACE_FILES_").toFile();
String tmpDirPath = tempDir.getAbsolutePath();
if (file instanceof FileUploadedRemote) {
FileUploadedRemote remote = (FileUploadedRemote) file;
LOG.info("Uploaded file is remote: " + remote.getUrl());
InputStream in = new URL(remote.getUrl()).openStream();
String fileName = (remote.getFileName() == null || remote.getFileName().isEmpty())
? "file_" + Random.nextInt()
: remote.getFileName();
LOG.info("the fileName is: " + fileName);
output = new File(tmpDirPath, fileName);
Path outputAbsolutePath = Paths.get(output.getAbsolutePath());
Files.copy(in, outputAbsolutePath, StandardCopyOption.REPLACE_EXISTING);
LOG.info("Remote file: " + remote.getUrl() + ", copied to new file: " + output.getName());
} else {
LOG.info("Uploaded file is local: " + file.getTempSystemPath());
input = new File(file.getTempSystemPath());
output = new File(tmpDirPath, file.getFileName());
copyContent(input, output);
LOG.info("Temp file: " + file.getTempSystemPath() + ", copied to new file: " + output.getName());
}
//tempDir.deleteOnExit();
} catch (Exception e) {
LOG.warn("Skipping file: " + file.getFileName() + ". Error: " + e.getMessage(), e);
}
File fileset = output;
LOG.info("final fileName is: " + fileset.getName());
mongoService.registerFileSet(theProject.getProfileID(), theProject, sectionJSONPath, fieldName, fieldDefinition, access, fileset);
LOG.info("registerFileSet: finished!");
}
/**
* Copy content.
*
* @param a the a
* @param b the b
* @throws Exception the exception
*/
public static void copyContent(File a, File b) throws Exception {
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
// read() function to read the
// byte of data
while ((n = in.read()) != -1) {
// write() function to write
// the byte of data
out.write(n);
}
} finally {
if (in != null) {
// close() function to close the
// stream
in.close();
}
// close() function to close
// the stream
if (out != null) {
out.close();
}
}
LOG.debug("File Copied");
}
}