use of com.twinsoft.convertigo.engine.util.HttpServletRequestTwsWrapper in project convertigo by convertigo.
the class GenericServlet method processRequest.
public Object processRequest(HttpServletRequest request) throws Exception {
HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper ? (HttpServletRequestTwsWrapper) request : null;
File temporaryFile = null;
try {
// Check multipart request
if (ServletFileUpload.isMultipartContent(request)) {
Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(1000);
temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
int cptFile = 0;
temporaryFile.delete();
temporaryFile.mkdirs();
factory.setRepository(temporaryFile);
Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : " + temporaryFile.getAbsolutePath());
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
upload.setFileSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));
// Parse the request
List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));
for (FileItem fileItem : items) {
String parameterName = fileItem.getFieldName();
String parameterValue;
if (fileItem.isFormField()) {
String ct = fileItem.getContentType();
parameterValue = ct != null && ct.contains("charset=") ? fileItem.getString() : fileItem.getString(StandardCharsets.UTF_8.name());
Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName + "' : " + parameterValue);
} else {
String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
if (name.length() > 0) {
File wDir = new File(temporaryFile, "" + (++cptFile));
wDir.mkdirs();
File wFile = new File(wDir, name);
fileItem.write(wFile);
fileItem.delete();
parameterValue = wFile.getAbsolutePath();
Engine.logContext.debug("(ServletRequester.initContext) Temporary uploaded file for field '" + parameterName + "' : " + parameterValue);
} else {
Engine.logContext.debug("(ServletRequester.initContext) No temporary uploaded file for field '" + parameterName + "', empty name");
parameterValue = "";
}
}
if (twsRequest != null) {
twsRequest.addParameter(parameterName, parameterValue);
}
}
}
Requester requester = getRequester();
request.setAttribute("convertigo.requester", requester);
Object result = requester.processRequest(request);
processRequestEnd(request, requester);
return result;
} finally {
if (temporaryFile != null) {
try {
Engine.logEngine.debug("(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
FileUtils.deleteDirectory(temporaryFile);
} catch (IOException e) {
}
}
}
}
use of com.twinsoft.convertigo.engine.util.HttpServletRequestTwsWrapper in project convertigo by convertigo.
the class RestApiServlet method service.
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getCharacterEncoding() == null) {
try {
// Set encoding if needed
request.setCharacterEncoding("UTF-8");
} catch (Exception e) {
throw new ServletException(e);
}
}
try {
if (EnginePropertiesManager.getPropertyAsBoolean(PropertyName.XSRF_API)) {
HttpUtils.checkXSRF(request, response);
}
HttpSessionListener.checkSession(request);
} catch (Throwable e) {
throw new ServletException(e.getMessage(), e);
}
if (Engine.isEngineMode() && KeyManager.getCV(Session.EmulIDURLMAPPER) < 1) {
String msg;
if (KeyManager.has(Session.EmulIDURLMAPPER) && KeyManager.hasExpired(Session.EmulIDURLMAPPER)) {
Engine.logEngine.error(msg = "Key expired for the URL Mapper.");
throw new ServletException(new KeyExpiredException(msg));
}
Engine.logEngine.error(msg = "No key for the URL Mapper.");
throw new ServletException(new MaxCvsExceededException(msg));
}
HttpServletRequestTwsWrapper wrapped_request = new HttpServletRequestTwsWrapper(request);
request = wrapped_request;
try {
HttpSessionListener.checkSession(request);
} catch (TASException e) {
HttpUtils.terminateSession(request.getSession());
throw new RuntimeException(e);
}
HttpSession httpSession = request.getSession();
LogParameters logParameters = GenericUtils.cast(httpSession.getAttribute(RestApiServlet.class.getCanonicalName()));
if (logParameters == null) {
httpSession.setAttribute(RestApiServlet.class.getCanonicalName(), logParameters = new LogParameters());
logParameters.put(mdcKeys.ContextID.toString().toLowerCase(), httpSession.getId());
}
Log4jHelper.mdcSet(logParameters);
logParameters.put(mdcKeys.ClientIP.toString().toLowerCase(), request.getRemoteAddr());
String encoded = request.getParameter(Parameter.RsaEncoded.getName());
if (encoded != null) {
String query = Engine.theApp.rsaManager.decrypt(encoded, request.getSession());
wrapped_request.clearParameters();
wrapped_request.addQuery(query);
}
String method = request.getMethod();
String uri = request.getRequestURI();
String query = request.getQueryString();
Engine.logEngine.debug("(RestApiServlet) Requested URI: " + method + " " + uri);
boolean isYaml = request.getParameter("YAML") != null;
boolean isJson = request.getParameter("JSON") != null;
if ("GET".equalsIgnoreCase(method) && (query == null || query.isEmpty()) && (uri.endsWith("/" + SwaggerUtils.servletMappingPath) || uri.endsWith("/" + OpenApiUtils.servletMappingPath))) {
isJson = true;
}
// Generate YAML/JSON definition (swagger specific)
if ("GET".equalsIgnoreCase(method) && (isYaml || isJson)) {
try {
String requestUrl = HttpUtils.originalRequestURL(request);
// force endpoint in definition
try {
String endPointUrl = EnginePropertiesManager.getProperty(PropertyName.APPLICATION_SERVER_CONVERTIGO_ENDPOINT);
if (endPointUrl != null && !endPointUrl.isEmpty()) {
requestUrl = endPointUrl + (uri.indexOf("/" + SwaggerUtils.servletMappingPath) != -1 ? uri.substring(uri.indexOf("/" + SwaggerUtils.servletMappingPath)) : uri.substring(uri.indexOf("/" + OpenApiUtils.servletMappingPath)));
Engine.logEngine.debug("(RestApiServlet) Force requestUrl: " + requestUrl);
} else {
Engine.logEngine.debug("(RestApiServlet) Set requestUrl: " + requestUrl);
}
} catch (Throwable t) {
Engine.logEngine.error("(RestApiServlet) Unable to retrieve server endpoint url: ", t);
}
Engine.logEngine.debug("(RestApiServlet) Projects path: " + new File(Engine.PROJECTS_PATH).getAbsolutePath());
String output = uri.indexOf("/" + SwaggerUtils.servletMappingPath) != -1 ? buildSwaggerDefinition(requestUrl, request.getParameter("__project"), isYaml) : buildOpenApiDefinition(requestUrl, request.getParameter("__project"), isYaml);
response.setCharacterEncoding("UTF-8");
response.setContentType((isYaml ? MimeType.Yaml : MimeType.Json).value());
Writer writer = response.getWriter();
writer.write(output);
Engine.logEngine.debug("(RestApiServlet) Definition sent :\n" + output);
} catch (Exception e) {
throw new ServletException(e);
}
} else // Handle REST request
{
long t0 = System.currentTimeMillis();
try {
Collection<UrlMapper> collection = RestApiManager.getInstance().getUrlMappers();
if (collection.size() > 0) {
if (method.equalsIgnoreCase("OPTIONS")) {
String origin = HeaderName.Origin.getHeader(request);
if (origin != null) {
Set<String> methods = new HashSet<String>();
String corsOrigin = null;
for (UrlMapper urlMapper : collection) {
String co = HttpUtils.filterCorsOrigin(urlMapper.getProject().getCorsOrigin(), origin);
if (co != null) {
if (corsOrigin == null || co.length() > corsOrigin.length()) {
corsOrigin = co;
}
urlMapper.addMatchingMethods(wrapped_request, methods);
}
}
HttpUtils.applyCorsHeaders(request, response, corsOrigin, String.join(", ", methods));
}
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}
// Found a matching operation
UrlMappingOperation urlMappingOperation = null;
List<UrlAuthentication> urlAuthentications = null;
for (UrlMapper urlMapper : collection) {
urlMappingOperation = urlMapper.getMatchingOperation(request);
if (urlMappingOperation != null) {
urlAuthentications = urlMapper.getAuthenticationList();
break;
}
}
// Handle request
if (urlMappingOperation != null) {
StringBuffer buf;
// Request headers
if (Engine.logEngine.isDebugEnabled()) {
buf = new StringBuffer();
buf.append("(RestApiServlet) Request headers:\n");
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
buf.append(" " + headerName + "=" + headerValue + "\n");
}
Engine.logEngine.debug(buf.toString());
Engine.logEngine.debug("(RestApiServlet) Request parameters: " + Collections.list(request.getParameterNames()));
}
// The response content
String content = null;
// Check for authentication
if (urlMappingOperation.isTargetAuthenticationContextRequired()) {
// Case Authentications are defined for mapper
if (urlAuthentications != null) {
boolean authenticated = false;
int len = urlAuthentications.size();
if (len > 0) {
for (UrlAuthentication urlAuthentication : urlAuthentications) {
// Handle Auth request
response.reset();
RequestAttribute.responseHeader.set(request, new HashMap<String, String>());
RequestAttribute.responseStatus.set(request, new HashMap<Integer, String>());
urlAuthentication.handleAuthRequest(request, response);
// Check user has been authenticated
authenticated = SessionAttribute.authenticatedUser.string(request.getSession()) != null;
if (authenticated) {
break;
}
}
// Handle User request
if (authenticated) {
response.reset();
RequestAttribute.responseHeader.set(request, new HashMap<String, String>());
RequestAttribute.responseStatus.set(request, new HashMap<Integer, String>());
content = urlMappingOperation.handleRequest(request, response);
}
} else // HTTP authentication required
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
} else // HTTP authentication required
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
} else // Handle User request
{
content = urlMappingOperation.handleRequest(request, response);
}
// Set response status
ServletUtils.applyCustomStatus(request, response);
Engine.logEngine.debug("(RestApiServlet) Response status code: " + response.getStatus());
// Set response headers
ServletUtils.applyCustomHeaders(request, response);
if (Engine.logEngine.isDebugEnabled()) {
buf = new StringBuffer();
buf.append("(RestApiServlet) Response headers:\n");
Collection<String> headerNames = response.getHeaderNames();
for (String headerName : headerNames) {
String headerValue = response.getHeader(headerName);
buf.append(" " + headerName + "=" + headerValue + "\n");
}
Engine.logEngine.debug(buf.toString());
}
// terminate session to avoid max session exceeded (case new session initiated for authentication)
if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
if (urlMappingOperation instanceof com.twinsoft.convertigo.beans.rest.AbstractRestOperation) {
com.twinsoft.convertigo.beans.rest.AbstractRestOperation aro = (com.twinsoft.convertigo.beans.rest.AbstractRestOperation) urlMappingOperation;
if (aro.isTerminateSession()) {
Engine.logEngine.debug("(RestApiServlet) requireEndOfContext because of required authentication");
request.setAttribute("convertigo.requireEndOfContext", true);
}
}
}
if (content != null) {
Writer writer = response.getWriter();
writer.write(content);
}
Engine.logEngine.debug("(RestApiServlet) Request successfully handled");
} else {
Engine.logEngine.debug("(RestApiServlet) No matching operation for request");
super.service(request, response);
}
} else {
Engine.logEngine.debug("(RestApiServlet) No mapping defined");
super.service(request, response);
}
} catch (Exception e) {
throw new ServletException(e);
} finally {
Requester requester = (Requester) request.getAttribute("convertigo.requester");
if (requester != null) {
Engine.logEngine.debug("(RestApiServlet) processRequestEnd, onFinally");
processRequestEnd(request, requester);
onFinally(request);
} else {
Engine.logEngine.debug("(RestApiServlet) terminate session");
try {
HttpUtils.terminateSession(httpSession);
} catch (Exception e) {
Engine.logEngine.warn("(RestApiServlet) unabled to terminate session", e);
}
}
long t1 = System.currentTimeMillis();
Engine.theApp.pluginsManager.fireHttpServletRequestEnd(request, t0, t1);
}
}
}
use of com.twinsoft.convertigo.engine.util.HttpServletRequestTwsWrapper in project convertigo by convertigo.
the class GenericServlet method doRequest.
protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpServletRequestTwsWrapper wrapped_request = new HttpServletRequestTwsWrapper(request);
request = wrapped_request;
String baseUrl = getServletBaseUrl(request);
boolean isProject;
if ((isProject = baseUrl.contains("/projects/")) || baseUrl.contains("/webclipper/")) {
long t0 = System.currentTimeMillis();
try {
if (EnginePropertiesManager.getPropertyAsBoolean(PropertyName.XSRF_API)) {
HttpUtils.checkXSRF(request, response);
}
String encoded = request.getParameter(Parameter.RsaEncoded.getName());
if (encoded != null) {
String query = Engine.theApp.rsaManager.decrypt(encoded, request.getSession());
wrapped_request.clearParameters();
wrapped_request.addQuery(query);
}
if (isProject && request.getMethod().equalsIgnoreCase("OPTIONS") && Engine.isStarted) {
Project project = null;
String projectName = request.getParameter(Parameter.Project.getName());
if (projectName == null) {
projectName = request.getRequestURI().replaceFirst(".*/projects/(.*?)/.*", "$1");
}
if (!projectName.contains("/")) {
try {
project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName);
} catch (Exception e) {
}
}
if (project == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
HttpUtils.applyFilterCorsHeaders(request, response, project.getCorsOrigin());
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}
Object result = processRequest(request);
response.addHeader("Expires", "-1");
if (getCacheControl(request).equals("false")) {
HeaderName.CacheControl.addHeader(response, "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
}
HttpUtils.applyCorsHeaders(request, response);
/**
* Disabled since #253 : Too much HTML Connector cookies in
* response header make a tomcat exception
* http://sourceus.twinsoft.fr/ticket/253 cookies must be in xml
* if wanted, not in headers
*
* Vector cookies = (Vector)
* request.getAttribute("convertigo.cookies"); for (int i=0;
* i<cookies.size(); i++) { String sCookie =
* (String)cookies.elementAt(i);
* response.addHeader("Set-Cookie", sCookie);
* Engine.logContext.trace("[GenericServlet] Set-Cookie: " +
* sCookie); }
*/
String trSessionId = (String) request.getAttribute("sequence.transaction.sessionid");
if ((trSessionId != null) && (!trSessionId.equals(""))) {
response.setHeader("Transaction-JSessionId", trSessionId);
}
String requested_content_type = request.getParameter(Parameter.ContentType.getName());
String content_type = getContentType(request);
if (requested_content_type != null && !requested_content_type.equals(content_type)) {
Engine.logEngine.debug("(GenericServlet) Override Content-Type requested to change : " + content_type + " to " + requested_content_type);
content_type = requested_content_type;
} else {
requested_content_type = null;
}
response.setContentType(content_type);
if (content_type.startsWith("text")) {
String charset = (String) request.getAttribute("convertigo.charset");
if (charset != null && charset.length() > 0) {
response.setCharacterEncoding(charset);
}
}
try {
if (result != null) {
Boolean b = (Boolean) request.getAttribute("convertigo.isErrorDocument");
if (b.booleanValue()) {
Requester requester = getRequester();
boolean bThrowHTTP500 = false;
if (requester instanceof WebServiceServletRequester) {
bThrowHTTP500 = Boolean.parseBoolean(EnginePropertiesManager.getProperty(EnginePropertiesManager.PropertyName.THROW_HTTP_500_SOAP_FAULT));
} else if (requester instanceof ServletRequester) {
bThrowHTTP500 = Boolean.parseBoolean(EnginePropertiesManager.getProperty(EnginePropertiesManager.PropertyName.THROW_HTTP_500));
}
if (bThrowHTTP500) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
Engine.logEngine.debug("(GenericServlet) Requested HTTP 500 status code");
}
} else {
applyCustomStatus(request, response);
}
if (result instanceof AttachmentDetails) {
AttachmentDetails attachment = (AttachmentDetails) result;
byte[] data = attachment.getData();
String contentType = attachment.getContentType();
if (requested_content_type != null) {
contentType = requested_content_type;
}
String name = attachment.getName();
HeaderName.ContentType.setHeader(response, contentType);
HeaderName.ContentLength.setHeader(response, "" + data.length);
HeaderName.ContentDisposition.setHeader(response, "attachment; filename=" + name);
applyCustomHeaders(request, response);
OutputStream out = response.getOutputStream();
out.write(data);
out.flush();
} else if (result instanceof byte[]) {
if (requested_content_type != null) {
response.setContentType(requested_content_type);
} else {
response.setContentType(getContentType(request));
response.setCharacterEncoding((String) request.getAttribute("convertigo.charset"));
}
HeaderName.ContentLength.addHeader(response, "" + ((byte[]) result).length);
applyCustomHeaders(request, response);
OutputStream out = response.getOutputStream();
out.write((byte[]) result);
out.flush();
} else {
String sResult = "";
if (result instanceof String) {
sResult = (String) result;
} else if (result instanceof Document) {
sResult = XMLUtils.prettyPrintDOM((Document) result);
} else if (result instanceof SOAPMessage) {
sResult = SOAPUtils.toString((SOAPMessage) result, (String) request.getAttribute("convertigo.charset"));
}
applyCustomHeaders(request, response);
Writer writer = response.getWriter();
writer.write(sResult);
writer.flush();
}
} else {
applyCustomHeaders(request, response);
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
} catch (IOException e) {
// The connection has probably been reset by peer
Engine.logContext.warn("[GenericServlet] The connection has probably been reset by peer (IOException): " + e.getMessage());
} finally {
onFinally(request);
}
} catch (Exception e) {
Engine.logContext.error("Unable to process the request!", e);
processException(request, response, e);
} finally {
long t1 = System.currentTimeMillis();
Engine.theApp.pluginsManager.fireHttpServletRequestEnd(request, t0, t1);
}
} else {
// Not a valid Convertigo invocation URL, use retrieve as static
// resource
handleStaticData(request, response);
return;
}
}
Aggregations