geoportal-data-viewer-app/src/main/java/org/gcube/portlets/user/geoportaldataviewer/server/GeoportalExporterActionServ...

241 lines
8.1 KiB
Java

/**
*
*/
package org.gcube.portlets.user.geoportaldataviewer.server;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.HttpGet;
import org.gcube.common.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.user.geoportaldataviewer.client.GeoportalDataViewerConstants;
import org.gcube.portlets.user.geoportaldataviewer.server.mongoservice.GeoportalServiceIdentityProxy;
import org.gcube.portlets.user.uriresolvermanager.geoportal.GeoportalExporterAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class GeoportalExporterActionServlet.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Apr 23, 2024
*/
public class GeoportalExporterActionServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 6037090280489238565L;
protected static Logger logger = LoggerFactory.getLogger(GeoportalExporterActionServlet.class);
/**
* {@inheritDoc}
*/
@Override
public void init() throws ServletException {
super.init();
logger.trace(GeoportalExporterActionServlet.class.getSimpleName() + " ready.");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("doPost Called");
serveRequest(req, resp);
}
// /**
// * Do get.
// *
// * @param req the req
// * @param resp the resp
// * @throws IOException Signals that an I/O exception has occurred.
// * @throws ServletException the servlet exception
// */
// public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
// logger.info("doGet Called");
// serveRequest(req, resp);
// }
/**
* Serve request.
*
* @param req the req
* @param resp the resp
* @throws IOException Signals that an I/O exception has occurred.
*/
public void serveRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// setSecretManager();
String projectID = req.getParameter(GeoportalDataViewerConstants.PROIECT_ID_PARAMETER);
String ucdID = req.getParameter(GeoportalDataViewerConstants.UCD_ID_PARAMETER);
String contextID = req.getParameter(GeoportalDataViewerConstants.CONTEXT_ID_PARAMETER);
String userID = req.getParameter(GeoportalDataViewerConstants.USER_ID_PARAMETER);
logger.info("serveRequest called with [projectID: " + projectID + ", ucdID: " + ucdID + ", contextID: " + contextID
+ ", userID: " + userID + "]");
if (contextID == null || contextID.isEmpty())
sendError(resp, "Bad Request. No context found!");
PortalContext pContext = PortalContext.getConfiguration();
String scope = pContext.getCurrentScope(contextID);
logger.info("The scope is {}", scope);
try {
// Setting header required to {@PortalContext}
MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
mutableRequest.putHeader(PortalContext.VRE_ID_ATTR_NAME, contextID);
mutableRequest.putHeader(PortalContext.USER_ID_ATTR_NAME, userID);
ScopeProvider.instance.set(scope);
GeoportalServiceIdentityProxy identity = new GeoportalServiceIdentityProxy(mutableRequest);
String theToken = identity.getToken();
String theIdentity = identity.getIdentity();
logger.info("The identity is {}", theIdentity);
GeoportalExporterAPI geoportalExporterAPI = new GeoportalExporterAPI();
URL urlRequest = geoportalExporterAPI.exportProject("pdf", ucdID, projectID, false);
String urlToRedirect = urlRequest.toString();
logger.info("Performing request to {} with identity description {}", urlToRedirect, identity.getDescription());
logger.info("Token is {}", theToken.substring(0, 20) + "_MASKED_TOKEN");
InputStream is = performHttpRequestToSGService(urlToRedirect, theIdentity, theToken);
resp.setContentType("text/html; charset=utf-8");
IOUtils.copy(is, resp.getOutputStream());
resp.flushBuffer();
} catch (Exception e) {
logger.error("Error occurred when exporting the Project with id: " + projectID, e);
sendError(resp, "Error occurred when exporting the Project. Error is: " + e.getMessage());
return;
}
}
/**
* Perform http request to SG service.
*
* @param urlToService the url to service
* @param identity the identity
* @param token the token
* @return the input stream
* @throws IOException Signals that an I/O exception has occurred.
*/
public static InputStream performHttpRequestToSGService(String urlToService, String identity, String token)
throws IOException {
logger.debug("performHttpRequestToSGService called");
try {
URL url = new URL(urlToService);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// timeout at 60sec
conn.setConnectTimeout(6000);
conn.setDoOutput(true);
if (token.length() > 50) {
// is JWT TOKEN
conn.setRequestProperty("Authorization", "Bearer " + token);
} else {
// is legacy Token
conn.setRequestProperty("gcube-token", token);
}
conn.setRequestProperty("Content-Type", "text/html");
conn.setRequestMethod("GET");
logger.debug("performHttpRequestToSGService done, returning");
return conn.getInputStream();
} catch (IOException e) {
logger.error("Error on performing request to url " + urlToService, e);
throw e;
}
}
/**
* Sets the headers to target.
*
* @param httpSource the http source
* @param response the response
* @return the http servlet response
*/
public static HttpServletResponse setHeadersToTarget(HttpServletRequest httpSource, HttpServletResponse response) {
Enumeration<String> headersNames = httpSource.getHeaderNames();
while (headersNames.hasMoreElements()) {
String headerName = (String) headersNames.nextElement();
Enumeration<String> values = httpSource.getHeaders(headerName);
while (values.hasMoreElements()) {
String value = values.nextElement();
logger.info("Copying header {} with value {}", headerName, value);
response.addHeader(headerName, value);
}
}
return response;
}
/**
* Sets the headers to target.
*
* @param httpSource the http source
* @param httpTarget the http target
* @return the http get
*/
public static HttpGet setHeadersToTarget(HttpServletRequest httpSource, HttpGet httpTarget) {
Enumeration<String> headersNames = httpSource.getHeaderNames();
while (headersNames.hasMoreElements()) {
String headerName = (String) headersNames.nextElement();
Enumeration<String> values = httpSource.getHeaders(headerName);
while (values.hasMoreElements()) {
String value = values.nextElement();
logger.info("Copying header {} with value {}", headerName, value);
httpTarget.addHeader(headerName, value);
}
}
return httpTarget;
}
/**
* Sets the headers to response.
*
* @param httpSource the http source
* @param httpTarget the http target
* @return the http get
*/
public static HttpGet setHeadersToResponse(HttpServletRequest httpSource, HttpGet httpTarget) {
Enumeration<String> headersNames = httpSource.getHeaderNames();
while (headersNames.hasMoreElements()) {
String headerName = (String) headersNames.nextElement();
Enumeration<String> values = httpSource.getHeaders(headerName);
while (values.hasMoreElements()) {
String value = values.nextElement();
logger.info("Copying header {} with value {}", headerName, value);
httpTarget.addHeader(headerName, value);
}
}
return httpTarget;
}
/**
* Send response.
*
* @param response the response
* @param message the message
* @throws IOException Signals that an I/O exception has occurred.
*/
protected void sendError(HttpServletResponse response, String message) throws IOException {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/html");
response.getWriter().write("<html><head><title>Error</title></head><body>" + message + "</body></html>");
response.flushBuffer();
}
}