diff --git a/pom.xml b/pom.xml index aef54e3c..597ab496 100644 --- a/pom.xml +++ b/pom.xml @@ -1,289 +1,287 @@ - - 4.0.0 - com.metamug - mason - 3.3 - jar - com.metamug:mason - API SDK - https://metamug.com - - UTF-8 - 1.8 - 1.8 - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - Anish Hirlekar - anish.hirlekar@metamug.com - Metamug Technologies - http://www.metamug.com - - Developer - - +5:30 - - - Deepak Mishra - deepak.mishra@metamug.com - Metamug Technologies - http://www.metamug.com - - Developer - - +5:30 - - - Kaustubh Damle - kaustubh.damle@metamug.com - Metamug Technologies - http://www.metamug.com - - Developer - - +5:30 - - - - scm:git:git@github.com:metamug/mason.git - scm:git:git@github.com:metamug/mason.git - git@github.com:metamug/mason.git - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - release - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - true - true - true - true - true - -Xdoclint:none - - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - true - false - release - deploy - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - sign-artifacts - verify - - sign - - - - + + 4.0.0 + com.metamug + mason + 3.3 + jar + com.metamug:mason + API SDK + https://metamug.com + + UTF-8 + 1.8 + 1.8 + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + Anish Hirlekar + anish.hirlekar@metamug.com + Metamug Technologies + http://www.metamug.com + + Developer + + +5:30 + + + Deepak Mishra + deepak.mishra@metamug.com + Metamug Technologies + http://www.metamug.com + + Developer + + +5:30 + + + Kaustubh Damle + kaustubh.damle@metamug.com + Metamug Technologies + http://www.metamug.com + + Developer + + +5:30 + + + + scm:git:git@github.com:metamug/mason.git + scm:git:git@github.com:metamug/mason.git + git@github.com:metamug/mason.git + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + release + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + true + true + true + true + true + -Xdoclint:none + + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.3 + + true + false + release + deploy + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.7 + true + + ossrh + https://oss.sonatype.org/ + true + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + - - - org.eluder.coveralls - coveralls-maven-plugin - 4.3.0 - - - org.jacoco - jacoco-maven-plugin - 0.7.9 - - - - prepare-agent - - - - report - prepare-package - - report - - - - prepare-integration-test-agent - - prepare-agent-integration - - - - generate-integration-test-report - - report-integration - - - - - - - - - - - - org.codehaus.groovy - groovy-all - 2.4.15 - - - org.apache.ivy - ivy - 2.4.0 - - - com.squareup.okhttp3 - okhttp - 3.10.0 - - - mysql - mysql-connector-java - 8.0.15 - - - com.google.protobuf - protobuf-java - - - - - org.json - json - 20180813 - - - com.github.wnameless.json - json-flattener - 0.7.1 - - - org.apache.commons - commons-text - 1.6 - - - org.eclipse.persistence - org.eclipse.persistence.moxy - 2.6.4 - - - javax.servlet - jstl - 1.2 - - - junit - junit - 4.12 - test - - - org.mockito - mockito-all - 1.10.19 - test - - - org.hamcrest - hamcrest-core - 1.3 - test - - - javax.servlet - javax.servlet-api - 4.0.1 - - - com.metamug - mtg-api - 1.5 - - - javax - javaee-web-api - 8.0 - - - com.jayway.jsonpath - json-path - 2.4.0 - - - + + org.eluder.coveralls + coveralls-maven-plugin + 4.3.0 + + + org.jacoco + jacoco-maven-plugin + 0.7.9 + + + + prepare-agent + + + + report + prepare-package + + report + + + + prepare-integration-test-agent + + prepare-agent-integration + + + + generate-integration-test-report + + report-integration + + + + + + + + + + + org.codehaus.groovy + groovy-all + 2.4.15 + + + org.apache.ivy + ivy + 2.4.0 + + + com.squareup.okhttp3 + okhttp + 3.10.0 + + + mysql + mysql-connector-java + 8.0.15 + + + com.google.protobuf + protobuf-java + + + + + org.json + json + 20180813 + + + com.github.wnameless.json + json-flattener + 0.7.1 + + + org.apache.commons + commons-text + 1.6 + + + org.eclipse.persistence + org.eclipse.persistence.moxy + 2.6.4 + + + javax.servlet + jstl + 1.2 + + + junit + junit + 4.12 + test + + + org.mockito + mockito-all + 1.10.19 + test + + + org.hamcrest + hamcrest-core + 1.3 + test + + + javax.servlet + javax.servlet-api + 4.0.1 + + + com.metamug + mtg-api + 1.5 + + + javax + javaee-web-api + 8.0 + + + com.jayway.jsonpath + json-path + 2.4.0 + + + \ No newline at end of file diff --git a/src/main/java/com/metamug/mason/Router.java b/src/main/java/com/metamug/mason/Router.java index 1a7cfcd0..a3f905d5 100644 --- a/src/main/java/com/metamug/mason/Router.java +++ b/src/main/java/com/metamug/mason/Router.java @@ -506,17 +506,22 @@ */ package com.metamug.mason; -import com.metamug.entity.Request; -import com.metamug.mason.entity.RootResource; import static com.metamug.mason.entity.request.FormStrategy.APPLICATION_FORM_URLENCODED; import static com.metamug.mason.entity.request.HtmlStrategy.APPLICATION_HTML; import static com.metamug.mason.entity.request.JsonStrategy.APPLICATION_JSON; -import com.metamug.mason.entity.request.RequestAdapter; import static com.metamug.mason.entity.request.MultipartFormStrategy.MULTIPART_FORM_DATA; +import static com.metamug.mason.tag.ResourceTagHandler.MSG_RESOURCE_NOT_FOUND; + +import com.metamug.entity.Request; +import com.metamug.mason.entity.RootResource; +import com.metamug.mason.entity.request.RequestAdapter; import com.metamug.mason.service.AuthService; import com.metamug.mason.service.ConnectionProvider; import com.metamug.mason.service.QueryManagerService; -import static com.metamug.mason.tag.ResourceTagHandler.MSG_RESOURCE_NOT_FOUND; + +import org.json.JSONException; +import org.json.JSONObject; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -524,6 +529,7 @@ import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; + import javax.naming.NamingException; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -532,237 +538,234 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.MultipartConfig; +import javax.servlet.annotation.WebFilter; +import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; -import org.json.JSONException; -import org.json.JSONObject; /** * Rest Controller. Handles all the incoming requests * * @author Kaisteel */ +@WebFilter(urlPatterns = "/rest/*", filterName = "Router", description = "Default REST filter", initParams = { + @WebInitParam(name = "datasource", value = "jdbc/mason") }) @MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 25) public class Router implements Filter { - private static final String JSP_EXTN = ".jsp"; - private static final String RESOURCES_FOLDER = "/WEB-INF/resources/"; - private String encoding; - - public static final String HEADER_CONTENT_TYPE = "Content-Type"; - public static final String QUERY_FILE_NAME = "query.properties"; - public static final String MASON_QUERY = "masonQuery"; //to hold queries from properties file - public static final String DATA_SOURCE = "datasource"; - public static final String MTG_AUTH_BASIC = "MTG_AUTH_BASIC"; - public static final String MTG_AUTH_BEARER = "MTG_AUTH_BEARER"; - - private ConnectionProvider connectionProvider; - public static final String CONNECTION_PROVIDER = "connectionProvider"; - public static final String MASON_REQUEST = "mtgReq"; - - public Router() { - - } - - /** - * - * @param request The servlet request we are processing - * @param response The servlet response we are creating - * @param chain The filter chain we are processing - * - * @exception IOException if an input/output error occurs - * @exception ServletException if a servlet error occurs - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - HttpServletRequest req = (HttpServletRequest) request; - HttpServletResponse res = (HttpServletResponse) response; - //Setting character encoding - if (null == request.getCharacterEncoding()) { - request.setCharacterEncoding(encoding); - } - - String path = req.getServletPath(); - String[] tokens = path.split("/"); - int versionTokenIndex = -1; - for (int i = 0; i < tokens.length; i++) { - if (tokens[i].matches("^.*(v\\d+\\.\\d+).*$")) { - versionTokenIndex = i; - break; - } - } - //check auth request - if (versionTokenIndex == -1 && req.getMethod().equalsIgnoreCase("post") && !path.contains("query")) { - RootResource rootResource = new RootResource(req, res); - rootResource.processAuth(new AuthService(connectionProvider)); - return; - } - if (tokens.length <= 2 || path.contains("index") || path.contains("docs")) { - chain.doFilter(request, response); - return; - } - processRequest(req, res); - } - - /** - * Servlet version of the request handling. Cast objects to handle REST - * request - * - * @param req - * @param res - * @param tokens The URI split by / - * @throws IOException - */ - private void processRequest(HttpServletRequest req, HttpServletResponse res) - throws IOException { - - String contentType = req.getContentType() == null ? APPLICATION_HTML : req.getContentType().toLowerCase(); - String method = req.getMethod().toLowerCase(); - - boolean validContentType = contentType.contains(APPLICATION_HTML) || contentType.contains("application/xml") - || contentType.contains(APPLICATION_FORM_URLENCODED) || contentType.contains(APPLICATION_JSON) || contentType.contains(MULTIPART_FORM_DATA); - - if (!"get".equals(method) && !"delete".equals(method) && !validContentType) { - writeError(res, 415, "Unsupported Media Type"); //methods having content(POST,DELETE) in body, sent with invalid contentType - return; - } - - res.setContentType(APPLICATION_JSON); - //requesting a REST resource - String resourceName = ""; - try { - //get queries - Request mtgReq = RequestAdapter.create(req); - resourceName = mtgReq.getResource().getName(); - - String jspPath = RESOURCES_FOLDER + "v" + mtgReq.getResource().getVersion() + "/" + resourceName + JSP_EXTN; - File file = new File(req.getServletContext().getRealPath(jspPath)); - - if(file.exists()) { - req.setAttribute(MASON_REQUEST, mtgReq); - - //Adding to request, otherwise the user has to write ${applicationScope.datasource} - req.setAttribute(DATA_SOURCE, req.getServletContext().getAttribute(DATA_SOURCE)); - req.setAttribute(CONNECTION_PROVIDER, connectionProvider); - - //Query map of stored queries in a file - Object queryMap = req.getServletContext().getAttribute(MASON_QUERY); - req.setAttribute(MASON_QUERY, queryMap); - - //save method as attribute because jsp only accepts GET and POST - //https://stackoverflow.com/a/46489035 - req.setAttribute("mtgMethod", req.getMethod()); //needed by ExceptionTagHandler - req.getRequestDispatcher(jspPath).forward( - new HttpServletRequestWrapper(req) { - @Override - public String getMethod() { - String method = super.getMethod(); - if (method.equalsIgnoreCase("delete") || method.equalsIgnoreCase("put")) { - return "POST"; - } else { - return method; - } - } - }, res - ); - } else { - writeError(res, 404, MSG_RESOURCE_NOT_FOUND); - } - - } catch (IOException | ServletException | JSONException ex) { - if (ex.getClass().toString().contains("com.eclipsesource.json.ParseException")) { - writeError(res, 422, "Could not parse the body of the request according to the provided Content-Type."); - } else if (ex.getCause() != null) { - String cause = ex.getCause().toString().split(": ")[1].replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); - writeError(res, 500, cause); - } else if (ex.getMessage().contains("ELException")) { - writeError(res, 512, "Incorrect test condition in '" + resourceName + "' resource"); - } else { - writeError(res, 500, ex.getMessage().replaceAll("(\\s|\\n|\\r|\\n\\r)+", " ")); - Logger.getLogger(Router.class.getName()).log(Level.SEVERE, "Router " + resourceName + ":{0}", ex.getMessage()); - } - Logger.getLogger(Router.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } catch (NullPointerException ex) { - Logger.getLogger(Router.class.getName()).log(Level.SEVERE, "Router " + resourceName + ":{0}", ex.getMessage()); - //The 404error.jsp works fine when a non-existing resource is called. But requesting a dispatcher for non-existing resource it returns Null during test executiong and a call to forward() on such a dispatcher creates NPE and the RouterTest fails. This catch if for that. - writeError(res, 404, "Resource doesn't exist." + ex.getMessage()); - } - } - - /** - * Error message to be returned - * - * @param res HTTP Response - * @param status Http Status Code - * @param message Message in Response - * @throws IOException - */ - private void writeError(HttpServletResponse res, int status, String message) throws IOException { - - try (PrintWriter writer = res.getWriter()) { - res.setContentType("application/json;charset=UTF-8"); - res.setCharacterEncoding("UTF-8"); - res.setStatus(status); - JSONObject obj = new JSONObject(); - obj.put("status", status); - obj.put("message", message); - writer.print(obj.toString()); - writer.flush(); - } - } - - /** - * Destroy method for this filter - */ - @Override - public void destroy() { - try { - connectionProvider.shutdown(); - } catch (SQLException | NamingException ex) { - Logger.getLogger(Router.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } - } - - /** - * Init method for this filter - * - * @param config - */ - @Override - public void init(FilterConfig config) { - encoding = config.getInitParameter("requestEncoding"); - if (encoding == null) { - encoding = "UTF-8"; - } - - if (config.getInitParameter(DATA_SOURCE) != null) { - config.getServletContext().setAttribute(DATA_SOURCE, config.getInitParameter("datasource")); - } else { - config.getServletContext().setAttribute(DATA_SOURCE, "jdbc/mason"); - } - - if (config.getInitParameter(MTG_AUTH_BASIC) != null) { - config.getServletContext().setAttribute(MTG_AUTH_BASIC, config.getInitParameter(MTG_AUTH_BASIC)); - } - if (config.getInitParameter(MTG_AUTH_BEARER) != null) { - config.getServletContext().setAttribute(MTG_AUTH_BEARER, config.getInitParameter(MTG_AUTH_BEARER)); - } - - InputStream queryFileInputStream = Router.class.getClassLoader().getResourceAsStream(QUERY_FILE_NAME); - QueryManagerService queryManagerService = new QueryManagerService(queryFileInputStream); - - try { - connectionProvider = new ConnectionProvider((String) config.getServletContext().getAttribute(DATA_SOURCE)); - //connectionProvider.getMasonDatasource(); - config.getServletContext().setAttribute(MASON_QUERY, queryManagerService.getQueryMap()); - config.getServletContext().setAttribute(CONNECTION_PROVIDER, connectionProvider); - queryFileInputStream.close(); - } catch (IOException | SQLException | NamingException ex) { - Logger.getLogger(Router.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } catch (NullPointerException nx) { - //Logger.getLogger(Router.class.getName()).log(Level.SEVERE, QUERY_FILE_NAME + " file does not exist!", nx); - } - } + private static final String JSP_EXTN = ".jsp"; + private static final String RESOURCES_FOLDER = "/WEB-INF/resources/"; + private String encoding; + + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + public static final String QUERY_FILE_NAME = "query.properties"; + public static final String MASON_QUERY = "masonQuery"; // to hold queries from properties file + public static final String DATA_SOURCE = "datasource"; + public static final String MTG_AUTH_BASIC = "MTG_AUTH_BASIC"; + public static final String MTG_AUTH_BEARER = "MTG_AUTH_BEARER"; + + private ConnectionProvider connectionProvider; + public static final String CONNECTION_PROVIDER = "connectionProvider"; + public static final String MASON_REQUEST = "mtgReq"; + + public Router() { + + } + + /** + * + * @param request The servlet request we are processing + * @param response The servlet response we are creating + * @param chain The filter chain we are processing + * + * @exception IOException if an input/output error occurs + * @exception ServletException if a servlet error occurs + */ + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse res = (HttpServletResponse) response; + // Setting character encoding + if (null == request.getCharacterEncoding()) { + request.setCharacterEncoding(encoding); + } + + String path = req.getServletPath(); + String[] tokens = path.split("/"); + int versionTokenIndex = -1; + for (int i = 0; i < tokens.length; i++) { + if (tokens[i].matches("^.*(v\\d+\\.\\d+).*$")) { + versionTokenIndex = i; + break; + } + } + // check auth request + if (versionTokenIndex == -1 && req.getMethod().equalsIgnoreCase("post") && !path.contains("query")) { + RootResource rootResource = new RootResource(req, res); + rootResource.processAuth(new AuthService(connectionProvider)); + return; + } + if (tokens.length <= 2 || path.contains("index") || path.contains("docs")) { + chain.doFilter(request, response); + return; + } + processRequest(req, res); + } + + /** + * Servlet version of the request handling. Cast objects to handle REST request + * + * @param req + * @param res + * @throws IOException + */ + private void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException { + + String contentType = req.getContentType() == null ? APPLICATION_HTML : req.getContentType().toLowerCase(); + String method = req.getMethod().toLowerCase(); + + boolean validContentType = contentType.contains(APPLICATION_HTML) || contentType.contains("application/xml") + || contentType.contains(APPLICATION_FORM_URLENCODED) || contentType.contains(APPLICATION_JSON) + || contentType.contains(MULTIPART_FORM_DATA); + + if (!"get".equals(method) && !"delete".equals(method) && !validContentType) { + writeError(res, 415, "Unsupported Media Type"); //methods having content(POST,DELETE) in body, sent with invalid contentType + return; + } + + res.setContentType(APPLICATION_JSON); + // requesting a REST resource + String resourceName = ""; + try { + // get queries + Request mtgReq = RequestAdapter.create(req); + resourceName = mtgReq.getResource().getName(); + + String jspPath = RESOURCES_FOLDER + "v" + mtgReq.getResource().getVersion() + "/" + resourceName + JSP_EXTN; + File file = new File(req.getServletContext().getRealPath(jspPath)); + + if (file.exists()) { + req.setAttribute(MASON_REQUEST, mtgReq); + + //Adding to request, otherwise the user has to write ${applicationScope.datasource} + req.setAttribute(DATA_SOURCE, req.getServletContext().getAttribute(DATA_SOURCE)); + req.setAttribute(CONNECTION_PROVIDER, connectionProvider); + + // Query map of stored queries in a file + Object queryMap = req.getServletContext().getAttribute(MASON_QUERY); + req.setAttribute(MASON_QUERY, queryMap); + + // save method as attribute because jsp only accepts GET and POST + // https://stackoverflow.com/a/46489035 + req.setAttribute("mtgMethod", req.getMethod()); // needed by ExceptionTagHandler + req.getRequestDispatcher(jspPath).forward(new HttpServletRequestWrapper(req) { + @Override + public String getMethod() { + String method = super.getMethod(); + if (method.equalsIgnoreCase("delete") || method.equalsIgnoreCase("put")) { + return "POST"; + } else { + return method; + } + } + }, res); + } else { + writeError(res, 404, MSG_RESOURCE_NOT_FOUND); + } + + } catch (IOException | ServletException | JSONException ex) { + if (ex.getClass().toString().contains("com.eclipsesource.json.ParseException")) { + writeError(res, 422, "Could not parse the body of the request according to the provided Content-Type."); + } else if (ex.getCause() != null) { + String cause = ex.getCause().toString().split(": ")[1].replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); + writeError(res, 500, cause); + } else if (ex.getMessage().contains("ELException")) { + writeError(res, 512, "Incorrect test condition in '" + resourceName + "' resource"); + } else { + writeError(res, 500, ex.getMessage().replaceAll("(\\s|\\n|\\r|\\n\\r)+", " ")); + Logger.getLogger(Router.class.getName()).log(Level.SEVERE, "Router " + resourceName + ":{0}", ex.getMessage()); + } + Logger.getLogger(Router.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } catch (NullPointerException ex) { + Logger.getLogger(Router.class.getName()).log(Level.SEVERE, "Router " + resourceName + ":{0}", ex.getMessage()); + //The 404error.jsp works fine when a non-existing resource is called. But requesting a dispatcher for non-existing resource it returns Null during test executiong and a call to forward() on such a dispatcher creates NPE and the RouterTest fails. This catch if for that. + writeError(res, 404, "Resource doesn't exist." + ex.getMessage()); + } + } + + /** + * Error message to be returned + * + * @param res HTTP Response + * @param status HTTP Status Code + * @param message Message in Response + * @throws IOException + */ + private void writeError(HttpServletResponse res, int status, String message) throws IOException { + + try (PrintWriter writer = res.getWriter()) { + res.setContentType("application/json;charset=UTF-8"); + res.setCharacterEncoding("UTF-8"); + res.setStatus(status); + JSONObject obj = new JSONObject(); + obj.put("status", status); + obj.put("message", message); + writer.print(obj.toString()); + writer.flush(); + } + } + + /** + * Destroy method for this filter + */ + @Override + public void destroy() { + try { + connectionProvider.shutdown(); + } catch (SQLException | NamingException ex) { + Logger.getLogger(Router.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } + } + + /** + * Init method for this filter + * + * @param config + */ + @Override + public void init(FilterConfig config) { + encoding = config.getInitParameter("requestEncoding"); + if (encoding == null) { + encoding = "UTF-8"; + } + + if (config.getInitParameter(DATA_SOURCE) != null) { + config.getServletContext().setAttribute(DATA_SOURCE, config.getInitParameter(DATA_SOURCE)); + } else { + config.getServletContext().setAttribute(DATA_SOURCE, "jdbc/mason"); + } + + if (config.getInitParameter(MTG_AUTH_BASIC) != null) { + config.getServletContext().setAttribute(MTG_AUTH_BASIC, config.getInitParameter(MTG_AUTH_BASIC)); + } + if (config.getInitParameter(MTG_AUTH_BEARER) != null) { + config.getServletContext().setAttribute(MTG_AUTH_BEARER, config.getInitParameter(MTG_AUTH_BEARER)); + } + + InputStream queryFileInputStream = Router.class.getClassLoader().getResourceAsStream(QUERY_FILE_NAME); + QueryManagerService queryManagerService = new QueryManagerService(queryFileInputStream); + + try { + connectionProvider = new ConnectionProvider((String) config.getServletContext().getAttribute(DATA_SOURCE)); + config.getServletContext().setAttribute(MASON_QUERY, queryManagerService.getQueryMap()); + config.getServletContext().setAttribute(CONNECTION_PROVIDER, connectionProvider); + queryFileInputStream.close(); + } catch (IOException | SQLException | NamingException ex) { + Logger.getLogger(Router.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } catch (NullPointerException nx) { + Logger.getLogger(Router.class.getName()).log(Level.SEVERE, QUERY_FILE_NAME + " file does not exist!", nx); + } + } } diff --git a/src/main/java/com/metamug/mason/entity/auth/JWebToken.java b/src/main/java/com/metamug/mason/entity/auth/JWebToken.java index fbe2e491..6ac2fb0f 100644 --- a/src/main/java/com/metamug/mason/entity/auth/JWebToken.java +++ b/src/main/java/com/metamug/mason/entity/auth/JWebToken.java @@ -506,6 +506,10 @@ */ package com.metamug.mason.entity.auth; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -517,11 +521,9 @@ import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; + import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; /** * @@ -529,119 +531,118 @@ */ public class JWebToken { - private static final String SECRET_KEY = "FREE_MASON"; //@TODO Add Signature here - private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); - private static final String ISSUER = "mason.metamug.net"; - private static final String JWT_HEADER = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}"; - private JSONObject payload = new JSONObject(); - private String signature; - private String encodedHeader; + private static final String SECRET_KEY = "FREE_MASON"; // @TODO Add Signature here + private static final String ISSUER = "mason.metamug.net"; + private static final String JWT_HEADER = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}"; + private JSONObject payload = new JSONObject(); + private String signature; + private String encodedHeader; - private JWebToken() { - encodedHeader = encode(new JSONObject(JWT_HEADER)); - } + private JWebToken() { + encodedHeader = encode(new JSONObject(JWT_HEADER)); + } - public JWebToken(JSONObject payload) { - this(payload.getString("sub"), payload.getJSONArray("aud"), payload.getLong("exp")); - } + public JWebToken(JSONObject payload) { + this(payload.getString("sub"), payload.getJSONArray("aud"), payload.getLong("exp")); + } - public JWebToken(String sub, JSONArray aud, long expires) { - this(); - payload.put("sub", sub); - payload.put("aud", aud); - payload.put("exp", expires); - payload.put("iat", LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)); - payload.put("iss", ISSUER); - payload.put("jti", UUID.randomUUID().toString()); //how do we use this? - signature = hmacSha256(encodedHeader + "." + encode(payload), SECRET_KEY); - } + public JWebToken(String sub, JSONArray aud, long expires) { + this(); + payload.put("sub", sub); + payload.put("aud", aud); + payload.put("exp", expires); + payload.put("iat", LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)); + payload.put("iss", ISSUER); + payload.put("jti", UUID.randomUUID().toString()); // how do we use this? + signature = hmacSha256(encodedHeader + "." + encode(payload), SECRET_KEY); + } - /** - * For verification - * - * @param token - * @throws java.security.NoSuchAlgorithmException - */ - public JWebToken(String token) throws NoSuchAlgorithmException { - this(); - String[] parts = token.split("\\."); - if (parts.length != 3) { - throw new IllegalArgumentException("Invalid Token format"); - } - if (encodedHeader.equals(parts[0])) { - encodedHeader = parts[0]; - } else { - throw new NoSuchAlgorithmException("JWT Header is Incorrect: " + parts[0]); - } + /** + * For verification + * + * @param token + * @throws java.security.NoSuchAlgorithmException + */ + public JWebToken(String token) throws NoSuchAlgorithmException { + this(); + String[] parts = token.split("\\."); + if (parts.length != 3) { + throw new IllegalArgumentException("Invalid Token format"); + } + if (encodedHeader.equals(parts[0])) { + encodedHeader = parts[0]; + } else { + throw new NoSuchAlgorithmException("JWT Header is Incorrect: " + parts[0]); + } - payload = new JSONObject(decode(parts[1])); - if (payload.isEmpty()) { - throw new JSONException("Payload is Empty: "); - } - if (!payload.has("exp")) { - throw new JSONException("Payload doesn't contain expiry " + payload); - } - signature = parts[2]; - } + payload = new JSONObject(decode(parts[1])); + if (payload.isEmpty()) { + throw new JSONException("Payload is Empty: "); + } + if (!payload.has("exp")) { + throw new JSONException("Payload doesn't contain expiry " + payload); + } + signature = parts[2]; + } - @Override - public String toString() { - return encodedHeader + "." + encode(payload) + "." + signature; - } + @Override + public String toString() { + return encodedHeader + "." + encode(payload) + "." + signature; + } - public boolean isValid() { - return payload.getLong("exp") > (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)) //token not expired - && signature.equals(hmacSha256(encodedHeader + "." + encode(payload), SECRET_KEY)); //signature matched - } + public boolean isValid() { + return payload.getLong("exp") > (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)) // token not expired + && signature.equals(hmacSha256(encodedHeader + "." + encode(payload), SECRET_KEY)); // signature matched + } - public String getSubject() { - return payload.getString("sub"); - } + public String getSubject() { + return payload.getString("sub"); + } - public List getAudience() { - JSONArray arr = payload.getJSONArray("aud"); - List list = new ArrayList<>(); - for (int i = 0; i < arr.length(); i++) { - list.add(arr.getString(i)); - } - return list; - } + public List getAudience() { + JSONArray arr = payload.getJSONArray("aud"); + List list = new ArrayList<>(); + for (int i = 0; i < arr.length(); i++) { + list.add(arr.getString(i)); + } + return list; + } - private static String encode(JSONObject obj) { - return encode(obj.toString().getBytes(StandardCharsets.UTF_8)); - } + private static String encode(JSONObject obj) { + return encode(obj.toString().getBytes(StandardCharsets.UTF_8)); + } - private static String encode(byte[] bytes) { - return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); - } + private static String encode(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } - private static String decode(String encodedString) { - return new String(Base64.getUrlDecoder().decode(encodedString)); - } + private static String decode(String encodedString) { + return new String(Base64.getUrlDecoder().decode(encodedString)); + } - /** - * Sign with HMAC SHA256 (HS256) - * - * @param data - * @return - * @throws Exception - */ - private String hmacSha256(String data, String secret) { - try { + /** + * Sign with HMAC SHA256 (HS256) + * + * @param data + * @return + * @throws Exception + */ + private String hmacSha256(String data, String secret) { + try { - //MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] hash = secret.getBytes(StandardCharsets.UTF_8);//digest.digest(secret.getBytes(StandardCharsets.UTF_8)); + // MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = secret.getBytes(StandardCharsets.UTF_8);// digest.digest(secret.getBytes(StandardCharsets.UTF_8)); - Mac sha256Hmac = Mac.getInstance("HmacSHA256"); - SecretKeySpec secretKey = new SecretKeySpec(hash, "HmacSHA256"); - sha256Hmac.init(secretKey); + Mac sha256Hmac = Mac.getInstance("HmacSHA256"); + SecretKeySpec secretKey = new SecretKeySpec(hash, "HmacSHA256"); + sha256Hmac.init(secretKey); - byte[] signedBytes = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8)); - return encode(signedBytes); - } catch (NoSuchAlgorithmException | InvalidKeyException ex) { - Logger.getLogger(JWebToken.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - return null; - } - } + byte[] signedBytes = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8)); + return encode(signedBytes); + } catch (NoSuchAlgorithmException | InvalidKeyException ex) { + Logger.getLogger(JWebToken.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + return null; + } + } } diff --git a/src/main/java/com/metamug/mason/entity/response/JSONOutput.java b/src/main/java/com/metamug/mason/entity/response/JSONOutput.java index 07881bce..c5d37506 100644 --- a/src/main/java/com/metamug/mason/entity/response/JSONOutput.java +++ b/src/main/java/com/metamug/mason/entity/response/JSONOutput.java @@ -506,125 +506,128 @@ */ package com.metamug.mason.entity.response; -import com.metamug.entity.Response; -import com.metamug.mason.io.mpath.MPathUtil; -import com.metamug.mason.io.objectreturn.ObjectReturn; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.logging.Level; import java.util.logging.Logger; + import javax.xml.bind.JAXBException; import javax.xml.bind.MarshalException; + import org.apache.taglibs.standard.tag.common.sql.ResultImpl; import org.json.JSONArray; import org.json.JSONObject; +import com.metamug.entity.Response; +import com.metamug.mason.io.mpath.MPathUtil; +import com.metamug.mason.io.objectreturn.ObjectReturn; + /** * JSONs Output Object */ public class JSONOutput extends MasonOutput{ - @Override - protected JSONObject getContent() { - JSONObject responseJson = new JSONObject(); - outputMap.entrySet().forEach( entry -> { - Object obj = entry.getValue(); - String key = entry.getKey(); - if(obj == null) { - responseJson.put(key, new JSONObject()); - } else if (obj instanceof ResultImpl) { - responseJson.put(key, getJson((ResultImpl) obj)); - } else if (obj instanceof JSONObject) { - responseJson.put(key, obj); - } else if (obj instanceof JSONArray) { - responseJson.put(key, obj); - } else if (obj instanceof String) { - responseJson.put(key, obj); - } else if (obj instanceof List) { - JSONArray array = new JSONArray(); + @Override + protected JSONObject getContent() { + JSONObject responseJson = new JSONObject(); + outputMap.entrySet().forEach( entry -> { + Object obj = entry.getValue(); + String key = entry.getKey(); + if(obj == null) { + responseJson.put(key, new JSONObject()); + } else if (obj instanceof ResultImpl) { + responseJson.put(key, getJson((ResultImpl) obj)); + } else if (obj instanceof JSONObject) { + responseJson.put(key, obj); + } else if (obj instanceof JSONArray) { + responseJson.put(key, obj); + } else if (obj instanceof String) { + responseJson.put(key, obj); + } else if (obj instanceof List) { + JSONArray array = new JSONArray(); List list = (List)obj; - for (Object o : list) { - if(o == null){ - array.put(new JSONObject()); - } else if(o instanceof String || o instanceof JSONObject || o instanceof JSONArray) { - array.put(o); - } else if (o instanceof ResultImpl) { - array.put(getJson((ResultImpl) o)); - } else { - // for POJO - try { - array.put(new JSONObject(ObjectReturn.convert(o, HEADER_JSON))); - } catch (JAXBException ex) { - //@TODO Do something here - Logger.getLogger(JSONOutput.class.getName()).log(Level.SEVERE, null, ex); - } - } - } - responseJson.put(key, array); - } else { - //obj is POJO - try { - //try if object of JAXB class - responseJson.put(key, new JSONObject(ObjectReturn.convert(obj, HEADER_JSON))); - } catch (MarshalException mex) { - responseJson.put(key, obj); - } catch (JAXBException ex) { - Logger.getLogger(JSONOutput.class.getName()).log(Level.SEVERE, null, ex); - } - } - }); - return responseJson; - } + for (Object o : list) { + if(o == null){ + array.put(new JSONObject()); + } else if(o instanceof String || o instanceof JSONObject || o instanceof JSONArray) { + array.put(o); + } else if (o instanceof ResultImpl) { + array.put(getJson((ResultImpl) o)); + } else { + // for POJO + try { + array.put(new JSONObject(ObjectReturn.convert(o, HEADER_JSON))); + } catch (JAXBException ex) { + //@TODO Do something here + Logger.getLogger(JSONOutput.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + responseJson.put(key, array); + } else { + //obj is POJO + try { + //try if object of JAXB class + responseJson.put(key, new JSONObject(ObjectReturn.convert(obj, HEADER_JSON))); + } catch (MarshalException mex) { + responseJson.put(key, obj); + } catch (JAXBException ex) { + Logger.getLogger(JSONOutput.class.getName()).log(Level.SEVERE, null, ex); + } + } + }); + return responseJson; + } - @Override - public String format(Response response) { - JSONObject responseJson = (JSONObject) response.getPayload(); - return responseJson.toString(); - } + @Override + public String format(Response response) { + JSONObject responseJson = (JSONObject) response.getPayload(); + return responseJson.toString(); + } - protected Object getJson(ResultImpl impl) { - return resultSetToJson(impl); - } + protected Object getJson(ResultImpl impl) { + return resultSetToJson(impl); + } - private JSONArray resultSetToJson(ResultImpl resultImpl) { - SortedMap[] rows = resultImpl.getRows(); - String[] columnNames = resultImpl.getColumnNames(); - JSONArray array = new JSONArray(); - for (SortedMap row : rows) { - JSONObject rowJson = new JSONObject(); - for (int i = 0; i < columnNames.length; i++) { - String columnName = columnNames[i].isEmpty() || columnNames[i].equalsIgnoreCase("null") ? "col" + i : columnNames[i]; - rowJson = MPathUtil.appendJsonFromMPath(rowJson, columnName, (row.get(columnName) != null) ? row.get(columnName) : JSONObject.NULL); - /*if (entry.getKey().startsWith("p")) { + private JSONArray resultSetToJson(ResultImpl resultImpl) { + SortedMap[] rows = resultImpl.getRows(); + String[] columnNames = resultImpl.getColumnNames(); + JSONArray array = new JSONArray(); + for (SortedMap row : rows) { + JSONObject rowJson = new JSONObject(); + for (int i = 0; i < columnNames.length; i++) { + String columnName = columnNames[i].isEmpty() || columnNames[i].equalsIgnoreCase("null") ? "col" + i : columnNames[i]; + rowJson = MPathUtil.appendJsonFromMPath(rowJson, columnName, (row.get(columnName) != null) ? row.get(columnName) : JSONObject.NULL); + /*if (entry.getKey().startsWith("p")) { params.put(columnName, String.valueOf((row.get(columnName) != null) ? row.get(columnName) : JSONObject.NULL)); }*/ - } - if (rowJson.length() > 0) { - array.put(rowJson); - } - } - // if (array.length() > 0) { - // if (entry.getKey().startsWith("d")) { - // if (entry.getKey().startsWith("c")) { - // responseJson.put("response", MPathUtil.collect(array)); - // } else { - // responseJson.put("response", array); - // } - // } - // } - return array; - } + } + if (rowJson.length() > 0) { + array.put(rowJson); + } + } + // if (array.length() > 0) { + // if (entry.getKey().startsWith("d")) { + // if (entry.getKey().startsWith("c")) { + // responseJson.put("response", MPathUtil.collect(array)); + // } else { + // responseJson.put("response", array); + // } + // } + // } + return array; + } - @Override - public String getContentType() { - return HEADER_JSON; - } + @Override + public String getContentType() { + return HEADER_JSON; + } - @Override - protected Map getExtraHeaders() { - return new HashMap<>(); - } + @Override + protected Map getExtraHeaders() { + return new HashMap<>(); + } } diff --git a/src/main/java/com/metamug/mason/exception/MasonException.java b/src/main/java/com/metamug/mason/exception/MasonException.java index 2efabf17..31e50170 100644 --- a/src/main/java/com/metamug/mason/exception/MasonException.java +++ b/src/main/java/com/metamug/mason/exception/MasonException.java @@ -512,38 +512,39 @@ */ public class MasonException extends Exception { - private final MasonError error; - private final Exception rootException; + private static final long serialVersionUID = 1L; + private final MasonError error; + private final Exception rootException; - public MasonException(MasonError error) { - super(error.getMsg()); - this.error = error; - this.rootException = null; - } + public MasonException(MasonError error) { + super(error.getMsg()); + this.error = error; + this.rootException = null; + } - public MasonException(MasonError error, String msg) { - super(msg); - this.error = error; - this.rootException = null; - } + public MasonException(MasonError error, String msg) { + super(msg); + this.error = error; + this.rootException = null; + } - public MasonException(MasonError error, Exception root) { - super(error.getMsg()); - this.error = error; - this.rootException = root; - } + public MasonException(MasonError error, Exception root) { + super(error.getMsg()); + this.error = error; + this.rootException = root; + } - public MasonException(MasonError error, Exception root, String msg) { - super(msg); - this.error = error; - this.rootException = root; - } + public MasonException(MasonError error, Exception root, String msg) { + super(msg); + this.error = error; + this.rootException = root; + } - public MasonError getError() { - return this.error; - } + public MasonError getError() { + return this.error; + } - public Exception getRootException() { - return this.rootException; - } + public Exception getRootException() { + return this.rootException; + } } diff --git a/src/main/java/com/metamug/mason/service/ConnectionProvider.java b/src/main/java/com/metamug/mason/service/ConnectionProvider.java index 1bd494e3..e64842d8 100644 --- a/src/main/java/com/metamug/mason/service/ConnectionProvider.java +++ b/src/main/java/com/metamug/mason/service/ConnectionProvider.java @@ -506,67 +506,70 @@ */ package com.metamug.mason.service; -import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread; + import java.sql.Connection; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; + import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; +import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread; + /** * * @author Kainix */ public class ConnectionProvider { - private static String masonDatasource; + private static String masonDatasource; - private final DataSource ds; + private final DataSource ds; - public static DataSource getMasonDatasource() { - try { - Context initialContext = new InitialContext(); - Context envContext = (Context) initialContext.lookup("java:/comp/env"); - return (DataSource) envContext.lookup(masonDatasource); - } catch (NamingException ex) { - Logger.getLogger(ConnectionProvider.class.getName()).log(Level.SEVERE, null, ex); - } - return null; - } + public static DataSource getMasonDatasource() { + try { + Context initialContext = new InitialContext(); + Context envContext = (Context) initialContext.lookup("java:/comp/env"); + return (DataSource) envContext.lookup(masonDatasource); + } catch (NamingException ex) { + Logger.getLogger(ConnectionProvider.class.getName()).log(Level.SEVERE, null, ex); + } + return null; + } - public ConnectionProvider(String masonDatasource) throws SQLException, NamingException { - this.masonDatasource = masonDatasource; - ds = getMasonDatasource(); - } + public ConnectionProvider(String masonDatasource) throws SQLException, NamingException { + ConnectionProvider.masonDatasource = masonDatasource; + ds = getMasonDatasource(); + } -// public static ConnectionProvider getInstance() throws SQLException, NamingException { -// return new ConnectionProvider(); -// } - public Connection getConnection() { - try { - return ds.getConnection(); - } catch (SQLException ex) { - Logger.getLogger(ConnectionProvider.class.getName()).log(Level.SEVERE, null, ex); - return null; - } - } + // public static ConnectionProvider getInstance() throws SQLException, NamingException { + // return new ConnectionProvider(); + // } + public Connection getConnection() { + try { + return ds.getConnection(); + } catch (SQLException ex) { + Logger.getLogger(ConnectionProvider.class.getName()).log(Level.SEVERE, null, ex); + return null; + } + } - public void shutdown() throws SQLException, NamingException { - String driver = ""; - //try (Connection con = getConnection()) { - // DatabaseMetaData dbMetaData = con.getMetaData(); - // driver = dbMetaData.getDriverName().toLowerCase().trim(); - //} catch (SQLException ex) { - // Logger.getLogger(ConnectionProvider.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - //} - if (driver.contains("hsql")) { - } else if (driver.contains("mysql")) { - //set this for mysql driver - //https://stackoverflow.com/a/19027873/4800126 - AbandonedConnectionCleanupThread.checkedShutdown(); - } - } + public void shutdown() throws SQLException, NamingException { + String driver = ""; + // try (Connection con = getConnection()) { + // DatabaseMetaData dbMetaData = con.getMetaData(); + // driver = dbMetaData.getDriverName().toLowerCase().trim(); + // } catch (SQLException ex) { + // Logger.getLogger(ConnectionProvider.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + // } + if (driver.contains("hsql")) { + } else if (driver.contains("mysql")) { + // set this for mysql driver + // https://stackoverflow.com/a/19027873/4800126 + AbandonedConnectionCleanupThread.checkedShutdown(); + } + } } diff --git a/src/main/java/com/metamug/mason/service/UploaderService.java b/src/main/java/com/metamug/mason/service/UploaderService.java index 74a380de..7310b9e7 100644 --- a/src/main/java/com/metamug/mason/service/UploaderService.java +++ b/src/main/java/com/metamug/mason/service/UploaderService.java @@ -506,13 +506,15 @@ */ package com.metamug.mason.service; +import static com.metamug.mason.entity.request.MultipartFormStrategy.MULTIPART_FORM_DATA; + import com.metamug.entity.Request; import com.metamug.entity.Response; import com.metamug.event.UploadEvent; import com.metamug.event.UploadListener; -import static com.metamug.mason.entity.request.MultipartFormStrategy.MULTIPART_FORM_DATA; import com.metamug.mason.exception.MasonError; import com.metamug.mason.exception.MasonException; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -524,6 +526,7 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; + import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; @@ -539,101 +542,101 @@ @MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 25) public class UploaderService { - public final String UPLOAD_ATTR = "_upload"; - private static final String UPLOAD_DIR = "uploads"; - PageContext pageContext; + public final String UPLOAD_ATTR = "_upload"; + private static final String UPLOAD_DIR = "uploads"; + PageContext pageContext; - public UploaderService(PageContext pageContext) { - this.pageContext = pageContext; - } + public UploaderService(PageContext pageContext) { + this.pageContext = pageContext; + } - public boolean upload() throws JspException { - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - if (request.getContentType()!=null && request.getContentType().contains(MULTIPART_FORM_DATA)) { + public boolean upload() throws JspException { + HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); + if (request.getContentType()!=null && request.getContentType().contains(MULTIPART_FORM_DATA)) { - try { - String listenerClass; - Properties prop = new Properties(); - try (InputStream fis = UploaderService.class.getClassLoader().getResourceAsStream("config.properties")) { - prop.load(fis); - listenerClass = prop.getProperty("uploadlistener"); - } - if (listenerClass != null) { - uploadPart(request, listenerClass); - } else { - throw new JspTagException("No implementation of UploadListener was found.", new MasonException(MasonError.NO_UPLOAD_LISTENER)); - } - } catch (IllegalStateException ex) { - if (ex.getMessage().contains("FileSizeLimitExceededException")) { - throw new JspException("", new MasonException(MasonError.UPLOAD_SIZE_EXCEEDED)); - } - } catch (NullPointerException | IOException ex) { - throw new JspException("", new MasonException(MasonError.UPLOAD_CODE_ERROR, ex)); - } catch (RuntimeException ex) { - throw new JspException("", new MasonException(MasonError.UPLOAD_CODE_ERROR, ex)); - } catch (Exception ex) { - throw new JspException("", new MasonException(MasonError.UPLOAD_CODE_ERROR, ex)); - } - } - return true; - } + try { + String listenerClass; + Properties prop = new Properties(); + try (InputStream fis = UploaderService.class.getClassLoader().getResourceAsStream("config.properties")) { + prop.load(fis); + listenerClass = prop.getProperty("uploadlistener"); + } + if (listenerClass != null) { + uploadPart(request, listenerClass); + } else { + throw new JspTagException("No implementation of UploadListener was found.", new MasonException(MasonError.NO_UPLOAD_LISTENER)); + } + } catch (IllegalStateException ex) { + if (ex.getMessage().contains("FileSizeLimitExceededException")) { + throw new JspException("", new MasonException(MasonError.UPLOAD_SIZE_EXCEEDED)); + } + } catch (NullPointerException | IOException ex) { + throw new JspException("", new MasonException(MasonError.UPLOAD_CODE_ERROR, ex)); + } catch (RuntimeException ex) { + throw new JspException("", new MasonException(MasonError.UPLOAD_CODE_ERROR, ex)); + } catch (Exception ex) { + throw new JspException("", new MasonException(MasonError.UPLOAD_CODE_ERROR, ex)); + } + } + return true; + } - private void callUploadEvent(File uploadedFile, String listenerClass, Request req) throws ClassNotFoundException, - InstantiationException, IllegalAccessException, Exception{ - Object result = null; + private void callUploadEvent(File uploadedFile, String listenerClass, Request req) throws ClassNotFoundException, + InstantiationException, IllegalAccessException, Exception{ + Object result = null; - Class cls = Class.forName(listenerClass); - Object newInstance = cls.newInstance(); - UploadListener listener; - if (UploadListener.class.isAssignableFrom(cls)) { - listener = (UploadListener) newInstance; - if (uploadedFile != null) { - DataSource ds = ConnectionProvider.getMasonDatasource(); - result = listener.uploadPerformed(new UploadEvent(uploadedFile, uploadedFile.getName(), req), ds); - } - } else { - throw new JspException("", new MasonException(MasonError.CLASS_NOT_IMPLEMENTED, "Class " + cls + " isn't an UploadListener.")); - } + Class cls = Class.forName(listenerClass); + Object newInstance = cls.newInstance(); + UploadListener listener; + if (UploadListener.class.isAssignableFrom(cls)) { + listener = (UploadListener) newInstance; + if (uploadedFile != null) { + DataSource ds = ConnectionProvider.getMasonDatasource(); + result = listener.uploadPerformed(new UploadEvent(uploadedFile, uploadedFile.getName(), req), ds); + } + } else { + throw new JspException("", new MasonException(MasonError.CLASS_NOT_IMPLEMENTED, "Class " + cls + " isn't an UploadListener.")); + } - //add to bus - if (result instanceof Response) { - pageContext.setAttribute(UPLOAD_ATTR, ((Response) result).getPayload()); - } else { - pageContext.setAttribute(UPLOAD_ATTR, result); - } - } + //add to bus + if (result instanceof Response) { + pageContext.setAttribute(UPLOAD_ATTR, ((Response) result).getPayload()); + } else { + pageContext.setAttribute(UPLOAD_ATTR, result); + } + } - private void uploadPart(HttpServletRequest request, String listenerClass) throws JspTagException, IOException, Exception { - try { - String uploadFilePath = System.getProperty("catalina.base") + File.separator + UPLOAD_DIR + request.getContextPath(); - Files.createDirectories(Paths.get(uploadFilePath)); + private void uploadPart(HttpServletRequest request, String listenerClass) throws JspTagException, IOException, Exception { + try { + String uploadFilePath = System.getProperty("catalina.base") + File.separator + UPLOAD_DIR + request.getContextPath(); + Files.createDirectories(Paths.get(uploadFilePath)); - //Get all the parts from request and write it to the file on server - // Retrieves - List fileParts = request.getParts().stream().filter(part - -> "file".equals(part.getName())).collect(Collectors.toList()); + //Get all the parts from request and write it to the file on server + // Retrieves + List fileParts = request.getParts().stream().filter(part + -> "file".equals(part.getName())).collect(Collectors.toList()); - String fileName; - for (Part filePart : fileParts) { //for multiple files - fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix. - File uploadedFile = new File(uploadFilePath + File.separator + fileName); - if (!uploadedFile.isDirectory()) { - try (FileOutputStream fos = new FileOutputStream(uploadedFile); InputStream fileContent = filePart.getInputStream()) { - int read; - byte[] bytes = new byte[1024]; - while ((read = fileContent.read(bytes)) != -1) { - fos.write(bytes, 0, read); - } - } catch (IOException ex) { - Logger.getLogger(UploaderService.class.getName()).log(Level.SEVERE, null, ex); - } - //call event - callUploadEvent(uploadedFile, listenerClass, (Request) request.getAttribute("mtgReq")); - } + String fileName; + for (Part filePart : fileParts) { //for multiple files + fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix. + File uploadedFile = new File(uploadFilePath + File.separator + fileName); + if (!uploadedFile.isDirectory()) { + try (FileOutputStream fos = new FileOutputStream(uploadedFile); InputStream fileContent = filePart.getInputStream()) { + int read; + byte[] bytes = new byte[1024]; + while ((read = fileContent.read(bytes)) != -1) { + fos.write(bytes, 0, read); + } + } catch (IOException ex) { + Logger.getLogger(UploaderService.class.getName()).log(Level.SEVERE, null, ex); + } + //call event + callUploadEvent(uploadedFile, listenerClass, (Request) request.getAttribute("mtgReq")); + } - } - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | RuntimeException ex) { - throw new JspTagException("Unable to load Upload Event Listener", new MasonException(MasonError.NO_UPLOAD_LISTENER)); - } - } + } + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | RuntimeException ex) { + throw new JspTagException("Unable to load Upload Event Listener", new MasonException(MasonError.NO_UPLOAD_LISTENER)); + } + } } diff --git a/src/main/java/com/metamug/mason/service/XRequestService.java b/src/main/java/com/metamug/mason/service/XRequestService.java index 6262622c..28910a49 100644 --- a/src/main/java/com/metamug/mason/service/XRequestService.java +++ b/src/main/java/com/metamug/mason/service/XRequestService.java @@ -507,6 +507,10 @@ package com.metamug.mason.service; import com.metamug.mason.entity.xrequest.XResponse; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONObject; + import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @@ -515,6 +519,7 @@ import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; + import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.MediaType; @@ -522,8 +527,6 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; -import org.apache.commons.lang3.StringUtils; -import org.json.JSONObject; /** * @@ -531,172 +534,172 @@ */ public class XRequestService { - private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); - private static final String UTF8 = "UTF-8"; - private static final String XREQUEST_ERROR = "XRequest error: "; + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + private static final String UTF8 = "UTF-8"; + private static final String XREQUEST_ERROR = "XRequest error: "; + + public static final String CONTENT_TYPE = "Content-Type"; + public static final String APP_FORM_URLENCODED = "application/x-www-form-urlencoded"; + public static final String APP_JSON = "application/json"; + + private final OkHttpClient client = new OkHttpClient(); + + private boolean outputHeaders; - public static final String CONTENT_TYPE = "Content-Type"; - public static final String APP_FORM_URLENCODED = "application/x-www-form-urlencoded"; - public static final String APP_JSON = "application/json"; + public XRequestService(boolean outputHeaders){ + this.outputHeaders = outputHeaders; + } - private final OkHttpClient client = new OkHttpClient(); - - private boolean outputHeaders; - - public XRequestService(boolean outputHeaders){ - this.outputHeaders = outputHeaders; - } + private XResponse makeRequest(Request request) { + XResponse xr; + try (Response response = client.newCall(request).execute()) { + Map headerMap = new HashMap<>(); + if(outputHeaders){ + Headers headers = response.headers(); + for (int i = 0; i < headers.size(); i++) { + headerMap.put(headers.name(i), headers.value(i)); + } + } + if (!response.isSuccessful()) { + xr = new XResponse(response.code(), headerMap, XREQUEST_ERROR + response, true, outputHeaders); - private XResponse makeRequest(Request request) { - XResponse xr; - try (Response response = client.newCall(request).execute()) { - Map headerMap = new HashMap<>(); - if(outputHeaders){ - Headers headers = response.headers(); - for (int i = 0; i < headers.size(); i++) { - headerMap.put(headers.name(i), headers.value(i)); - } - } - if (!response.isSuccessful()) { - xr = new XResponse(response.code(), headerMap, XREQUEST_ERROR + response, true, outputHeaders); - - } else { - xr = new XResponse(response.code(), headerMap, response.body().string().trim(), false, outputHeaders); - } - } catch (IOException ex) { - xr = new XResponse(0, null, XREQUEST_ERROR + ex.getMessage(), true, outputHeaders); - } - return xr; - } + } else { + xr = new XResponse(response.code(), headerMap, response.body().string().trim(), false, outputHeaders); + } + } catch (IOException ex) { + xr = new XResponse(0, null, XREQUEST_ERROR + ex.getMessage(), true, outputHeaders); + } + return xr; + } - public XResponse get(String url, Map headers, Map params) { - Request.Builder reqBuilder = new Request.Builder().get(); - headers.entrySet().forEach(entry -> { - String key = entry.getKey(); - String value = entry.getValue(); - reqBuilder.addHeader(key, value); - }); - StringBuilder queryParams = new StringBuilder(); - for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) { - try { - String str = (String) iterator.next(); - String key = URLEncoder.encode(str, UTF8); - //@TODO handle file uplaod in xrequest - String value = URLEncoder.encode((String) params.get(str), UTF8); - queryParams.append(key).append("=").append(value); - if (iterator.hasNext()) { - queryParams.append("&"); - } - } catch (UnsupportedEncodingException ex) { - Logger.getLogger(XRequestService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } - } - if (queryParams.length() > 0) { - url += "?" + queryParams.toString(); - } - Request request = reqBuilder.url(url).build(); - return makeRequest(request); - } + public XResponse get(String url, Map headers, Map params) { + Request.Builder reqBuilder = new Request.Builder().get(); + headers.entrySet().forEach(entry -> { + String key = entry.getKey(); + String value = entry.getValue(); + reqBuilder.addHeader(key, value); + }); + StringBuilder queryParams = new StringBuilder(); + for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) { + try { + String str = iterator.next(); + String key = URLEncoder.encode(str, UTF8); + // @TODO handle file upload in XRequest + String value = URLEncoder.encode((String) params.get(str), UTF8); + queryParams.append(key).append("=").append(value); + if (iterator.hasNext()) { + queryParams.append("&"); + } + } catch (UnsupportedEncodingException ex) { + Logger.getLogger(XRequestService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } + } + if (queryParams.length() > 0) { + url += "?" + queryParams.toString(); + } + Request request = reqBuilder.url(url).build(); + return makeRequest(request); + } - public XResponse post(String url, Map headers, - Map params, String body) { - Request.Builder reqBuilder = null; + public XResponse post(String url, Map headers, + Map params, String body) { + Request.Builder reqBuilder = null; - if (headers.get(CONTENT_TYPE) == null) { - headers.put(CONTENT_TYPE, APP_FORM_URLENCODED); - } + if (headers.get(CONTENT_TYPE) == null) { + headers.put(CONTENT_TYPE, APP_FORM_URLENCODED); + } - String contentType = headers.get(CONTENT_TYPE).toLowerCase(); + String contentType = headers.get(CONTENT_TYPE).toLowerCase(); - if (contentType.equals(APP_FORM_URLENCODED)) { - FormBody.Builder formBuilder = new FormBody.Builder(); - for (Map.Entry entry : params.entrySet()) { - formBuilder.add(entry.getKey(), (String) entry.getValue()); - } - reqBuilder = new Request.Builder().post(formBuilder.build()); - } else if (contentType.equals(APP_JSON)) { - if (StringUtils.isNotBlank(body)) { - RequestBody reqBody = RequestBody.create(JSON, body); - reqBuilder = new Request.Builder().post(reqBody); - } else { - JSONObject jo = new JSONObject(); - for (Map.Entry entry : params.entrySet()) { - jo.put(entry.getKey(), entry.getValue()); - } - RequestBody reqBody = RequestBody.create(JSON, jo.toString()); - reqBuilder = new Request.Builder().post(reqBody); - } - } - //no params or body given - if (null == reqBuilder) { - RequestBody reqbody = RequestBody.create(null, new byte[0]); - reqBuilder = new Request.Builder().post(reqbody); - } - for (Map.Entry entry : headers.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - reqBuilder.addHeader(key, value); - } - Request request = reqBuilder.url(url).build(); - return makeRequest(request); - } + if (contentType.equals(APP_FORM_URLENCODED)) { + FormBody.Builder formBuilder = new FormBody.Builder(); + for (Map.Entry entry : params.entrySet()) { + formBuilder.add(entry.getKey(), (String) entry.getValue()); + } + reqBuilder = new Request.Builder().post(formBuilder.build()); + } else if (contentType.equals(APP_JSON)) { + if (StringUtils.isNotBlank(body)) { + RequestBody reqBody = RequestBody.create(JSON, body); + reqBuilder = new Request.Builder().post(reqBody); + } else { + JSONObject jo = new JSONObject(); + for (Map.Entry entry : params.entrySet()) { + jo.put(entry.getKey(), entry.getValue()); + } + RequestBody reqBody = RequestBody.create(JSON, jo.toString()); + reqBuilder = new Request.Builder().post(reqBody); + } + } + //no params or body given + if (null == reqBuilder) { + RequestBody reqbody = RequestBody.create(null, new byte[0]); + reqBuilder = new Request.Builder().post(reqbody); + } + for (Map.Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + reqBuilder.addHeader(key, value); + } + Request request = reqBuilder.url(url).build(); + return makeRequest(request); + } - public XResponse put(String url, Map headers, - Map params, String body) { - Request.Builder reqBuilder = null; - String contentType = headers.get(CONTENT_TYPE).toLowerCase(); - if (contentType.equals(APP_FORM_URLENCODED)) { - FormBody.Builder formBuilder = new FormBody.Builder(); - for (Map.Entry entry : params.entrySet()) { - formBuilder.add(entry.getKey(), (String) entry.getValue()); - } - reqBuilder = new Request.Builder().put(formBuilder.build()); - } else if (contentType.equals(APP_JSON)) { - if ((body != null) && (!body.equals(""))) { - RequestBody reqBody = RequestBody.create(JSON, body); - reqBuilder = new Request.Builder().put(reqBody); - } else { - JSONObject jo = new JSONObject(); - for (Map.Entry entry : params.entrySet()) { - jo.put(entry.getKey(), entry.getValue()); - } - RequestBody reqBody = RequestBody.create(JSON, jo.toString()); - reqBuilder = new Request.Builder().put(reqBody); - } - } - //no params or body given - if (null == reqBuilder) { - RequestBody reqbody = RequestBody.create(null, new byte[0]); - reqBuilder = new Request.Builder().put(reqbody); - } - for (Map.Entry entry : headers.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - reqBuilder.addHeader(key, value); - } - Request request = reqBuilder.url(url).build(); - return makeRequest(request); - } + public XResponse put(String url, Map headers, + Map params, String body) { + Request.Builder reqBuilder = null; + String contentType = headers.get(CONTENT_TYPE).toLowerCase(); + if (contentType.equals(APP_FORM_URLENCODED)) { + FormBody.Builder formBuilder = new FormBody.Builder(); + for (Map.Entry entry : params.entrySet()) { + formBuilder.add(entry.getKey(), (String) entry.getValue()); + } + reqBuilder = new Request.Builder().put(formBuilder.build()); + } else if (contentType.equals(APP_JSON)) { + if ((body != null) && (!body.equals(""))) { + RequestBody reqBody = RequestBody.create(JSON, body); + reqBuilder = new Request.Builder().put(reqBody); + } else { + JSONObject jo = new JSONObject(); + for (Map.Entry entry : params.entrySet()) { + jo.put(entry.getKey(), entry.getValue()); + } + RequestBody reqBody = RequestBody.create(JSON, jo.toString()); + reqBuilder = new Request.Builder().put(reqBody); + } + } + //no params or body given + if (null == reqBuilder) { + RequestBody reqbody = RequestBody.create(null, new byte[0]); + reqBuilder = new Request.Builder().put(reqbody); + } + for (Map.Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + reqBuilder.addHeader(key, value); + } + Request request = reqBuilder.url(url).build(); + return makeRequest(request); + } - public XResponse delete(String url, Map params) { - StringBuilder queryParams = new StringBuilder(); - for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) { - try { - String str = (String) iterator.next(); - String key = URLEncoder.encode(str, UTF8); - String value = URLEncoder.encode((String) params.get(str), UTF8); - queryParams.append(key).append("=").append(value); - if (iterator.hasNext()) { - queryParams.append("&"); - } - } catch (UnsupportedEncodingException ex) { - Logger.getLogger(XRequestService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } - } - if (queryParams.length() > 0) { - url += "?" + queryParams.toString(); - } - Request request = new Request.Builder().url(url).delete().build(); - return makeRequest(request); - } + public XResponse delete(String url, Map params) { + StringBuilder queryParams = new StringBuilder(); + for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) { + try { + String str = iterator.next(); + String key = URLEncoder.encode(str, UTF8); + String value = URLEncoder.encode((String) params.get(str), UTF8); + queryParams.append(key).append("=").append(value); + if (iterator.hasNext()) { + queryParams.append("&"); + } + } catch (UnsupportedEncodingException ex) { + Logger.getLogger(XRequestService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } + } + if (queryParams.length() > 0) { + url += "?" + queryParams.toString(); + } + Request request = new Request.Builder().url(url).delete().build(); + return makeRequest(request); + } } diff --git a/src/main/java/com/metamug/mason/tag/ExceptionTagHandler.java b/src/main/java/com/metamug/mason/tag/ExceptionTagHandler.java index c2b2f0ec..7ecec1c9 100644 --- a/src/main/java/com/metamug/mason/tag/ExceptionTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/ExceptionTagHandler.java @@ -508,6 +508,7 @@ import com.metamug.mason.exception.MasonException; import com.metamug.mason.service.ConnectionProvider; + import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; @@ -516,12 +517,12 @@ import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; -import static javax.servlet.jsp.tagext.Tag.SKIP_PAGE; import javax.servlet.jsp.tagext.TryCatchFinally; import javax.sql.DataSource; @@ -531,316 +532,324 @@ */ public class ExceptionTagHandler extends BodyTagSupport implements TryCatchFinally { - private Object value; - private DataSource ds; + /** + * + */ + private static final long serialVersionUID = 1L; + private Object value; + private DataSource ds; - /** - * This method is called after the JSP engine finished processing the tag. - * - * @return EVAL_PAGE if the JSP engine should continue evaluating the JSP page, otherwise return SKIP_PAGE. This method is automatically generated. Do not modify this method. Instead, modify the - * methods that this method calls. - * @throws javax.servlet.jsp.JspException - */ - @Override - public int doEndTag() throws JspException { - Exception exception = (Exception) value; - ds = ConnectionProvider.getMasonDatasource(); - JspWriter out = pageContext.getOut(); - HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - String header = request.getHeader("Accept") == null ? "application/json" : request.getHeader("Accept"); - try { - if (Arrays.asList(header.split("/")).contains("xml")) { - response.setContentType("application/xml"); - out.println("\n"); - if (exception.getCause() != null) { - String cause = exception.getCause().toString(); - if (cause.contains("MySQLSyntaxErrorException") || cause.contains("MySQLIntegrityConstraintViolationException") || cause.contains("MysqlDataTruncation") || cause.contains("SQLException") || cause.contains("PSQLException")) { - response.setStatus(512); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - logError(errorId, request, exception); - out.println("" + errorId + "\n" + 512 + "" - + "\nAPI Error. Please contact your API administrator."); - } else if (cause.contains("NumberFormatException") || cause.contains("ParseException")) { - response.setStatus(422); - out.println("Unable to parse input\n" + 422 + ""); - Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); - } else if (cause.contains(MasonException.class.getName())) { - MasonException mtgCause = (MasonException) exception.getCause(); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - switch (mtgCause.getError()) { - case BEARER_TOKEN_MISMATCH: - response.setStatus(401); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 401 + ""); - break; - case INCORRECT_ROLE_AUTHENTICATION: - response.setStatus(401); - response.setHeader("WWW-Authenticate", "Basic"); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 401 + ""); - break; - case INCORRECT_STATUS_CODE: - response.setStatus(406); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 406 + ""); - break; - case INPUT_VALIDATION_ERROR: - response.setStatus(412); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 412 + ""); - break; - case NO_UPLOAD_LISTENER: - response.setStatus(424); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 424 + ""); - break; - case PARENT_RESOURCE_MISSING: - response.setStatus(404); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 424 + ""); - break; - case ROLE_ACCESS_DENIED: - response.setStatus(403); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 403 + ""); - break; - case SQL_ERROR: - response.setStatus(512); - logError(errorId, request, exception); - out.println("" + errorId + "\n" + 512 + "" - + "\n" + mtgCause.getMessage() + "" - + "\nAPI Error. Please contact your API administrator."); - break; - case UPLOAD_CODE_ERROR: - response.setStatus(512); - logUploadCodeError(errorId, request, mtgCause.getRootException()); - out.println("" + errorId + "\n" + 512 + "" - + "\n" + mtgCause.getMessage() + "" - + "\nAPI Error. Please contact your API administrator."); - break; - case UPLOAD_SIZE_EXCEEDED: - response.setStatus(413); - out.println("" + mtgCause.getMessage() + "" - + "\n" + 413 + ""); - break; - } - } else { - response.setStatus(512); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - logError(errorId, request, exception); - out.println("" + errorId + "\n" + 512 + "" - + "\nAPI Error. Please contact your API administrator."); - } - } else { - response.setStatus(512); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - logError(errorId, request, exception); - out.println("" + errorId + "\n" + 512 + "" - + "\nAPI Error. Please contact your API administrator."); - } - out.println("\n"); - } else { - response.setContentType("application/json"); - if (exception.getCause() != null) { - String cause = exception.getCause().toString(); - if (cause.contains("MySQLSyntaxErrorException") || cause.contains("MySQLIntegrityConstraintViolationException") || cause.contains("MysqlDataTruncation") || cause.contains("SQLException")) { - response.setStatus(512); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - logError(errorId, request, exception); - out.println("{\"errorId\":" + errorId + ",\"status\":" + 512 + "," - + "\"message\": \"API Error. Please contact your API administrator.\"}"); - } else if (cause.contains("NumberFormatException") || cause.contains("ParseException")) { - response.setStatus(422); - out.println("{\"message\": \"Unable to parse input\",\"status\":" + 422 + "}"); - Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); - } else if (cause.contains(MasonException.class.getName())) { - MasonException mtgCause = (MasonException) exception.getCause(); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - switch (mtgCause.getError()) { - case BEARER_TOKEN_MISMATCH: - response.setStatus(401); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 401 + "}"); - break; - case CLASS_NOT_IMPLEMENTED: - response.setStatus(422); - logCodeError(errorId, request, mtgCause); - out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," - + "\"message\": \"API Error. Please contact your API administrator.\"," - + "\"status\":" + 422 + "}"); - break; - case CODE_ERROR: - response.setStatus(512); - logCodeError(errorId, request, mtgCause.getRootException()); - out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," - + "\"message\": \"API Error. Please contact your API administrator.\"," - + "\"status\":" + 512 + "}"); - break; - case EMPTY_PERSIST_ERROR: - response.setStatus(409); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 409 + "}"); - break; - case INCORRECT_ROLE_AUTHENTICATION: - response.setStatus(401); - response.setHeader("WWW-Authenticate", "Basic"); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 401 + "}"); - break; - case INCORRECT_STATUS_CODE: - response.setStatus(406); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 406 + "}"); - break; - case INPUT_VALIDATION_ERROR: - response.setStatus(412); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 412 + "}"); - break; - case NO_UPLOAD_LISTENER: - response.setStatus(424); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 424 + "}"); - break; - case PARENT_RESOURCE_MISSING: - response.setStatus(404); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 404 + "}"); - break; - case ROLE_ACCESS_DENIED: - response.setStatus(403); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 403 + "}"); - break; - case SQL_ERROR: - response.setStatus(512); - logError(errorId, request, mtgCause); - out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," - + "\"message\": \"API Error. Please contact your API administrator.\"," - + "\"status\":" + 512 + "}"); - break; - case UPLOAD_CODE_ERROR: - response.setStatus(512); - logUploadCodeError(errorId, request, mtgCause.getRootException()); - out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," - + "\"message\": \"API Error. Please contact your API administrator.\"," - + "\"status\":" + 512 + "}"); - break; - case UPLOAD_SIZE_EXCEEDED: - response.setStatus(413); - out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 413 + "}"); - break; - } - } else { - response.setStatus(512); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - logError(errorId, request, exception); - out.println("{\"errorId\":" + errorId + ",\"status\":" + 512 + "," - + "\"message\": \"API Error. Please contact your API administrator.\"}"); - } - } else { - response.setStatus(512); - String timestamp = String.valueOf(System.currentTimeMillis()); - long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); - String errorId = String.valueOf(Math.abs(hash)); - logError(errorId, request, exception); - out.println("{\"errorId\":" + errorId + ",\"status\":" + 512 + "," - + "\"message\": \"API Error. Please contact your API administrator.\"}"); - } - } - } catch (IOException ex) { - Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } - return SKIP_PAGE; - } + /** + * This method is called after the JSP engine finished processing the tag. + * + * @return EVAL_PAGE if the JSP engine should continue evaluating the JSP page, otherwise return SKIP_PAGE. This method is automatically generated. Do not modify this method. Instead, modify the + * methods that this method calls. + * @throws javax.servlet.jsp.JspException + */ + @Override + public int doEndTag() throws JspException { + Exception exception = (Exception) value; + ds = ConnectionProvider.getMasonDatasource(); + JspWriter out = pageContext.getOut(); + HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); + HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); + String header = request.getHeader("Accept") == null ? "application/json" : request.getHeader("Accept"); + try { + if (Arrays.asList(header.split("/")).contains("xml")) { + response.setContentType("application/xml"); + out.println("\n"); + if (exception.getCause() != null) { + String cause = exception.getCause().toString(); + if (cause.contains("MySQLSyntaxErrorException") || cause.contains("MySQLIntegrityConstraintViolationException") || cause.contains("MysqlDataTruncation") || cause.contains("SQLException") || cause.contains("PSQLException")) { + response.setStatus(512); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + logError(errorId, request, exception); + out.println("" + errorId + "\n" + 512 + "" + + "\nAPI Error. Please contact your API administrator."); + } else if (cause.contains("NumberFormatException") || cause.contains("ParseException")) { + response.setStatus(422); + out.println("Unable to parse input\n" + 422 + ""); + Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); + } else if (cause.contains(MasonException.class.getName())) { + MasonException mtgCause = (MasonException) exception.getCause(); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + switch (mtgCause.getError()) { + case BEARER_TOKEN_MISMATCH: + response.setStatus(401); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 401 + ""); + break; + case INCORRECT_ROLE_AUTHENTICATION: + response.setStatus(401); + response.setHeader("WWW-Authenticate", "Basic"); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 401 + ""); + break; + case INCORRECT_STATUS_CODE: + response.setStatus(406); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 406 + ""); + break; + case INPUT_VALIDATION_ERROR: + response.setStatus(412); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 412 + ""); + break; + case NO_UPLOAD_LISTENER: + response.setStatus(424); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 424 + ""); + break; + case PARENT_RESOURCE_MISSING: + response.setStatus(404); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 424 + ""); + break; + case ROLE_ACCESS_DENIED: + response.setStatus(403); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 403 + ""); + break; + case SQL_ERROR: + response.setStatus(512); + logError(errorId, request, exception); + out.println("" + errorId + "\n" + 512 + "" + + "\n" + mtgCause.getMessage() + "" + + "\nAPI Error. Please contact your API administrator."); + break; + case UPLOAD_CODE_ERROR: + response.setStatus(512); + logUploadCodeError(errorId, request, mtgCause.getRootException()); + out.println("" + errorId + "\n" + 512 + "" + + "\n" + mtgCause.getMessage() + "" + + "\nAPI Error. Please contact your API administrator."); + break; + case UPLOAD_SIZE_EXCEEDED: + response.setStatus(413); + out.println("" + mtgCause.getMessage() + "" + + "\n" + 413 + ""); + break; + default: + break; + } + } else { + response.setStatus(512); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + logError(errorId, request, exception); + out.println("" + errorId + "\n" + 512 + "" + + "\nAPI Error. Please contact your API administrator."); + } + } else { + response.setStatus(512); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + logError(errorId, request, exception); + out.println("" + errorId + "\n" + 512 + "" + + "\nAPI Error. Please contact your API administrator."); + } + out.println("\n"); + } else { + response.setContentType("application/json"); + if (exception.getCause() != null) { + String cause = exception.getCause().toString(); + if (cause.contains("MySQLSyntaxErrorException") || cause.contains("MySQLIntegrityConstraintViolationException") || cause.contains("MysqlDataTruncation") || cause.contains("SQLException")) { + response.setStatus(512); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + logError(errorId, request, exception); + out.println("{\"errorId\":" + errorId + ",\"status\":" + 512 + "," + + "\"message\": \"API Error. Please contact your API administrator.\"}"); + } else if (cause.contains("NumberFormatException") || cause.contains("ParseException")) { + response.setStatus(422); + out.println("{\"message\": \"Unable to parse input\",\"status\":" + 422 + "}"); + Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); + } else if (cause.contains(MasonException.class.getName())) { + MasonException mtgCause = (MasonException) exception.getCause(); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + switch (mtgCause.getError()) { + case BEARER_TOKEN_MISMATCH: + response.setStatus(401); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 401 + "}"); + break; + case CLASS_NOT_IMPLEMENTED: + response.setStatus(422); + logCodeError(errorId, request, mtgCause); + out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," + + "\"message\": \"API Error. Please contact your API administrator.\"," + + "\"status\":" + 422 + "}"); + break; + case CODE_ERROR: + response.setStatus(512); + logCodeError(errorId, request, mtgCause.getRootException()); + out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," + + "\"message\": \"API Error. Please contact your API administrator.\"," + + "\"status\":" + 512 + "}"); + break; + case EMPTY_PERSIST_ERROR: + response.setStatus(409); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 409 + "}"); + break; + case INCORRECT_ROLE_AUTHENTICATION: + response.setStatus(401); + response.setHeader("WWW-Authenticate", "Basic"); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 401 + "}"); + break; + case INCORRECT_STATUS_CODE: + response.setStatus(406); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 406 + "}"); + break; + case INPUT_VALIDATION_ERROR: + response.setStatus(412); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 412 + "}"); + break; + case NO_UPLOAD_LISTENER: + response.setStatus(424); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 424 + "}"); + break; + case PARENT_RESOURCE_MISSING: + response.setStatus(404); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 404 + "}"); + break; + case ROLE_ACCESS_DENIED: + response.setStatus(403); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 403 + "}"); + break; + case SQL_ERROR: + response.setStatus(512); + logError(errorId, request, mtgCause); + out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," + + "\"message\": \"API Error. Please contact your API administrator.\"," + + "\"status\":" + 512 + "}"); + break; + case UPLOAD_CODE_ERROR: + response.setStatus(512); + logUploadCodeError(errorId, request, mtgCause.getRootException()); + out.println("{\"errorId\":" + errorId + ",\"error\":\"" + mtgCause.getMessage() + "\"," + + "\"message\": \"API Error. Please contact your API administrator.\"," + + "\"status\":" + 512 + "}"); + break; + case UPLOAD_SIZE_EXCEEDED: + response.setStatus(413); + out.println("{\"message\": \"" + mtgCause.getMessage() + "\",\"status\":" + 413 + "}"); + break; + default: + break; + } + } else { + response.setStatus(512); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + logError(errorId, request, exception); + out.println("{\"errorId\":" + errorId + ",\"status\":" + 512 + "," + + "\"message\": \"API Error. Please contact your API administrator.\"}"); + } + } else { + response.setStatus(512); + String timestamp = String.valueOf(System.currentTimeMillis()); + long hash = UUID.nameUUIDFromBytes(timestamp.getBytes()).getMostSignificantBits(); + String errorId = String.valueOf(Math.abs(hash)); + logError(errorId, request, exception); + out.println("{\"errorId\":" + errorId + ",\"status\":" + 512 + "," + + "\"message\": \"API Error. Please contact your API administrator.\"}"); + } + } + } catch (IOException ex) { + Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } + return SKIP_PAGE; + } - private void logError(String errorId, HttpServletRequest request, Exception exception) { -// String method = (String) request.getAttribute("mtgMethod"); -// String resourceURI = (String) request.getAttribute("javax.servlet.forward.request_uri"); - String exceptionMessage; - if (exception.getMessage() != null) { - exceptionMessage = exception.getMessage().replaceAll("(\\w+)_db\\.", "").replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); - } else { - exceptionMessage = exception.toString(); - } - //to trace here - dbLogErorr(errorId, request, exceptionMessage, new StringBuilder()); - Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); - } + private void logError(String errorId, HttpServletRequest request, Exception exception) { + // String method = (String) request.getAttribute("mtgMethod"); + // String resourceURI = (String) request.getAttribute("javax.servlet.forward.request_uri"); + String exceptionMessage; + if (exception.getMessage() != null) { + exceptionMessage = exception.getMessage().replaceAll("(\\w+)_db\\.", "").replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); + } else { + exceptionMessage = exception.toString(); + } + //to trace here + dbLogErorr(errorId, request, exceptionMessage, new StringBuilder()); + Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); + } - private void logCodeError(String errorId, HttpServletRequest request, Exception exception) { - String exceptionMessage; - if (exception.getMessage() != null) { - exceptionMessage = exception.getMessage().replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); - } else { - exceptionMessage = exception.toString(); - } - StringBuilder errorTraceBuilder = new StringBuilder(); - StackTraceElement[] stackTrace = exception.getStackTrace(); - for (StackTraceElement stackTraceElement : stackTrace) { - errorTraceBuilder.append(stackTraceElement); - if (stackTraceElement.getClassName().contains("CodeTagHandler")) { - break; - } - errorTraceBuilder.append("\n"); - } - dbLogErorr(errorId, request, exceptionMessage, errorTraceBuilder); - Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); - } + private void logCodeError(String errorId, HttpServletRequest request, Exception exception) { + String exceptionMessage; + if (exception.getMessage() != null) { + exceptionMessage = exception.getMessage().replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); + } else { + exceptionMessage = exception.toString(); + } + StringBuilder errorTraceBuilder = new StringBuilder(); + StackTraceElement[] stackTrace = exception.getStackTrace(); + for (StackTraceElement stackTraceElement : stackTrace) { + errorTraceBuilder.append(stackTraceElement); + if (stackTraceElement.getClassName().contains("CodeTagHandler")) { + break; + } + errorTraceBuilder.append("\n"); + } + dbLogErorr(errorId, request, exceptionMessage, errorTraceBuilder); + Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); + } - private void logUploadCodeError(String errorId, HttpServletRequest request, Exception exception) { - String exceptionMessage; - StringBuilder errorTraceBuilder = new StringBuilder(); - StackTraceElement[] stackTrace = exception.getStackTrace(); - for (StackTraceElement stackTraceElement : stackTrace) { - if (stackTraceElement.getClassName().contains("UploadEventTagHandler")) { - errorTraceBuilder.append(stackTraceElement); - break; - } - errorTraceBuilder.append(stackTraceElement).append("\n"); - } - if (exception.getMessage() != null) { - exceptionMessage = exception.getMessage().replaceAll("(\\w+)_db\\.", "").replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); - } else { - exceptionMessage = exception.toString(); - } - dbLogErorr(errorId, request, exceptionMessage, errorTraceBuilder); - Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); - } + private void logUploadCodeError(String errorId, HttpServletRequest request, Exception exception) { + String exceptionMessage; + StringBuilder errorTraceBuilder = new StringBuilder(); + StackTraceElement[] stackTrace = exception.getStackTrace(); + for (StackTraceElement stackTraceElement : stackTrace) { + if (stackTraceElement.getClassName().contains("UploadEventTagHandler")) { + errorTraceBuilder.append(stackTraceElement); + break; + } + errorTraceBuilder.append(stackTraceElement).append("\n"); + } + if (exception.getMessage() != null) { + exceptionMessage = exception.getMessage().replaceAll("(\\w+)_db\\.", "").replaceAll("(\\s|\\n|\\r|\\n\\r)+", " "); + } else { + exceptionMessage = exception.toString(); + } + dbLogErorr(errorId, request, exceptionMessage, errorTraceBuilder); + Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, exception.getMessage(), exception); + } - public void setValue(Object value) { - this.value = value; - } + public void setValue(Object value) { + this.value = value; + } - @Override - public void doCatch(Throwable throwable) throws Throwable { - throw throwable; - } + @Override + public void doCatch(Throwable throwable) throws Throwable { + throw throwable; + } - @Override - public void doFinally() { - } + @Override + public void doFinally() { + } - private void dbLogErorr(String errorId, HttpServletRequest request, String exceptionMessage, StringBuilder errorTraceBuilder) { - String method = (String) request.getAttribute("mtgMethod"); - String resourceURI = (String) request.getAttribute("javax.servlet.forward.request_uri"); - try (Connection con = ds.getConnection(); PreparedStatement stmnt = con.prepareStatement("INSERT INTO error_log (error_id,request_method,message,trace," - + " resource) VALUES(?,?,?,?,?)");) { - stmnt.setString(1, String.valueOf(errorId)); - stmnt.setString(2, method); - stmnt.setString(3, exceptionMessage); - stmnt.setString(4, errorTraceBuilder.toString()); - stmnt.setString(5, resourceURI); - stmnt.execute(); - } catch (SQLException ex) { - Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } - } + private void dbLogErorr(String errorId, HttpServletRequest request, String exceptionMessage, StringBuilder errorTraceBuilder) { + String method = (String) request.getAttribute("mtgMethod"); + String resourceURI = (String) request.getAttribute("javax.servlet.forward.request_uri"); + try (Connection con = ds.getConnection(); PreparedStatement stmnt = con.prepareStatement("INSERT INTO error_log (error_id,request_method,message,trace," + + " resource) VALUES(?,?,?,?,?)");) { + stmnt.setString(1, String.valueOf(errorId)); + stmnt.setString(2, method); + stmnt.setString(3, exceptionMessage); + stmnt.setString(4, errorTraceBuilder.toString()); + stmnt.setString(5, resourceURI); + stmnt.execute(); + } catch (SQLException ex) { + Logger.getLogger(ExceptionTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } + } } diff --git a/src/main/java/com/metamug/mason/tag/ExecuteTagHandler.java b/src/main/java/com/metamug/mason/tag/ExecuteTagHandler.java index 1fd9adc3..5057c147 100644 --- a/src/main/java/com/metamug/mason/tag/ExecuteTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/ExecuteTagHandler.java @@ -514,13 +514,15 @@ import com.metamug.mason.exception.MasonError; import com.metamug.mason.exception.MasonException; import com.metamug.mason.service.ConnectionProvider; + +import org.apache.taglibs.standard.tag.common.sql.ResultImpl; + import java.util.Enumeration; import java.util.Map; import java.util.TreeMap; + import javax.servlet.jsp.JspException; -import static javax.servlet.jsp.tagext.Tag.EVAL_PAGE; import javax.sql.DataSource; -import org.apache.taglibs.standard.tag.common.sql.ResultImpl; /** * @@ -528,95 +530,96 @@ */ public class ExecuteTagHandler extends RequestTag { - private String className; - private Object param; //input for execution sql result(ResultProcessable) or http request(RequestProcessable) - private String var; - private DataSource ds; + private static final long serialVersionUID = 1L; + private String className; + private Object param; //input for execution sql result(ResultProcessable) or http request(RequestProcessable) + private String var; + private DataSource ds; + + private boolean output; //default value + private String onerror; + + @Override + public int doEndTag() throws JspException { + + Response result = null; + try { + Class cls = Class.forName(className); + Object newInstance = cls.newInstance(); + ResultProcessable resProcessable; + RequestProcessable reqProcessable; + + if (ResultProcessable.class.isAssignableFrom(cls)) { + resProcessable = (ResultProcessable) newInstance; + if (param instanceof ResultImpl) { + ResultImpl ri = (ResultImpl) param; + //@TODO remove cast + Result sqlResult = new Result(ri.getRows(), ri.getColumnNames(), ri.getRowCount()); - private boolean output; //default value - private String onerror; + result = resProcessable.process(sqlResult); + } + } else if (RequestProcessable.class.isAssignableFrom(cls)) { - @Override - public int doEndTag() throws JspException { + reqProcessable = (RequestProcessable) newInstance; + if (param instanceof Request) { + Request masonReq = (Request) param; - Response result = null; - try { - Class cls = Class.forName(className); - Object newInstance = cls.newInstance(); - ResultProcessable resProcessable; - RequestProcessable reqProcessable; - - if (ResultProcessable.class.isAssignableFrom(cls)) { - resProcessable = (ResultProcessable) newInstance; - if (param instanceof ResultImpl) { - ResultImpl ri = (ResultImpl) param; - //@TODO remove cast - Result sqlResult = new Result(ri.getRows(), ri.getColumnNames(), ri.getRowCount()); - - result = resProcessable.process(sqlResult); - } - } else if (RequestProcessable.class.isAssignableFrom(cls)) { - - reqProcessable = (RequestProcessable) newInstance; - if (param instanceof Request) { - Request masonReq = (Request) param; - - Map requestParameters = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - masonReq.getParams().entrySet().forEach(entry -> { - String key = entry.getKey(); - String value = entry.getValue(); - requestParameters.put(key, value); - }); - Enumeration headerNames = request.getHeaderNames(); - Map requestHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - while (headerNames.hasMoreElements()) { - String header = headerNames.nextElement(); - requestHeaders.put(header, request.getHeader(header)); - } - ds = ConnectionProvider.getMasonDatasource(); - //no bus - result = reqProcessable.process(masonReq, ds, parameters); //@TODO add actual args and resource - } - } else { - throw new JspException("", new MasonException(MasonError.CLASS_NOT_IMPLEMENTED, - "Class " + cls + " isn't processable")); - } + Map requestParameters = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + masonReq.getParams().entrySet().forEach(entry -> { + String key = entry.getKey(); + String value = entry.getValue(); + requestParameters.put(key, value); + }); + Enumeration headerNames = request.getHeaderNames(); + Map requestHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + while (headerNames.hasMoreElements()) { + String header = headerNames.nextElement(); + requestHeaders.put(header, request.getHeader(header)); + } + ds = ConnectionProvider.getMasonDatasource(); + //no bus + result = reqProcessable.process(masonReq, ds, parameters); //@TODO add actual args and resource + } + } else { + throw new JspException("", new MasonException(MasonError.CLASS_NOT_IMPLEMENTED, + "Class " + cls + " isn't processable")); + } - // if Response object is returned, put payload in bus and mason output - addToBus(var, result); + // if Response object is returned, put payload in bus and mason output + addToBus(var, result); - if (output) { - addToOutput(var, result); - } + if (output) { + addToOutput(var, result); + } - } catch (Exception ex) { - if (onerror == null) { - throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, ex.getMessage())); - } else { - throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, onerror)); - } - } + } catch (Exception ex) { + if (onerror == null) { + throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, ex.getMessage())); + } else { + throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, onerror)); + } + } - return EVAL_PAGE; - } + return EVAL_PAGE; + } - public void setClassName(String className) { - this.className = className; - } + public void setClassName(String className) { + this.className = className; + } - public void setOnerror(String onError) { - this.onerror = onError; - } + public void setOnerror(String onError) { + this.onerror = onError; + } - public void setParam(Object param) { - this.param = param; - } + public void setParam(Object param) { + this.param = param; + } - public void setVar(String var) { - this.var = var; - } + public void setVar(String var) { + this.var = var; + } - public void setOutput(boolean output) { - this.output = output; - } + public void setOutput(boolean output) { + this.output = output; + } } \ No newline at end of file diff --git a/src/main/java/com/metamug/mason/tag/HeaderTag.java b/src/main/java/com/metamug/mason/tag/HeaderTag.java index 02a3eba3..713157bb 100644 --- a/src/main/java/com/metamug/mason/tag/HeaderTag.java +++ b/src/main/java/com/metamug/mason/tag/HeaderTag.java @@ -511,40 +511,40 @@ You should also get your employer (if you work as a programmer) or your import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.BodyTagSupport; -import static javax.servlet.jsp.tagext.Tag.EVAL_PAGE; /** * * @author pc */ public class HeaderTag extends BodyTagSupport { - private String name; - private String value; - protected RequestTag parent; - - @Override - public int doEndTag() throws JspException { - parent = (RequestTag) getParent(); - if (parent == null) { - throw new JspTagException("Header Tag doesnt have a valid parent!"); - } - - if (value == null) { - value = getBodyContent().getString().trim(); - } - - if (this.value.length() > 0) { - parent.addHeader(name, this.value); - } - - return EVAL_PAGE; - } - - public void setName(String n) { - name = n; - } - - public void setValue(Object v) { - value = (String) v; - } + private static final long serialVersionUID = 1L; + private String name; + private String value; + protected RequestTag parent; + + @Override + public int doEndTag() throws JspException { + parent = (RequestTag) getParent(); + if (parent == null) { + throw new JspTagException("Header Tag doesnt have a valid parent!"); + } + + if (value == null) { + value = getBodyContent().getString().trim(); + } + + if (this.value.length() > 0) { + parent.addHeader(name, this.value); + } + + return EVAL_PAGE; + } + + public void setName(String n) { + name = n; + } + + public void setValue(Object v) { + value = (String) v; + } } \ No newline at end of file diff --git a/src/main/java/com/metamug/mason/tag/ParamTagHandler.java b/src/main/java/com/metamug/mason/tag/ParamTagHandler.java index 8f445991..5592d67e 100644 --- a/src/main/java/com/metamug/mason/tag/ParamTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/ParamTagHandler.java @@ -509,13 +509,14 @@ import com.metamug.entity.Request; import com.metamug.mason.exception.MasonError; import com.metamug.mason.exception.MasonException; + import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; + import javax.servlet.jsp.JspException; -import static javax.servlet.jsp.tagext.Tag.EVAL_PAGE; /** * @@ -523,30 +524,31 @@ */ public class ParamTagHandler extends RestTag { - private String name; - private String type; - private Boolean isRequired; - private Double max; - private Double min; - private Integer maxLen; - private Integer minLen; - private String pattern; - private String defaultValue; - private String value; + private static final long serialVersionUID = 1L; + private String name; + private String type; + private Boolean isRequired; + private Double max; + private Double min; + private Integer maxLen; + private Integer minLen; + private String pattern; + private String defaultValue; + private String value; - /** - * This method is called after the JSP engine finished processing the tag. - * - * @return EVAL_PAGE if the JSP engine should continue evaluating the JSP - * page, otherwise return SKIP_PAGE. This method is automatically generated. - * Do not modify this method. Instead, modify the methods that this method - * calls. - * @throws javax.servlet.jsp.JspException - */ - @Override - public int doEndTag() throws JspException { - Request mtgReq = (Request) pageContext.getRequest().getAttribute("mtgReq"); - /*if (value == null && isRequired != null && isRequired) { + /** + * This method is called after the JSP engine finished processing the tag. + * + * @return EVAL_PAGE if the JSP engine should continue evaluating the JSP + * page, otherwise return SKIP_PAGE. This method is automatically generated. + * Do not modify this method. Instead, modify the methods that this method + * calls. + * @throws javax.servlet.jsp.JspException + */ + @Override + public int doEndTag() throws JspException { + Request mtgReq = (Request) pageContext.getRequest().getAttribute("mtgReq"); + /*if (value == null && isRequired != null && isRequired) { if (defaultValue == null) { throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); } else { @@ -556,181 +558,181 @@ public int doEndTag() throws JspException { } }*/ - if (value == null) { - if (defaultValue != null) { - mtgReq.setDefault(name, defaultValue); - release(); - return EVAL_PAGE; - } else { - if (isRequired != null && isRequired) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); - } - } - } + if (value == null) { + if (defaultValue != null) { + mtgReq.setDefault(name, defaultValue); + release(); + return EVAL_PAGE; + } else { + if (isRequired != null && isRequired) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); + } + } + } - //continue validation if value != null - if (pattern != null) { - try { - if (!value.matches(pattern)) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Input value doesn't match with specified pattern of " + name + " parameter")); - } - } catch (PatternSyntaxException ex) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Incorrect pattern syntax of " + name + " parameter")); - } - } - if (type != null) { - Pattern regexPattern; - Matcher matcher; - switch (type.toLowerCase()) { - case "date": - if (pattern == null) { - try { - validateDateTime(value, "yyyy-MM-dd"); - } catch (ParseException ex) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); - } - } - break; - case "datetime": - if (pattern == null) { - try { - validateDateTime(value, "yyyy-MM-dd HH:mm:ss"); - } catch (ParseException ex) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Incorrect datetime pattern of " + name + " parameter")); - } - } - break; - case "email": - String emailPattern - = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" - + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - regexPattern = Pattern.compile(emailPattern); + //continue validation if value != null + if (pattern != null) { + try { + if (!value.matches(pattern)) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Input value doesn't match with specified pattern of " + name + " parameter")); + } + } catch (PatternSyntaxException ex) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Incorrect pattern syntax of " + name + " parameter")); + } + } + if (type != null) { + Pattern regexPattern; + Matcher matcher; + switch (type.toLowerCase()) { + case "date": + if (pattern == null) { + try { + validateDateTime(value, "yyyy-MM-dd"); + } catch (ParseException ex) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); + } + } + break; + case "datetime": + if (pattern == null) { + try { + validateDateTime(value, "yyyy-MM-dd HH:mm:ss"); + } catch (ParseException ex) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Incorrect datetime pattern of " + name + " parameter")); + } + } + break; + case "email": + String emailPattern + = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + regexPattern = Pattern.compile(emailPattern); - matcher = regexPattern.matcher(value); - if (!matcher.matches()) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Invalid email input")); - } - break; - case "number": - try { - double val = Double.parseDouble(value); - if (max != null) { - double maxVal = max; - if (val > maxVal) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Max value allowed for " + name + " is " + maxVal)); - } - } - if (min != null) { - double minVal = min; - if (val < minVal) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Min value allowed for " + name + " is " + minVal)); - } - } - } catch (NumberFormatException ex) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Empty or invalid parameter \'" + name + "\' value")); - } - break; - case "text": - if (maxLen != null) { - double maxLength = maxLen; - try { - if (value.length() > maxLength) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Input " + value + " can be " + maxLength + " character long for " + name + " parameter")); - } - } catch (NullPointerException ex) { - if (isRequired != null) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); - } - } - } - if (minLen != null) { - double minLength = minLen; - if (value.length() < minLength) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Input value must be " + minLength + " character long for " + name + " parameter")); - } - } - break; - case "time": - if (pattern == null) { - try { - validateDateTime(value, "HH:mm:ss"); - } catch (ParseException ex) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Incorrect time pattern of " + name + " parameter")); - } - } - break; - case "url": - String urlPattern = "(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)*(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}]{2,})))(?::\\d{2,5})?(?:/[^\\s]*)?"; - regexPattern = Pattern.compile(urlPattern); - matcher = regexPattern.matcher(value); - if (!matcher.matches()) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Invalid URL input")); - } - break; - default: - } - } - release(); - return EVAL_PAGE; - } + matcher = regexPattern.matcher(value); + if (!matcher.matches()) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Invalid email input")); + } + break; + case "number": + try { + double val = Double.parseDouble(value); + if (max != null) { + double maxVal = max; + if (val > maxVal) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Max value allowed for " + name + " is " + maxVal)); + } + } + if (min != null) { + double minVal = min; + if (val < minVal) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Min value allowed for " + name + " is " + minVal)); + } + } + } catch (NumberFormatException ex) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Empty or invalid parameter \'" + name + "\' value")); + } + break; + case "text": + if (maxLen != null) { + double maxLength = maxLen; + try { + if (value.length() > maxLength) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Input " + value + " can be " + maxLength + " character long for " + name + " parameter")); + } + } catch (NullPointerException ex) { + if (isRequired != null) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); + } + } + } + if (minLen != null) { + double minLength = minLen; + if (value.length() < minLength) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Input value must be " + minLength + " character long for " + name + " parameter")); + } + } + break; + case "time": + if (pattern == null) { + try { + validateDateTime(value, "HH:mm:ss"); + } catch (ParseException ex) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Incorrect time pattern of " + name + " parameter")); + } + } + break; + case "url": + String urlPattern = "(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}0-9]+-?)*[a-z\\x{00a1}-\\x{ffff}0-9]+)*(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}]{2,})))(?::\\d{2,5})?(?:/[^\\s]*)?"; + regexPattern = Pattern.compile(urlPattern); + matcher = regexPattern.matcher(value); + if (!matcher.matches()) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, "Invalid URL input")); + } + break; + default: + } + } + release(); + return EVAL_PAGE; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public void setIsRequired(boolean required) { - this.isRequired = required; - } + public void setIsRequired(boolean required) { + this.isRequired = required; + } - public void setMax(String max) { - this.max = Double.parseDouble(max); - } + public void setMax(String max) { + this.max = Double.parseDouble(max); + } - public void setMin(String min) { - this.min = Double.parseDouble(min); - } + public void setMin(String min) { + this.min = Double.parseDouble(min); + } - public void setMaxLen(String maxLen) { - this.maxLen = Integer.parseInt(maxLen); - } + public void setMaxLen(String maxLen) { + this.maxLen = Integer.parseInt(maxLen); + } - public void setMinLen(String minLen) { - this.minLen = Integer.parseInt(minLen); - } + public void setMinLen(String minLen) { + this.minLen = Integer.parseInt(minLen); + } - public void setPattern(String pattern) { - this.pattern = pattern; - } + public void setPattern(String pattern) { + this.pattern = pattern; + } - public void setValue(String value) { - if (value.isEmpty()) { - this.value = null; - } else { - this.value = value; - } - } + public void setValue(String value) { + if (value.isEmpty()) { + this.value = null; + } else { + this.value = value; + } + } - public void setDefaultValue(String defaultValue) { - if (defaultValue.isEmpty()) { - this.defaultValue = null; - } else { - this.defaultValue = defaultValue; - } - } + public void setDefaultValue(String defaultValue) { + if (defaultValue.isEmpty()) { + this.defaultValue = null; + } else { + this.defaultValue = defaultValue; + } + } - private void validateDateTime(String value, String format) throws ParseException, JspException { - try { - SimpleDateFormat sdf = new SimpleDateFormat(format); - sdf.setLenient(false); - sdf.parse(value); - } catch (NullPointerException ex) { - if (isRequired != null) { - throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); - } - } - } + private void validateDateTime(String value, String format) throws ParseException, JspException { + try { + SimpleDateFormat sdf = new SimpleDateFormat(format); + sdf.setLenient(false); + sdf.parse(value); + } catch (NullPointerException ex) { + if (isRequired != null) { + throw new JspException("", new MasonException(MasonError.INPUT_VALIDATION_ERROR, name + " parameter can't be null")); + } + } + } } diff --git a/src/main/java/com/metamug/mason/tag/RequestTag.java b/src/main/java/com/metamug/mason/tag/RequestTag.java index b564cea5..6a85bdb1 100644 --- a/src/main/java/com/metamug/mason/tag/RequestTag.java +++ b/src/main/java/com/metamug/mason/tag/RequestTag.java @@ -517,27 +517,28 @@ You should also get your employer (if you work as a programmer) or your */ public class RequestTag extends RestTag { - protected String method; - protected Map headers = new HashMap<>(); //to set headers for request/response depending on the tag. - protected Map parameters = new HashMap<>(); - - public void setMethod(String m) { - method = m; - } - - public void setHeaders(Map headers) { - this.headers = headers; - } - - public void addHeader(String name, String value) { - headers.put(name, value); - } - - public void setParameters(Map parameters) { - this.parameters = parameters; - } - - public void addParameter(String name, Object value) { - parameters.put(name, value); - } + private static final long serialVersionUID = 1L; + protected String method; + protected Map headers = new HashMap<>(); //to set headers for request/response depending on the tag. + protected Map parameters = new HashMap<>(); + + public void setMethod(String m) { + method = m; + } + + public void setHeaders(Map headers) { + this.headers = headers; + } + + public void addHeader(String name, String value) { + headers.put(name, value); + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } + + public void addParameter(String name, Object value) { + parameters.put(name, value); + } } \ No newline at end of file diff --git a/src/main/java/com/metamug/mason/tag/RequestTagHandler.java b/src/main/java/com/metamug/mason/tag/RequestTagHandler.java index f8692a66..c305800f 100644 --- a/src/main/java/com/metamug/mason/tag/RequestTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/RequestTagHandler.java @@ -506,18 +506,20 @@ */ package com.metamug.mason.tag; +import static com.metamug.mason.Router.MASON_REQUEST; +import static com.metamug.mason.entity.response.MasonOutput.HEADER_JSON; + import com.metamug.entity.Attachment; import com.metamug.entity.Request; import com.metamug.entity.Response; -import static com.metamug.mason.Router.MASON_REQUEST; -import com.metamug.mason.entity.response.FileOutput; import com.metamug.mason.entity.response.DatasetOutput; +import com.metamug.mason.entity.response.FileOutput; import com.metamug.mason.entity.response.JSONOutput; import com.metamug.mason.entity.response.MasonOutput; -import static com.metamug.mason.entity.response.MasonOutput.HEADER_JSON; import com.metamug.mason.entity.response.ResponeBuilder; import com.metamug.mason.entity.response.XMLOutput; import com.metamug.mason.service.UploaderService; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -533,6 +535,7 @@ import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; + import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; @@ -542,127 +545,128 @@ */ public class RequestTagHandler extends RequestTag { - private boolean item; - private boolean evaluate; + private static final long serialVersionUID = 1L; + private boolean item; + private boolean evaluate; + + private Request masonRequest; + + protected ResourceTagHandler parent; + + @Override + public int doStartTag() throws JspException { + super.doStartTag(); + + parent = (ResourceTagHandler)getParent(); + //add http method of this request tag to parent's list + parent.addChildMethod(method); - private Request masonRequest; - - protected ResourceTagHandler parent; + masonRequest = (Request) request.getAttribute(MASON_REQUEST); - @Override - public int doStartTag() throws JspException { - super.doStartTag(); - - parent = (ResourceTagHandler)getParent(); - //add http method of this request tag to parent's list - parent.addChildMethod(method); - - masonRequest = (Request) request.getAttribute(MASON_REQUEST); + if (method.equalsIgnoreCase(masonRequest.getMethod())) { + evaluate = (masonRequest.getId() != null) == item; //evaluate + if (evaluate) { + //initialize only when this request is executed. + //Holds var names to be printed in output + //to maintain the order of insertion + Map output = new HashMap<>(); + pageContext.setAttribute(MASON_OUTPUT, output); - if (method.equalsIgnoreCase(masonRequest.getMethod())) { - evaluate = (masonRequest.getId() != null) == item; //evaluate - if (evaluate) { - //initialize only when this request is executed. - //Holds var names to be printed in output - //to maintain the order of insertion - Map output = new HashMap<>(); - pageContext.setAttribute(MASON_OUTPUT, output); + //@TODO Also check for multipart + if (method.equalsIgnoreCase("POST")) {//upload file if incoming file + UploaderService uploader = new UploaderService(pageContext); + uploader.upload(); + } - //@TODO Also check for multipart - if (method.equalsIgnoreCase("POST")) {//upload file if incoming file - UploaderService uploader = new UploaderService(pageContext); - uploader.upload(); - } + return EVAL_BODY_INCLUDE; + } + } - return EVAL_BODY_INCLUDE; - } - } + return SKIP_BODY; + } - return SKIP_BODY; - } + @Override + public int doEndTag() throws JspException { + if (evaluate) { + processOutput(); + return SKIP_PAGE; + } else { + return EVAL_PAGE; + } + } - @Override - public int doEndTag() throws JspException { - if (evaluate) { - processOutput(); - return SKIP_PAGE; - } else { - return EVAL_PAGE; - } - } + private void processOutput() { + String header = request.getHeader(HEADER_ACCEPT) == null ? HEADER_JSON : request.getHeader(HEADER_ACCEPT); - private void processOutput() { - String header = request.getHeader(HEADER_ACCEPT) == null ? HEADER_JSON : request.getHeader(HEADER_ACCEPT); + boolean hasAttachment = false; - boolean hasAttachment = false; + Map outputMap = (Map) pageContext.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE); + //get response objects to be printed in output + for (Entry tag : outputMap.entrySet()) { + //check for Attachment + if (tag.getValue() instanceof Attachment) { + hasAttachment = true; + break; + } + } - Map outputMap = (Map) pageContext.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE); - //get response objects to be printed in output - for (Entry tag : outputMap.entrySet()) { - //check for Attachment - if (tag.getValue() instanceof Attachment) { - hasAttachment = true; - break; - } - } + //set response headers + if(headers != null) { + headers.entrySet().forEach( entry -> { + response.setHeader(entry.getKey(), entry.getValue()); + }); + } - //set response headers - if(headers != null) { - headers.entrySet().forEach( entry -> { - response.setHeader(entry.getKey(), entry.getValue()); - }); - } - - //write response - try (OutputStream outputStream = response.getOutputStream()) { + //write response + try (OutputStream outputStream = response.getOutputStream()) { - if (!hasAttachment) { + if (!hasAttachment) { - MasonOutput output = null; - List list = Arrays.asList(header.split("/")); - if (list.contains("xml")) { //Accept: application/xml, text/xml - output = new XMLOutput(); - } else if (list.contains("json+dataset")) { //Accept: application/json+dataset - output = new DatasetOutput(); - } else { //Accept: application/json OR default - output = new JSONOutput(); - } + MasonOutput output = null; + List list = Arrays.asList(header.split("/")); + if (list.contains("xml")) { //Accept: application/xml, text/xml + output = new XMLOutput(); + } else if (list.contains("json+dataset")) { //Accept: application/json+dataset + output = new DatasetOutput(); + } else { //Accept: application/json OR default + output = new JSONOutput(); + } - //cannnot use print writer since it we are already using outputstream - Response masonResponse = new ResponeBuilder(output).build(outputMap); - masonResponse.getHeaders().forEach((k, v) -> response.setHeader(k, v)); - byte[] bytes = output.format(masonResponse).getBytes(StandardCharsets.UTF_8); - response.setContentLength(bytes.length); - outputStream.write(bytes); - outputStream.flush(); + //cannnot use print writer since it we are already using outputstream + Response masonResponse = new ResponeBuilder(output).build(outputMap); + masonResponse.getHeaders().forEach((k, v) -> response.setHeader(k, v)); + byte[] bytes = output.format(masonResponse).getBytes(StandardCharsets.UTF_8); + response.setContentLength(bytes.length); + outputStream.write(bytes); + outputStream.flush(); - } else { - //has file in response - Response masonResponse = new ResponeBuilder(FileOutput.class).build(outputMap); - masonResponse.getHeaders().forEach((k, v) -> response.setHeader(k, v)); - InputStream inputStream = ((Attachment) masonResponse.getPayload()).getStream(); - try (ReadableByteChannel in = Channels.newChannel(inputStream); - WritableByteChannel out = Channels.newChannel(outputStream);) { - /** - * Don't set Content Length. Max buffer for output stream is - * 2KB and it is flushed - */ + } else { + //has file in response + Response masonResponse = new ResponeBuilder(FileOutput.class).build(outputMap); + masonResponse.getHeaders().forEach((k, v) -> response.setHeader(k, v)); + InputStream inputStream = ((Attachment) masonResponse.getPayload()).getStream(); + try (ReadableByteChannel in = Channels.newChannel(inputStream); + WritableByteChannel out = Channels.newChannel(outputStream);) { + /** + * Don't set Content Length. Max buffer for output stream is + * 2KB and it is flushed + */ - ByteBuffer buffer = ByteBuffer.allocate(2048); //2KB buffer - while (in.read(buffer) != -1) { - buffer.flip(); - out.write(buffer); - buffer.clear(); - } - } - } - } catch (IOException ex) { - //@TODO write error response if there is an error in file read or something else - Logger.getLogger(RequestTagHandler.class.getName()).log(Level.SEVERE, null, ex); - } - } + ByteBuffer buffer = ByteBuffer.allocate(2048); //2KB buffer + while (in.read(buffer) != -1) { + buffer.flip(); + out.write(buffer); + buffer.clear(); + } + } + } + } catch (IOException ex) { + //@TODO write error response if there is an error in file read or something else + Logger.getLogger(RequestTagHandler.class.getName()).log(Level.SEVERE, null, ex); + } + } - public void setItem(boolean i) { - item = i; - } + public void setItem(boolean i) { + item = i; + } } diff --git a/src/main/java/com/metamug/mason/tag/ResourceTagHandler.java b/src/main/java/com/metamug/mason/tag/ResourceTagHandler.java index 39f2473b..2732691a 100644 --- a/src/main/java/com/metamug/mason/tag/ResourceTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/ResourceTagHandler.java @@ -506,154 +506,160 @@ */ package com.metamug.mason.tag; -import com.metamug.entity.Request; -import com.metamug.entity.Resource; -import com.metamug.mason.Router; import static com.metamug.mason.Router.CONNECTION_PROVIDER; import static com.metamug.mason.Router.MASON_REQUEST; import static com.metamug.mason.entity.response.MasonOutput.HEADER_JSON; + +import com.metamug.entity.Request; +import com.metamug.entity.Resource; +import com.metamug.mason.Router; import com.metamug.mason.exception.MasonError; import com.metamug.mason.exception.MasonException; import com.metamug.mason.service.AuthService; import com.metamug.mason.service.ConnectionProvider; + +import org.apache.commons.lang3.StringUtils; + import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; + import javax.servlet.jsp.JspException; -import org.apache.commons.lang3.StringUtils; /** * * @author anishhirlekar */ public class ResourceTagHandler extends RestTag { - - private Request masonRequest; - private String auth; - private String parentName; - private transient AuthService authService; + private static final long serialVersionUID = 1L; + + private Request masonRequest; + + private String auth; + private String parentName; + private transient AuthService authService; + + public static final int STATUS_METHOD_NOT_ALLOWED = 405; + public static final String MSG_METHOD_NOT_ALLOWED = "Method not allowed"; + public static final int STATUS_RESOURCE_NOT_FOUND = 404; + public static final String MSG_RESOURCE_NOT_FOUND = "Resource not found"; + + public static final String ACCESS_DENIED = "Access Denied due to unauthorization"; + public static final String ACCESS_FORBIDDEN = "Access Denied due to unauthorization!"; + public static final String BEARER_ = "Bearer "; + + private List childMethods = new ArrayList<>(); //holds http methods of child request tags + + public void setAuth(String auth) { + this.auth = auth; + } + + public void addChildMethod(String method) { + childMethods.add(method.toLowerCase()); + } + + /** + * cannot name is setParent since Tag Support class already exists + * @param parentName + */ + public void setParentName(String parentName) { + this.parentName = parentName; + } + + @Override + public int doStartTag() throws JspException { + super.doStartTag(); + + if (StringUtils.isNotBlank(auth)) { + processAuth(); + } - public static final int STATUS_METHOD_NOT_ALLOWED = 405; - public static final String MSG_METHOD_NOT_ALLOWED = "Method not allowed"; - public static final int STATUS_RESOURCE_NOT_FOUND = 404; - public static final String MSG_RESOURCE_NOT_FOUND = "Resource not found"; - - public static final String ACCESS_DENIED = "Access Denied due to unauthorization"; - public static final String ACCESS_FORBIDDEN = "Access Denied due to unauthorization!"; - public static final String BEARER_ = "Bearer "; - - private List childMethods = new ArrayList<>(); //holds http methods of child request tags + masonRequest = (Request) request.getAttribute(MASON_REQUEST); + Resource parent = masonRequest.getParent(); + if (parent != null && !parent.getName().equalsIgnoreCase(this.parentName)) { + throw new JspException("Parent resource not found", new MasonException(MasonError.PARENT_RESOURCE_MISSING)); + } - public void setAuth(String auth) { - this.auth = auth; - } - - public void addChildMethod(String method) { - childMethods.add(method.toLowerCase()); - } - - /** - * cannot name is setParent since Tag Support class already exists - * @param parentName - */ - public void setParentName(String parentName) { - this.parentName = parentName; - } + return EVAL_BODY_INCLUDE; + } - @Override - public int doStartTag() throws JspException { - super.doStartTag(); - - if (StringUtils.isNotBlank(auth)) { - processAuth(); - } + @Override + public int doEndTag() throws JspException { + String requestMethod = masonRequest.getMethod().toLowerCase(); - masonRequest = (Request) request.getAttribute(MASON_REQUEST); - Resource parent = masonRequest.getParent(); - if (parent != null && !parent.getName().equalsIgnoreCase(this.parentName)) { - throw new JspException("Parent resource not found", new MasonException(MasonError.PARENT_RESOURCE_MISSING)); - } + if(!childMethods.contains(requestMethod)) { + //incoming request has method which is not handled by any child + print405(); + } else { + //incoming request has method which is handled by a child + //but the flow reached the end tag of + print404(); + } - return EVAL_BODY_INCLUDE; - } + return SKIP_PAGE; + } - @Override - public int doEndTag() throws JspException { - String requestMethod = masonRequest.getMethod().toLowerCase(); - - if(!childMethods.contains(requestMethod)) { - //incoming request has method which is not handled by any child - print405(); - } else { - //incoming request has method which is handled by a child - //but the flow reached the end tag of - print404(); - } - - return SKIP_PAGE; - } - - private void print404() { - response.setContentType(HEADER_JSON); - response.setStatus(STATUS_RESOURCE_NOT_FOUND); - try { - pageContext.getOut().print("{\"message\":\"" + MSG_RESOURCE_NOT_FOUND + "\",\"status\":" - + STATUS_RESOURCE_NOT_FOUND + "}"); - } catch (IOException ex) { - Logger.getLogger(ResourceTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } - } + private void print404() { + response.setContentType(HEADER_JSON); + response.setStatus(STATUS_RESOURCE_NOT_FOUND); + try { + pageContext.getOut().print("{\"message\":\"" + MSG_RESOURCE_NOT_FOUND + "\",\"status\":" + + STATUS_RESOURCE_NOT_FOUND + "}"); + } catch (IOException ex) { + Logger.getLogger(ResourceTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } + } - private void print405() { -// String header = request.getHeader(HEADER_ACCEPT) == null ? HEADER_JSON : request.getHeader(HEADER_ACCEPT); - response.setContentType(HEADER_JSON); - response.setStatus(STATUS_METHOD_NOT_ALLOWED); - try { -// if (Arrays.asList(header.split("/")).contains("xml")) { -// StringBuilder xmlBuilder = new StringBuilder(); -// xmlBuilder.append(""); -// xmlBuilder.append(""); -// xmlBuilder.append("\n\t"); -// xmlBuilder.append(STATUS_METHOD_NOT_ALLOWED); -// xmlBuilder.append(""); -// xmlBuilder.append("\n\t"); -// xmlBuilder.append(MSG_METHOD_NOT_ALLOWED); -// xmlBuilder.append(""); -// xmlBuilder.append("\n"); -// pageContext.getOut().print(xmlBuilder.toString()); -// } else { - pageContext.getOut().print("{\"message\":\"" + MSG_METHOD_NOT_ALLOWED + "\",\"status\":" - + STATUS_METHOD_NOT_ALLOWED + "}"); -// } - } catch (IOException ex) { - Logger.getLogger(ResourceTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - } - } + private void print405() { + // String header = request.getHeader(HEADER_ACCEPT) == null ? HEADER_JSON : request.getHeader(HEADER_ACCEPT); + response.setContentType(HEADER_JSON); + response.setStatus(STATUS_METHOD_NOT_ALLOWED); + try { + // if (Arrays.asList(header.split("/")).contains("xml")) { + // StringBuilder xmlBuilder = new StringBuilder(); + // xmlBuilder.append(""); + // xmlBuilder.append(""); + // xmlBuilder.append("\n\t"); + // xmlBuilder.append(STATUS_METHOD_NOT_ALLOWED); + // xmlBuilder.append(""); + // xmlBuilder.append("\n\t"); + // xmlBuilder.append(MSG_METHOD_NOT_ALLOWED); + // xmlBuilder.append(""); + // xmlBuilder.append("\n"); + // pageContext.getOut().print(xmlBuilder.toString()); + // } else { + pageContext.getOut().print("{\"message\":\"" + MSG_METHOD_NOT_ALLOWED + "\",\"status\":" + + STATUS_METHOD_NOT_ALLOWED + "}"); + // } + } catch (IOException ex) { + Logger.getLogger(ResourceTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + } + } - private void processAuth() throws JspException { - String header = request.getHeader("Authorization"); - if (header == null) { - throw new JspException(ACCESS_DENIED, new MasonException(MasonError.ROLE_ACCESS_DENIED)); - } - Request masonReq = (Request) request.getAttribute(MASON_REQUEST); - authService = new AuthService((ConnectionProvider) request.getAttribute(CONNECTION_PROVIDER)); - try { - if (header.contains("Basic ")) { - String authQuery = (String) request.getServletContext().getAttribute(Router.MTG_AUTH_BASIC); - masonReq.setUid(authService.validateBasic(header, auth, authQuery.trim())); - } else if (header.contains(BEARER_)) { - String bearerToken = header.replaceFirst(BEARER_, ""); - //check jwt format - //validateJwt - check aud against val, exp - masonReq.setUid(authService.validateBearer(bearerToken.trim(), auth)); - } else { - throw new JspException(ACCESS_DENIED, new MasonException(MasonError.ROLE_ACCESS_DENIED)); - } - } catch (IllegalArgumentException ex) { - throw new JspException(ACCESS_DENIED, new MasonException(MasonError.ROLE_ACCESS_DENIED)); - } - } + private void processAuth() throws JspException { + String header = request.getHeader("Authorization"); + if (header == null) { + throw new JspException(ACCESS_DENIED, new MasonException(MasonError.ROLE_ACCESS_DENIED)); + } + Request masonReq = (Request) request.getAttribute(MASON_REQUEST); + authService = new AuthService((ConnectionProvider) request.getAttribute(CONNECTION_PROVIDER)); + try { + if (header.contains("Basic ")) { + String authQuery = (String) request.getServletContext().getAttribute(Router.MTG_AUTH_BASIC); + masonReq.setUid(authService.validateBasic(header, auth, authQuery.trim())); + } else if (header.contains(BEARER_)) { + String bearerToken = header.replaceFirst(BEARER_, ""); + //check jwt format + //validateJwt - check aud against val, exp + masonReq.setUid(authService.validateBearer(bearerToken.trim(), auth)); + } else { + throw new JspException(ACCESS_DENIED, new MasonException(MasonError.ROLE_ACCESS_DENIED)); + } + } catch (IllegalArgumentException ex) { + throw new JspException(ACCESS_DENIED, new MasonException(MasonError.ROLE_ACCESS_DENIED)); + } + } } \ No newline at end of file diff --git a/src/main/java/com/metamug/mason/tag/RestTag.java b/src/main/java/com/metamug/mason/tag/RestTag.java index e1716f2c..edd906be 100644 --- a/src/main/java/com/metamug/mason/tag/RestTag.java +++ b/src/main/java/com/metamug/mason/tag/RestTag.java @@ -507,7 +507,9 @@ package com.metamug.mason.tag; import com.metamug.entity.Response; + import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; @@ -521,59 +523,60 @@ */ public class RestTag extends BodyTagSupport implements TryCatchFinally { - public static final String HEADER_ACCEPT = "Accept"; -// public static final String MASON_BUS = "bus"; - public static final String MASON_OUTPUT = "output"; - public static final String EXTRACTED = "extract"; + private static final long serialVersionUID = 1L; + public static final String HEADER_ACCEPT = "Accept"; + // public static final String MASON_BUS = "bus"; + public static final String MASON_OUTPUT = "output"; + public static final String EXTRACTED = "extract"; - protected HttpServletRequest request; - protected HttpServletResponse response; + protected HttpServletRequest request; + protected HttpServletResponse response; - protected PageContext context; //For Mocking https://stackoverflow.com/a/17474381/1097600 - //WARNING: DO NOT USE context object in subclasses + protected PageContext context; //For Mocking https://stackoverflow.com/a/17474381/1097600 + //WARNING: DO NOT USE context object in subclasses - public RestTag() { - super(); - this.context = super.pageContext; - } + public RestTag() { + super(); + this.context = super.pageContext; + } - @Override - public int doStartTag() throws JspException { - request = (HttpServletRequest) pageContext.getRequest(); - response = (HttpServletResponse) pageContext.getResponse(); - return EVAL_BODY_INCLUDE; - } + @Override + public int doStartTag() throws JspException { + request = (HttpServletRequest) pageContext.getRequest(); + response = (HttpServletResponse) pageContext.getResponse(); + return EVAL_BODY_INCLUDE; + } - @Override - public void doCatch(Throwable throwable) throws Throwable { - throw throwable; - } + @Override + public void doCatch(Throwable throwable) throws Throwable { + throw throwable; + } - @Override - public void doFinally() { - } + @Override + public void doFinally() { + } - protected void addToBus(String var, Object result) { - if (result instanceof Response) { - pageContext.setAttribute(var, ((Response) result).getPayload()); - } else { - pageContext.setAttribute(var, result); - } - } + protected void addToBus(String var, Object result) { + if (result instanceof Response) { + pageContext.setAttribute(var, ((Response) result).getPayload()); + } else { + pageContext.setAttribute(var, result); + } + } - protected void addToOutput(String var, Object value) { - Map masonOutput = (Map) pageContext.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE); + protected void addToOutput(String var, Object value) { + Map masonOutput = (Map) pageContext.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE); - if (value instanceof Response) { - Response res = (Response) value; - if(null != res.getPayload()){ - masonOutput.put(var, res.getPayload()); - } - if(null != res.getHeaders()){ - res.getHeaders().forEach((k, v) -> response.setHeader(k, v)); - } - } else { - masonOutput.put(var, value); - } - } + if (value instanceof Response) { + Response res = (Response) value; + if(null != res.getPayload()){ + masonOutput.put(var, res.getPayload()); + } + if(null != res.getHeaders()){ + res.getHeaders().forEach((k, v) -> response.setHeader(k, v)); + } + } else { + masonOutput.put(var, value); + } + } } \ No newline at end of file diff --git a/src/main/java/com/metamug/mason/tag/ScriptTagHandler.java b/src/main/java/com/metamug/mason/tag/ScriptTagHandler.java index 33eab168..8202554e 100644 --- a/src/main/java/com/metamug/mason/tag/ScriptTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/ScriptTagHandler.java @@ -8,17 +8,19 @@ import com.metamug.entity.Request; import com.metamug.mason.exception.MasonError; import com.metamug.mason.exception.MasonException; + import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import groovy.util.ResourceException; import groovy.util.ScriptException; + import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; + import javax.servlet.jsp.JspException; -import javax.servlet.jsp.PageContext; /** * @@ -26,47 +28,48 @@ */ public class ScriptTagHandler extends RestTag { - private String file, var; + private static final long serialVersionUID = 1L; + private String file, var; - public void setFile(String file) { - this.file = file; - } + public void setFile(String file) { + this.file = file; + } - /** - * - * @param var - */ - public void setVar(String var) { - this.var = var; - } + /** + * + * @param var + */ + public void setVar(String var) { + this.var = var; + } - @Override - public int doStartTag() throws JspException { - super.doStartTag(); - runScript(); - return SKIP_BODY; - } + @Override + public int doStartTag() throws JspException { + super.doStartTag(); + runScript(); + return SKIP_BODY; + } - public void runScript() throws JspException { - try { - //file:/C:/tomcat9/webapps/mason-sample/WEB-INF/classes//WEB_INF/scripts/test.groovy - GroovyScriptEngine engine = new GroovyScriptEngine(new URL[]{ScriptTagHandler.class.getClassLoader().getResource("..")}); - Binding binding = new Binding(); - Request masonReq = (Request) request.getAttribute("mtgReq"); - binding.setVariable("_request", masonReq); -// Map masonBus = (Map) pageContext.getAttribute(MASON_BUS,PageContext.PAGE_SCOPE); - binding.setVariable("_context", pageContext); - Map object = new LinkedHashMap<>(); - binding.setVariable(var, object); //for the output - engine.run(SCRIPT_ROOT + file, binding); - //output to bus - addToBus(var, object); - } catch (SecurityException | ResourceException | ScriptException | IllegalArgumentException ex) { - Logger.getLogger(ScriptTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); - throw new JspException("", new MasonException(MasonError.SCRIPT_ERROR)); - } - } + public void runScript() throws JspException { + try { + //file:/C:/tomcat9/webapps/mason-sample/WEB-INF/classes//WEB_INF/scripts/test.groovy + GroovyScriptEngine engine = new GroovyScriptEngine(new URL[]{ScriptTagHandler.class.getClassLoader().getResource("..")}); + Binding binding = new Binding(); + Request masonReq = (Request) request.getAttribute("mtgReq"); + binding.setVariable("_request", masonReq); + // Map masonBus = (Map) pageContext.getAttribute(MASON_BUS,PageContext.PAGE_SCOPE); + binding.setVariable("_context", pageContext); + Map object = new LinkedHashMap<>(); + binding.setVariable(var, object); //for the output + engine.run(SCRIPT_ROOT + file, binding); + //output to bus + addToBus(var, object); + } catch (SecurityException | ResourceException | ScriptException | IllegalArgumentException ex) { + Logger.getLogger(ScriptTagHandler.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); + throw new JspException("", new MasonException(MasonError.SCRIPT_ERROR)); + } + } - private static final String SCRIPT_ROOT = "scripts/"; + private static final String SCRIPT_ROOT = "scripts/"; } diff --git a/src/main/java/com/metamug/mason/tag/xrequest/BodyTagHandler.java b/src/main/java/com/metamug/mason/tag/xrequest/BodyTagHandler.java index 9a9caaec..a1d647ae 100644 --- a/src/main/java/com/metamug/mason/tag/xrequest/BodyTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/xrequest/BodyTagHandler.java @@ -509,7 +509,6 @@ import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.BodyTagSupport; -import static javax.servlet.jsp.tagext.TagSupport.findAncestorWithClass; /** * @@ -517,18 +516,20 @@ */ public class BodyTagHandler extends BodyTagSupport { - @Override - public int doEndTag() throws JspException { - XRequestTagHandler parent = (XRequestTagHandler) findAncestorWithClass(this, XRequestTagHandler.class); - if (parent == null) { - throw new JspTagException("X Body Tag outside X Request Tag"); - } + private static final long serialVersionUID = 1L; - String reqBodyContent = getBodyContent().getString().trim(); - if (reqBodyContent.length() > 0) { - parent.setRequestBody(reqBodyContent); - } + @Override + public int doEndTag() throws JspException { + XRequestTagHandler parent = (XRequestTagHandler) findAncestorWithClass(this, XRequestTagHandler.class); + if (parent == null) { + throw new JspTagException("X Body Tag outside X Request Tag"); + } - return EVAL_PAGE; - } + String reqBodyContent = getBodyContent().getString().trim(); + if (reqBodyContent.length() > 0) { + parent.setRequestBody(reqBodyContent); + } + + return EVAL_PAGE; + } } diff --git a/src/main/java/com/metamug/mason/tag/xrequest/ParamTagHandler.java b/src/main/java/com/metamug/mason/tag/xrequest/ParamTagHandler.java index 46521a5f..c4ce59f7 100644 --- a/src/main/java/com/metamug/mason/tag/xrequest/ParamTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/xrequest/ParamTagHandler.java @@ -507,10 +507,10 @@ package com.metamug.mason.tag.xrequest; import com.metamug.mason.tag.RequestTag; + import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.BodyTagSupport; -import static javax.servlet.jsp.tagext.Tag.EVAL_PAGE; /** * @@ -518,33 +518,34 @@ */ public class ParamTagHandler extends BodyTagSupport { - private String name; - private Object value; - protected RequestTag parent; + private static final long serialVersionUID = 1L; + private String name; + private Object value; + protected RequestTag parent; - @Override - public int doEndTag() throws JspException { + @Override + public int doEndTag() throws JspException { - parent = (RequestTag) getParent(); - if (parent == null) { - throw new JspTagException("Header Tag doesnt have a valid parent"); - } + parent = (RequestTag) getParent(); + if (parent == null) { + throw new JspTagException("Header Tag doesnt have a valid parent"); + } - if (value == null) { - value = getBodyContent().getString().trim(); - } + if (value == null) { + value = getBodyContent().getString().trim(); + } - parent.addParameter(name, this.value); + parent.addParameter(name, this.value); - return EVAL_PAGE; - } + return EVAL_PAGE; + } - public void setName(String n) { - name = n; - } + public void setName(String n) { + name = n; + } - public void setValue(Object v) { - value = v; - } + public void setValue(Object v) { + value = v; + } } diff --git a/src/main/java/com/metamug/mason/tag/xrequest/XRequestTagHandler.java b/src/main/java/com/metamug/mason/tag/xrequest/XRequestTagHandler.java index eee1612b..c44d6881 100644 --- a/src/main/java/com/metamug/mason/tag/xrequest/XRequestTagHandler.java +++ b/src/main/java/com/metamug/mason/tag/xrequest/XRequestTagHandler.java @@ -515,10 +515,11 @@ import com.metamug.mason.service.XRequestService; import com.metamug.mason.tag.RequestTag; import com.metamug.mason.tag.ResourceTagHandler; + import java.util.Map; + import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; -import static javax.servlet.jsp.tagext.Tag.EVAL_PAGE; /** * @@ -526,99 +527,100 @@ */ public class XRequestTagHandler extends RequestTag { - private String var; - private String url; - private String requestBody; - private String className; - - private boolean outputHeaders; - private boolean output; + private static final long serialVersionUID = 1L; + private String var; + private String url; + private String requestBody; + private String className; + + private boolean outputHeaders; + private boolean output; + + @Override + public int doEndTag() throws JspException { + //Accept header of mtg request + String acceptHeader = request.getHeader(HEADER_ACCEPT) == null + ? MasonOutput.HEADER_JSON : request.getHeader(HEADER_ACCEPT); + //Accept type of XRequest + String xAcceptType = "json"; + for (Map.Entry entry : headers.entrySet()) { + if (entry.getKey().equals(ResourceTagHandler.HEADER_ACCEPT) && entry.getValue().equals("application/xml")) { + //if Accept header of XRequest is application/xml + xAcceptType = "xml"; + } + } + + XRequestService xRequestService = new XRequestService(outputHeaders); + XResponse xresponse = null; + + switch (method) { + case "GET": + xresponse = xRequestService.get(url, headers, parameters); + break; + case "POST": + xresponse = xRequestService.post(url, headers, parameters, requestBody); + break; + case "PUT": + xresponse = xRequestService.put(url, headers, parameters, requestBody); + break; + case "DELETE": + xresponse = xRequestService.delete(url, parameters); + break; + default: + throw new JspTagException("Unsupported method \"" + method + "\"."); + } + + Response res = xresponse.getResponse(acceptHeader, xAcceptType); + + if(className!=null){ + //post processable classname is given + try { + Class cls = Class.forName(className); + if(ResponseProcessable.class.isAssignableFrom(cls)){ + ResponseProcessable responseProcessor = (ResponseProcessable)cls.newInstance(); + //get post processed response + res = responseProcessor.process(res); + } else { + throw new JspException("", new MasonException(MasonError.RESPONSE_PROCESSABLE_NOT_IMPLEMENTED, + "Class " + cls + " is not Response processable")); + } + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { + throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, ex.getMessage())); + } catch (Exception ex) { + throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, ex.getMessage())); + } + } + + addToBus(var, res); - @Override - public int doEndTag() throws JspException { - //Accept header of mtg request - String acceptHeader = request.getHeader(HEADER_ACCEPT) == null - ? MasonOutput.HEADER_JSON : request.getHeader(HEADER_ACCEPT); - //Accept type of XRequest - String xAcceptType = "json"; - for (Map.Entry entry : headers.entrySet()) { - if (entry.getKey().equals(ResourceTagHandler.HEADER_ACCEPT) && entry.getValue().equals("application/xml")) { - //if Accept header of XRequest is application/xml - xAcceptType = "xml"; - } - } + if(output){ + addToOutput(var, res); + } - XRequestService xRequestService = new XRequestService(outputHeaders); - XResponse xresponse = null; + return EVAL_PAGE; + } - switch (method) { - case "GET": - xresponse = xRequestService.get(url, headers, parameters); - break; - case "POST": - xresponse = xRequestService.post(url, headers, parameters, requestBody); - break; - case "PUT": - xresponse = xRequestService.put(url, headers, parameters, requestBody); - break; - case "DELETE": - xresponse = xRequestService.delete(url, parameters); - break; - default: - throw new JspTagException("Unsupported method \"" + method + "\"."); - } + public void setVar(String var) { + this.var = var; + } - Response res = xresponse.getResponse(acceptHeader, xAcceptType); - - if(className!=null){ - //post processable classname is given - try { - Class cls = Class.forName(className); - if(ResponseProcessable.class.isAssignableFrom(cls)){ - ResponseProcessable responseProcessor = (ResponseProcessable)cls.newInstance(); - //get post processed response - res = responseProcessor.process(res); - } else { - throw new JspException("", new MasonException(MasonError.RESPONSE_PROCESSABLE_NOT_IMPLEMENTED, - "Class " + cls + " is not Response processable")); - } - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { - throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, ex.getMessage())); - } catch (Exception ex) { - throw new JspException("", new MasonException(MasonError.CODE_ERROR, ex, ex.getMessage())); - } - } - - addToBus(var, res); - - if(output){ - addToOutput(var, res); - } + public void setUrl(String u) { + url = u; + } - return EVAL_PAGE; - } + public void setRequestBody(String b) { + requestBody = b; + } - public void setVar(String var) { - this.var = var; - } + public void setOutput(Boolean output){ + this.output = output; + } - public void setUrl(String u) { - url = u; - } + public void setOutputHeaders(boolean outputHeaders) { + this.outputHeaders = outputHeaders; + } - public void setRequestBody(String b) { - requestBody = b; - } - - public void setOutput(Boolean output){ - this.output = output; - } - - public void setOutputHeaders(boolean outputHeaders) { - this.outputHeaders = outputHeaders; - } - - public void setClassName(String className) { - this.className = className; - } + public void setClassName(String className) { + this.className = className; + } } \ No newline at end of file diff --git a/src/test/java/com/metamug/mason/entity/auth/JWebTokenTest.java b/src/test/java/com/metamug/mason/entity/auth/JWebTokenTest.java index a2cfa667..54332b0c 100644 --- a/src/test/java/com/metamug/mason/entity/auth/JWebTokenTest.java +++ b/src/test/java/com/metamug/mason/entity/auth/JWebTokenTest.java @@ -5,15 +5,17 @@ */ package com.metamug.mason.entity.auth; +import static org.junit.Assert.fail; + import java.security.NoSuchAlgorithmException; import java.time.LocalDateTime; import java.time.ZoneOffset; + import org.json.JSONArray; import org.json.JSONObject; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; -import static org.junit.Assert.fail; import org.junit.Before; import org.junit.BeforeClass; @@ -23,101 +25,101 @@ */ public class JWebTokenTest { - LocalDateTime ldt; - JSONObject payload; - - public JWebTokenTest() { - } - - @BeforeClass - public static void setUpClass() { - } - - @AfterClass - public static void tearDownClass() { - } - - @Before - public void setUp() { - ldt = LocalDateTime.now().plusDays(90); - payload = new JSONObject("{\"sub\":\"1234\",\"aud\":[\"admin\"]," - + "\"exp\":" + ldt.toEpochSecond(ZoneOffset.UTC) + "}"); - } - - @After - public void tearDown() { - } - - /** - * Test of HMACSHA256 method, of class JWebToken. - */ - @org.junit.Test - public void testWithData() { - //generate JWT - long exp = ldt.now().plusDays(90).toEpochSecond(ZoneOffset.UTC); - String token = new JWebToken("1234", new JSONArray("['admin']"), exp).toString(); - //verify and use - JWebToken incomingToken; - System.out.println(token); - try { - incomingToken = new JWebToken(token); - if (incomingToken.isValid()) { - Assert.assertEquals("1234", incomingToken.getSubject()); - Assert.assertEquals("admin", incomingToken.getAudience().get(0)); - } - } catch (NoSuchAlgorithmException ex) { - fail("Invalid Token" + ex.getMessage()); - } - - } - - @org.junit.Test - public void testWithJson() { - - String token = new JWebToken(payload).toString(); - //verify and use - JWebToken incomingToken; - try { - incomingToken = new JWebToken(token); - if (incomingToken.isValid()) { - Assert.assertEquals("1234", incomingToken.getSubject()); - Assert.assertEquals("admin", incomingToken.getAudience().get(0)); - } - } catch (NoSuchAlgorithmException ex) { - fail("Invalid Token" + ex.getMessage()); - } - } - - @org.junit.Test(expected = IllegalArgumentException.class) - public void testBadHeaderFormat() { - - String token = new JWebToken(payload).toString(); - token = token.replaceAll("\\.", "X"); - //verify and use - JWebToken incomingToken; - try { - incomingToken = new JWebToken(token); - if (incomingToken.isValid()) { - Assert.assertEquals("1234", incomingToken.getSubject()); - Assert.assertEquals("admin", incomingToken.getAudience().get(0)); - } - } catch (NoSuchAlgorithmException ex) { - fail("Invalid Token" + ex.getMessage()); - } - } - - @org.junit.Test(expected = NoSuchAlgorithmException.class) - public void testIncorrectHeader() throws NoSuchAlgorithmException { - - String token = new JWebToken(payload).toString(); - token = token.replaceAll("[^.]", "X"); - //verify and use - JWebToken incomingToken; - - incomingToken = new JWebToken(token); - if (incomingToken.isValid()) { - Assert.assertEquals("1234", incomingToken.getSubject()); - Assert.assertEquals("admin", incomingToken.getAudience().get(0)); - } - } + LocalDateTime ldt; + JSONObject payload; + + public JWebTokenTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + ldt = LocalDateTime.now().plusDays(90); + payload = new JSONObject("{\"sub\":\"1234\",\"aud\":[\"admin\"]," + + "\"exp\":" + ldt.toEpochSecond(ZoneOffset.UTC) + "}"); + } + + @After + public void tearDown() { + } + + /** + * Test of HMACSHA256 method, of class JWebToken. + */ + @org.junit.Test + public void testWithData() { + //generate JWT + long exp = LocalDateTime.now().plusDays(90).toEpochSecond(ZoneOffset.UTC); + String token = new JWebToken("1234", new JSONArray("['admin']"), exp).toString(); + //verify and use + JWebToken incomingToken; + System.out.println(token); + try { + incomingToken = new JWebToken(token); + if (incomingToken.isValid()) { + Assert.assertEquals("1234", incomingToken.getSubject()); + Assert.assertEquals("admin", incomingToken.getAudience().get(0)); + } + } catch (NoSuchAlgorithmException ex) { + fail("Invalid Token" + ex.getMessage()); + } + + } + + @org.junit.Test + public void testWithJson() { + + String token = new JWebToken(payload).toString(); + //verify and use + JWebToken incomingToken; + try { + incomingToken = new JWebToken(token); + if (incomingToken.isValid()) { + Assert.assertEquals("1234", incomingToken.getSubject()); + Assert.assertEquals("admin", incomingToken.getAudience().get(0)); + } + } catch (NoSuchAlgorithmException ex) { + fail("Invalid Token" + ex.getMessage()); + } + } + + @org.junit.Test(expected = IllegalArgumentException.class) + public void testBadHeaderFormat() { + + String token = new JWebToken(payload).toString(); + token = token.replaceAll("\\.", "X"); + //verify and use + JWebToken incomingToken; + try { + incomingToken = new JWebToken(token); + if (incomingToken.isValid()) { + Assert.assertEquals("1234", incomingToken.getSubject()); + Assert.assertEquals("admin", incomingToken.getAudience().get(0)); + } + } catch (NoSuchAlgorithmException ex) { + fail("Invalid Token" + ex.getMessage()); + } + } + + @org.junit.Test(expected = NoSuchAlgorithmException.class) + public void testIncorrectHeader() throws NoSuchAlgorithmException { + + String token = new JWebToken(payload).toString(); + token = token.replaceAll("[^.]", "X"); + //verify and use + JWebToken incomingToken; + + incomingToken = new JWebToken(token); + if (incomingToken.isValid()) { + Assert.assertEquals("1234", incomingToken.getSubject()); + Assert.assertEquals("admin", incomingToken.getAudience().get(0)); + } + } } diff --git a/src/test/java/com/metamug/mason/entity/response/MasonOutputTest.java b/src/test/java/com/metamug/mason/entity/response/MasonOutputTest.java index e911c6d2..3ba783af 100644 --- a/src/test/java/com/metamug/mason/entity/response/MasonOutputTest.java +++ b/src/test/java/com/metamug/mason/entity/response/MasonOutputTest.java @@ -5,15 +5,19 @@ */ package com.metamug.mason.entity.response; -import com.metamug.entity.Response; +import static org.mockito.Mockito.when; + import com.metamug.mason.processables.Customer; + import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; + import javax.xml.bind.JAXBException; + import org.apache.taglibs.standard.tag.common.sql.ResultImpl; import org.json.JSONArray; import org.json.JSONObject; @@ -22,7 +26,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import static org.mockito.Mockito.when; import org.mockito.runners.MockitoJUnitRunner; /** @@ -32,111 +35,110 @@ @RunWith(MockitoJUnitRunner.class) public class MasonOutputTest { - private Map outputMap; - private final String sampleObj = "{ \"name\":\"John\", \"age\":30, \"car\":null }"; - private final String sampleArray = "[\n" - + " { \"name\":\"Ford\", \"models\":[ \"Fiesta\", \"Focus\", \"Mustang\" ] },\n" - + " { \"name\":\"BMW\", \"models\":[ \"320\", \"X3\", \"X5\" ] },\n" - + " { \"name\":\"Fiat\", \"models\":[ \"500\", \"Panda\" ] }\n" - + " ]"; - - @Mock - private ResultImpl sampleResult; - - @Before - public void setup() { - - String[] colNames = {"name", "age", "car"}; - SortedMap[] rows = getSampleRows(); - - when(sampleResult.getColumnNames()).thenReturn(colNames); - when(sampleResult.getRows()).thenReturn(rows); - - List list = new ArrayList<>(); - list.add("I am String"); - list.add(new JSONObject(sampleObj)); - list.add(sampleResult); - list.add(null); - - Customer customer = new Customer(); - customer.setName("John"); - customer.setId(1); - customer.setContact("8080808080", "john@example.com"); - - list.add(customer); - - outputMap = new LinkedHashMap<>(); - outputMap.put("jsonobj", new JSONObject(sampleObj)); - outputMap.put("jsonarray", new JSONArray(sampleArray)); - outputMap.put("string", "Hello World"); - outputMap.put("result", sampleResult); - outputMap.put("null", null); - outputMap.put("pojo", customer); - outputMap.put("list", list); - } - - @Test - public void testJson() throws JAXBException { - String dataType = MasonOutput.HEADER_JSON; - MasonOutput output = getOutput(dataType); - String outStr = output.toString(); - System.out.println("json: " + outStr); - System.out.println("Length: " + outStr.length()); - //Assert.assertTrue(outStr.length()>1); - } - - @Test - public void testDataSet() throws JAXBException { - String dataType = MasonOutput.HEADER_DATASET; - MasonOutput output = getOutput(dataType); - String outStr = output.toString(); - System.out.println("DATASET: " + outStr); - System.out.println("Length: " + outStr.length()); - //Assert.assertTrue(outStr.length()>1); - } - - @Test - public void testXml() throws JAXBException { - String dataType = MasonOutput.HEADER_XML; - MasonOutput output = getOutput(dataType); - String outStr = output.toString(); - System.out.println("XML: " + outStr); - System.out.println("Length: " + outStr.length()); - XML.toJSONObject(outStr); //validate xml - //Assert.assertTrue(outStr.length()>1); - } - - private MasonOutput getOutput(String dataType) throws JAXBException { - MasonOutput output = null; - - switch (dataType) { - case MasonOutput.HEADER_JSON: - output = new JSONOutput(); - break; - case MasonOutput.HEADER_DATASET: - output = new DatasetOutput(); - break; - case MasonOutput.HEADER_XML: - output = new XMLOutput(); - break; - } - Response res = output.generate(null, outputMap); -// Assert.assertEquals(null, res.getPayload()); - return output; - } - - public static SortedMap[] getSampleRows() { - SortedMap row1 = new TreeMap<>(); - row1.put("name", "John"); - row1.put("age", "30"); - row1.put("car", "Ford"); - - SortedMap row2 = new TreeMap<>(); - row2.put("name", "Sean"); - row2.put("age", "40"); - row2.put("car", "BMW"); - - SortedMap[] rows = {row1, row2}; - return rows; - } + private Map outputMap; + private final String sampleObj = "{ \"name\":\"John\", \"age\":30, \"car\":null }"; + private final String sampleArray = "[\n" + + " { \"name\":\"Ford\", \"models\":[ \"Fiesta\", \"Focus\", \"Mustang\" ] },\n" + + " { \"name\":\"BMW\", \"models\":[ \"320\", \"X3\", \"X5\" ] },\n" + + " { \"name\":\"Fiat\", \"models\":[ \"500\", \"Panda\" ] }\n" + + " ]"; + + @Mock + private ResultImpl sampleResult; + + @Before + public void setup() { + + String[] colNames = {"name", "age", "car"}; + SortedMap[] rows = getSampleRows(); + + when(sampleResult.getColumnNames()).thenReturn(colNames); + when(sampleResult.getRows()).thenReturn(rows); + + List list = new ArrayList<>(); + list.add("I am String"); + list.add(new JSONObject(sampleObj)); + list.add(sampleResult); + list.add(null); + + Customer customer = new Customer(); + customer.setName("John"); + customer.setId(1); + customer.setContact("8080808080", "john@example.com"); + + list.add(customer); + + outputMap = new LinkedHashMap<>(); + outputMap.put("jsonobj", new JSONObject(sampleObj)); + outputMap.put("jsonarray", new JSONArray(sampleArray)); + outputMap.put("string", "Hello World"); + outputMap.put("result", sampleResult); + outputMap.put("null", null); + outputMap.put("pojo", customer); + outputMap.put("list", list); + } + + @Test + public void testJson() throws JAXBException { + String dataType = MasonOutput.HEADER_JSON; + MasonOutput output = getOutput(dataType); + String outStr = output.toString(); + System.out.println("json: " + outStr); + System.out.println("Length: " + outStr.length()); + //Assert.assertTrue(outStr.length()>1); + } + + @Test + public void testDataSet() throws JAXBException { + String dataType = MasonOutput.HEADER_DATASET; + MasonOutput output = getOutput(dataType); + String outStr = output.toString(); + System.out.println("DATASET: " + outStr); + System.out.println("Length: " + outStr.length()); + //Assert.assertTrue(outStr.length()>1); + } + + @Test + public void testXml() throws JAXBException { + String dataType = MasonOutput.HEADER_XML; + MasonOutput output = getOutput(dataType); + String outStr = output.toString(); + System.out.println("XML: " + outStr); + System.out.println("Length: " + outStr.length()); + XML.toJSONObject(outStr); //validate xml + //Assert.assertTrue(outStr.length()>1); + } + + private MasonOutput getOutput(String dataType) throws JAXBException { + MasonOutput output = null; + + switch (dataType) { + case MasonOutput.HEADER_JSON: + output = new JSONOutput(); + break; + case MasonOutput.HEADER_DATASET: + output = new DatasetOutput(); + break; + case MasonOutput.HEADER_XML: + output = new XMLOutput(); + break; + } + // Assert.assertEquals(null, res.getPayload()); + return output; + } + + public static SortedMap[] getSampleRows() { + SortedMap row1 = new TreeMap<>(); + row1.put("name", "John"); + row1.put("age", "30"); + row1.put("car", "Ford"); + + SortedMap row2 = new TreeMap<>(); + row2.put("name", "Sean"); + row2.put("age", "40"); + row2.put("car", "BMW"); + + SortedMap[] rows = {row1, row2}; + return rows; + } } diff --git a/src/test/java/com/metamug/mason/io/mpath/MPathUnflattenTest.java b/src/test/java/com/metamug/mason/io/mpath/MPathUnflattenTest.java index ee31306d..e878d270 100644 --- a/src/test/java/com/metamug/mason/io/mpath/MPathUnflattenTest.java +++ b/src/test/java/com/metamug/mason/io/mpath/MPathUnflattenTest.java @@ -78,8 +78,7 @@ public void TestCase1() { String mPath = "a.b.c"; String value = "123"; try { - JSONObject json = MPathUtil.getJsonFromMPath(mPath, value); - //System.out.println(json); + MPathUtil.getJsonFromMPath(mPath, value); } catch (JSONException jx) { Assert.fail(jx.toString()); } @@ -94,8 +93,7 @@ public void TestCase2() { int value1 = 456; JSONObject unflatJson1 = MPathUtil.appendJsonFromMPath(initJson, mPath1, value1); String mPath2 = "a.e.f", value2 = "8910"; - JSONObject unflatJson2 = MPathUtil.appendJsonFromMPath(unflatJson1, mPath2, value2); - //System.out.println(unflatJson2); + MPathUtil.appendJsonFromMPath(unflatJson1, mPath2, value2); } catch (JSONException jx) { Assert.fail(jx.toString()); } @@ -104,7 +102,6 @@ public void TestCase2() { @Test public void TestCase3() { JSONObject initJson = new JSONObject(); - JSONObject result = MPathUtil.appendJsonFromMPath(initJson, "data", TestData.TEST_JSON4); - //System.out.println(result); + MPathUtil.appendJsonFromMPath(initJson, "data", TestData.TEST_JSON4); } } diff --git a/src/test/java/com/metamug/mason/io/objectreturn/testclasses/Customer.java b/src/test/java/com/metamug/mason/io/objectreturn/testclasses/Customer.java index ec61119e..bb5b1230 100644 --- a/src/test/java/com/metamug/mason/io/objectreturn/testclasses/Customer.java +++ b/src/test/java/com/metamug/mason/io/objectreturn/testclasses/Customer.java @@ -54,6 +54,7 @@ import java.util.ArrayList; import java.util.List; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @@ -63,28 +64,44 @@ @XmlRootElement(name = "customer") public class Customer { - @XmlAttribute - private int id; + @XmlAttribute + private int id; + + private String firstName; + + private String lastName; + + private final List phoneNumbers = new ArrayList<>(); + + //must have zero argument constructor + public Customer() { - private String firstName; + } - private String lastName; + public Customer(int id, String firstName, String lastName) { + this.id = id; + this.setFirstName(firstName); + this.setLastName(lastName); + } - private final List phoneNumbers = new ArrayList<>(); + public void addPhoneNumber(PhoneNumber pn) { + phoneNumbers.add(pn); + } - //must have zero argument constructor - public Customer() { + public String getFirstName() { + return firstName; + } - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public Customer(int id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } + public String getLastName() { + return lastName; + } - public void addPhoneNumber(PhoneNumber pn) { - phoneNumbers.add(pn); - } + public void setLastName(String lastName) { + this.lastName = lastName; + } } diff --git a/src/test/java/com/metamug/mason/tag/TagHandlerTest.java b/src/test/java/com/metamug/mason/tag/TagHandlerTest.java index f86c1f08..5c0f6d9f 100644 --- a/src/test/java/com/metamug/mason/tag/TagHandlerTest.java +++ b/src/test/java/com/metamug/mason/tag/TagHandlerTest.java @@ -506,16 +506,21 @@ */ package com.metamug.mason.tag; +import static com.metamug.mason.Router.MASON_REQUEST; +import static com.metamug.mason.entity.request.MultipartFormStrategy.MULTIPART_FORM_DATA; +import static com.metamug.mason.tag.RestTag.HEADER_ACCEPT; +import static com.metamug.mason.tag.RestTag.MASON_OUTPUT; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.metamug.entity.Attachment; import com.metamug.entity.Request; import com.metamug.entity.Response; -import static com.metamug.mason.Router.MASON_REQUEST; -import static com.metamug.mason.entity.request.MultipartFormStrategy.MULTIPART_FORM_DATA; import com.metamug.mason.entity.response.FileOutput; import com.metamug.mason.service.ConnectionProvider; -import static com.metamug.mason.tag.RestTag.HEADER_ACCEPT; -import static com.metamug.mason.tag.RestTag.MASON_OUTPUT; import com.metamug.mason.tag.xrequest.XRequestTagHandler; + import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; @@ -532,6 +537,7 @@ import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; + import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -539,18 +545,16 @@ import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; + import org.apache.taglibs.standard.tag.common.sql.ResultImpl; import org.json.JSONArray; import org.json.JSONObject; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import org.mockito.runners.MockitoJUnitRunner; /** @@ -560,211 +564,214 @@ @RunWith(MockitoJUnitRunner.class) public class TagHandlerTest { - @Mock - private HttpServletRequest request; - @Mock - private HttpServletResponse response; + @Mock + private HttpServletRequest request; + @Mock + private HttpServletResponse response; - @Mock - private Request masonRequest; + @Mock + private Request masonRequest; - @Mock - private PageContext context; + @Mock + private PageContext context; - private LinkedHashMap resultMap; + private LinkedHashMap resultMap; - @Mock - private JspWriter writer; + @Mock + private JspWriter writer; - @Mock - private ServletOutputStream outputStream; + @Mock + private ServletOutputStream outputStream; - @InjectMocks - RequestTagHandler requestTag = new RequestTagHandler(); //needs to initialized here + @InjectMocks + RequestTagHandler requestTag = new RequestTagHandler(); //needs to initialized here - @InjectMocks - ResourceTagHandler resourceTag = new ResourceTagHandler(); + @InjectMocks + ResourceTagHandler resourceTag = new ResourceTagHandler(); - @InjectMocks - XRequestTagHandler xrequestTag = new XRequestTagHandler(); + @InjectMocks + XRequestTagHandler xrequestTag = new XRequestTagHandler(); - @InjectMocks - ExecuteTagHandler executeTag = new ExecuteTagHandler(); + @InjectMocks + ExecuteTagHandler executeTag = new ExecuteTagHandler(); - @InjectMocks - ScriptTagHandler scriptTag = new ScriptTagHandler(); + @InjectMocks + ScriptTagHandler scriptTag = new ScriptTagHandler(); - @InjectMocks - ParamTagHandler paramTag = new ParamTagHandler(); + @InjectMocks + ParamTagHandler paramTag = new ParamTagHandler(); -// @InjectMocks -// ParentTagHandler parentTag = new ParentTagHandler(); + // @InjectMocks + // ParentTagHandler parentTag = new ParentTagHandler(); - @Mock - private ConnectionProvider provider; + @Mock + private ConnectionProvider provider; - @Mock - Connection connection; - @Mock - private PreparedStatement statement; + @Mock + Connection connection; + @Mock + private PreparedStatement statement; - @Mock - private ResultSet resultSet; + @Mock + private ResultSet resultSet; - @Mock - private ResultImpl resultImpl; + @Mock + private ResultImpl resultImpl; - public TagHandlerTest() { + public TagHandlerTest() { - } + } - @Before - public void setup() { - - try { - String sampleObj = "{ \"name\":\"John\", \"age\":30, \"car\":null }"; - String sampleArray = "[\n" - + " { \"name\":\"Ford\", \"models\":[ \"Fiesta\", \"Focus\", \"Mustang\" ] },\n" - + " { \"name\":\"BMW\", \"models\":[ \"320\", \"X3\", \"X5\" ] },\n" - + " { \"name\":\"Fiat\", \"models\":[ \"500\", \"Panda\" ] }\n" - + " ]"; - String[] colNames = {"name", "age", "car"}; - resultMap = new LinkedHashMap<>(); - resultMap.put("res1", new JSONObject(sampleObj)); - resultMap.put("res2", new JSONArray(sampleArray)); - resultMap.put("res3", "Hello World"); - - when(context.getRequest()).thenReturn(request); - when(context.getResponse()).thenReturn(response); - - when(response.getOutputStream()).thenReturn(outputStream); - - when(context.getOut()).thenReturn(writer); - when(request.getAttribute(MASON_REQUEST)).thenReturn(masonRequest); - - when(request.getParameter("auth")).thenReturn("bearer"); - when(request.getParameter("userid")).thenReturn("1234"); - when(request.getParameter("password")).thenReturn("pass"); - //when(provider.getInstance()).thenReturn(provider); - when(provider.getConnection()).thenReturn(connection); - when(connection.prepareStatement(Matchers.anyString())).thenReturn(statement); - when(statement.executeQuery()).thenReturn(resultSet); - //result set should return true for config function to give auth query - //second time inside createBearer function and then it should return false. - when(resultSet.next()).thenReturn(Boolean.TRUE).thenReturn(Boolean.TRUE).thenReturn(Boolean.FALSE); - when(resultSet.getString("auth_query")).thenReturn("some query mocked"); - when(resultSet.getString(1)).thenReturn("1234"); - when(resultSet.getString(2)).thenReturn("admin"); - - //mock resultimpl - SortedMap row = new TreeMap(); - row.put("Name", "Anish"); - row.put("Age", "26"); - when(resultImpl.getRows()).thenReturn(new SortedMap[]{row}); - when(resultImpl.getColumnNames()).thenReturn(new String[]{"Name", "Age"}); - when(resultImpl.getRowCount()).thenReturn(2); - } catch (SQLException ex) { - Logger.getLogger(TagHandlerTest.class.getName()).log(Level.SEVERE, null, ex); - } catch (IOException ex) { - Logger.getLogger(TagHandlerTest.class.getName()).log(Level.SEVERE, null, ex); - } - } - - @Test (expected = JspException.class) - public void fileUpload() throws JspException, IOException { - - File temp = File.createTempFile("test", ".txt"); - - // Delete temp file when program exits. - temp.deleteOnExit(); - - // Write to temp file - BufferedWriter out = new BufferedWriter(new FileWriter(temp)); - out.write("aString"); - out.close(); - - resultMap = new LinkedHashMap<>(); - resultMap.put("res3", "Hello World"); - resultMap.put("file", new Response(new FileInputStream(temp))); //this will be used a mason bus - - when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); - - when(request.getHeader(HEADER_ACCEPT)).thenReturn("application/xml"); - when(request.getContentType()).thenReturn(MULTIPART_FORM_DATA); - when(masonRequest.getMethod()).thenReturn("POST"); + @Before + public void setup() { - requestTag.setMethod("POST"); - requestTag.setParent(resourceTag); + try { + String sampleObj = "{ \"name\":\"John\", \"age\":30, \"car\":null }"; + String sampleArray = "[\n" + + " { \"name\":\"Ford\", \"models\":[ \"Fiesta\", \"Focus\", \"Mustang\" ] },\n" + + " { \"name\":\"BMW\", \"models\":[ \"320\", \"X3\", \"X5\" ] },\n" + + " { \"name\":\"Fiat\", \"models\":[ \"500\", \"Panda\" ] }\n" + + " ]"; + resultMap = new LinkedHashMap<>(); + resultMap.put("res1", new JSONObject(sampleObj)); + resultMap.put("res2", new JSONArray(sampleArray)); + resultMap.put("res3", "Hello World"); - assertEquals(Tag.EVAL_BODY_INCLUDE, requestTag.doStartTag()); - assertEquals(Tag.SKIP_PAGE, requestTag.doEndTag()); //skip everything after request matched. + when(context.getRequest()).thenReturn(request); + when(context.getResponse()).thenReturn(response); - } + when(response.getOutputStream()).thenReturn(outputStream); - @Test - public void fileDownload() throws JspException, IOException { - File temp = File.createTempFile("test", ".txt"); + when(context.getOut()).thenReturn(writer); + when(request.getAttribute(MASON_REQUEST)).thenReturn(masonRequest); - // Delete temp file when program exits. - temp.deleteOnExit(); - // Write to temp file - BufferedWriter out = new BufferedWriter(new FileWriter(temp)); - out.write("aString"); - out.close(); + when(request.getParameter("auth")).thenReturn("bearer"); + when(request.getParameter("userid")).thenReturn("1234"); + when(request.getParameter("password")).thenReturn("pass"); + //when(provider.getInstance()).thenReturn(provider); + when(provider.getConnection()).thenReturn(connection); + when(connection.prepareStatement(Matchers.anyString())).thenReturn(statement); + when(statement.executeQuery()).thenReturn(resultSet); + //result set should return true for config function to give auth query + //second time inside createBearer function and then it should return false. + when(resultSet.next()).thenReturn(Boolean.TRUE).thenReturn(Boolean.TRUE).thenReturn(Boolean.FALSE); + when(resultSet.getString("auth_query")).thenReturn("some query mocked"); + when(resultSet.getString(1)).thenReturn("1234"); + when(resultSet.getString(2)).thenReturn("admin"); - resultMap = new LinkedHashMap<>(); - resultMap.put("res3", "Hello World"); - resultMap.put("file",new Attachment(new FileInputStream(temp))); //this will be used a mason bus + //mock resultimpl + SortedMap row = new TreeMap(); + row.put("Name", "Anish"); + row.put("Age", "26"); + when(resultImpl.getRows()).thenReturn(new SortedMap[]{row}); + when(resultImpl.getColumnNames()).thenReturn(new String[]{"Name", "Age"}); + when(resultImpl.getRowCount()).thenReturn(2); + } catch (SQLException ex) { + Logger.getLogger(TagHandlerTest.class.getName()).log(Level.SEVERE, null, ex); + } catch (IOException ex) { + Logger.getLogger(TagHandlerTest.class.getName()).log(Level.SEVERE, null, ex); + } + } - when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); - when(request.getHeader(HEADER_ACCEPT)).thenReturn("application/xml"); - when(masonRequest.getMethod()).thenReturn("GET"); + @Test (expected = JspException.class) + public void fileUpload() throws JspException, IOException { - requestTag.setMethod("GET"); - requestTag.setItem(false); - requestTag.setParent(resourceTag); + File temp = File.createTempFile("test", ".txt"); - assertEquals(Tag.EVAL_BODY_INCLUDE, requestTag.doStartTag()); - assertEquals(Tag.SKIP_PAGE, requestTag.doEndTag()); //skip everything after request matched. + // Delete temp file when program exits. + temp.deleteOnExit(); - verify(response).setHeader("Content-Type",FileOutput.OCTETSTREAM); - //verify(outputStream).write("aString".getBytes(StandardCharsets.UTF_8)); + // Write to temp file + BufferedWriter out = new BufferedWriter(new FileWriter(temp)); + out.write("aString"); + out.close(); - } - - /** - * Test of doStartTag method, of class RequestTagHandler. - */ - @Test - public void requestTag() throws JspException { + resultMap = new LinkedHashMap<>(); + resultMap.put("res3", "Hello World"); + resultMap.put("file", new Response(new FileInputStream(temp))); //this will be used a mason bus - when(request.getHeader(HEADER_ACCEPT)).thenReturn("application/xml"); - when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); + when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); - when(masonRequest.getMethod()).thenReturn("GET"); - - requestTag.setMethod("GET"); - requestTag.setItem(false); - requestTag.setParent(resourceTag); + when(request.getHeader(HEADER_ACCEPT)).thenReturn("application/xml"); + when(request.getContentType()).thenReturn(MULTIPART_FORM_DATA); + when(masonRequest.getMethod()).thenReturn("POST"); - assertEquals(Tag.EVAL_BODY_INCLUDE, requestTag.doStartTag()); - assertEquals(Tag.SKIP_PAGE, requestTag.doEndTag()); //skip everything after request matched. + requestTag.setMethod("POST"); + requestTag.setParent(resourceTag); - } + assertEquals(Tag.EVAL_BODY_INCLUDE, requestTag.doStartTag()); + assertEquals(Tag.SKIP_PAGE, requestTag.doEndTag()); //skip everything after request matched. - @Test(expected = JspException.class) - public void resourceTag() throws JspException { - resourceTag.setAuth("admin"); - String bearer = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0IiwiYXVkIjpbImFkbWluIl0sImlzcyI6Im1hc29uLm1ldGFtdWcubmV0IiwiZXhwIjoxNTYxNDU4OTMxLCJpYXQiOjE1NTM2ODI5MzEsImp0aSI6ImJjMTgxNGMzLWU5ZGItNDljOC1iYTMyLWI4NDAxY2Q0YTgyMSJ9.bD+8dO0FG/HCwxLs6TH9+BvH94CL46hBFVZO9oCTyQk="; - when(request.getHeader("Authorization")).thenReturn(bearer); - assertEquals(Tag.EVAL_BODY_INCLUDE, resourceTag.doStartTag()); - assertEquals(Tag.SKIP_PAGE, resourceTag.doEndTag()); //should be last call of the page + } - } + @Test + public void fileDownload() throws JspException, IOException { - @Test + File temp = File.createTempFile("test", ".txt"); + + // Delete temp file when program exits. + temp.deleteOnExit(); + + // Write to temp file + BufferedWriter out = new BufferedWriter(new FileWriter(temp)); + out.write("aString"); + out.close(); + + resultMap = new LinkedHashMap<>(); + resultMap.put("res3", "Hello World"); + resultMap.put("file",new Attachment(new FileInputStream(temp))); //this will be used a mason bus + + when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); + when(request.getHeader(HEADER_ACCEPT)).thenReturn("application/xml"); + when(masonRequest.getMethod()).thenReturn("GET"); + + requestTag.setMethod("GET"); + requestTag.setItem(false); + requestTag.setParent(resourceTag); + + assertEquals(Tag.EVAL_BODY_INCLUDE, requestTag.doStartTag()); + assertEquals(Tag.SKIP_PAGE, requestTag.doEndTag()); //skip everything after request matched. + + verify(response).setHeader("Content-Type",FileOutput.OCTETSTREAM); + //verify(outputStream).write("aString".getBytes(StandardCharsets.UTF_8)); + + } + + /** + * Test of doStartTag method, of class RequestTagHandler. + */ + @Test + public void requestTag() throws JspException { + + when(request.getHeader(HEADER_ACCEPT)).thenReturn("application/xml"); + when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); + + when(masonRequest.getMethod()).thenReturn("GET"); + + requestTag.setMethod("GET"); + requestTag.setItem(false); + requestTag.setParent(resourceTag); + + assertEquals(Tag.EVAL_BODY_INCLUDE, requestTag.doStartTag()); + assertEquals(Tag.SKIP_PAGE, requestTag.doEndTag()); //skip everything after request matched. + + } + + @Test + public void resourceTag() throws JspException { + resourceTag.setAuth("admin"); + String bearer = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0IiwiYXVkIjpbImFkbWluIl0sImlzcyI6Im1hc29uLm1ldGFtdWcubmV0IiwiZXhwIjoxNTg0MTE2NTAzLCJpYXQiOjE1NzYzNDA1MDMsImp0aSI6ImUwNjE1YjJhLTUyODQtNDk2Yi04NzIzLWZiMGNkZDcyNTZjOCJ9.-Go2J-Uz4q8UAcUT6KVj2rvPfot38D2xJKoATlNVjqs"; + when(request.getHeader("Authorization")).thenReturn(bearer); + when(masonRequest.getMethod()).thenReturn("GET"); + resourceTag.addChildMethod("GET".toLowerCase()); + assertEquals(Tag.EVAL_BODY_INCLUDE, resourceTag.doStartTag()); + assertEquals(Tag.SKIP_PAGE, resourceTag.doEndTag()); //should be last call of the page + + } + + @Test public void resourceTag404() throws JspException { //add child request same as incoming request method, this is the equivalent of mocking a 404 response, //if the flow reaches the end of resource tag @@ -795,160 +802,160 @@ public void scriptTag() throws JspException { assertEquals(Tag.EVAL_PAGE, executeTag.doEndTag()); } -// @Test -// public void parentTag() throws JspException { -// when(masonRequest.getParent()).thenReturn("mother"); -// parentTag.setValue("mother"); -// assertEquals(Tag.EVAL_PAGE, parentTag.doEndTag()); -// } - - @Test - public void paramTag() throws JspException { - // - // - paramTag.setName("limit"); - paramTag.setType("number"); - paramTag.setMin("0"); - paramTag.setMax("100"); - paramTag.setValue("12"); - - assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); - - paramTag.setName("offset"); - paramTag.setType("number"); - paramTag.setMin("0"); - paramTag.setMax("900"); - paramTag.setValue("40"); - - assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); - - paramTag.setName("startDate"); - paramTag.setType("date"); - paramTag.setValue("2018-11-10"); - - assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); - - paramTag.setName("name"); - paramTag.setType("text"); - paramTag.setValue("hirlekar"); - paramTag.setMaxLen("20"); - paramTag.setMinLen("7"); - - assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); - - paramTag.setName("link"); - paramTag.setType("url"); - paramTag.setValue("https://metamug.com"); - - assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); - - paramTag.setName("mail"); - paramTag.setType("email"); - paramTag.setValue("hi@metamug.com"); - - assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); - } - - @Test(expected = JspException.class) - public void executeTagInvalidProcessable() throws JspException { - executeTag.setVar("executeOutput"); - - executeTag.setClassName("com.metamug.mason.service.ConvertServiceTest"); //should be from test package - assertEquals(Tag.EVAL_BODY_INCLUDE, executeTag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, executeTag.doEndTag()); - } - /* + // @Test + // public void parentTag() throws JspException { + // when(masonRequest.getParent()).thenReturn("mother"); + // parentTag.setValue("mother"); + // assertEquals(Tag.EVAL_PAGE, parentTag.doEndTag()); + // } + + @Test + public void paramTag() throws JspException { + // + // + paramTag.setName("limit"); + paramTag.setType("number"); + paramTag.setMin("0"); + paramTag.setMax("100"); + paramTag.setValue("12"); + + assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); + + paramTag.setName("offset"); + paramTag.setType("number"); + paramTag.setMin("0"); + paramTag.setMax("900"); + paramTag.setValue("40"); + + assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); + + paramTag.setName("startDate"); + paramTag.setType("date"); + paramTag.setValue("2018-11-10"); + + assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); + + paramTag.setName("name"); + paramTag.setType("text"); + paramTag.setValue("hirlekar"); + paramTag.setMaxLen("20"); + paramTag.setMinLen("7"); + + assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); + + paramTag.setName("link"); + paramTag.setType("url"); + paramTag.setValue("https://metamug.com"); + + assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); + + paramTag.setName("mail"); + paramTag.setType("email"); + paramTag.setValue("hi@metamug.com"); + + assertEquals(Tag.EVAL_PAGE, paramTag.doEndTag()); + } + + @Test(expected = JspException.class) + public void executeTagInvalidProcessable() throws JspException { + executeTag.setVar("executeOutput"); + + executeTag.setClassName("com.metamug.mason.service.ConvertServiceTest"); //should be from test package + assertEquals(Tag.EVAL_BODY_INCLUDE, executeTag.doStartTag()); + assertEquals(Tag.EVAL_PAGE, executeTag.doEndTag()); + } + /* @Test public void executeTagRequestProcessable() throws JspException { when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); - - + + executeTag.setVar("executeOutput"); executeTag.setOutput(true); - executeTag.setClassName("com.metamug.mason.processables.RequestExample"); - + executeTag.setClassName("com.metamug.mason.processables.RequestExample"); + Map requestParams = new HashMap<>(); requestParams.put("foo1","bar1"); requestParams.put("foo2","bar2"); masonRequest.setParams(requestParams); - - List headerNames = new ArrayList(); + + List headerNames = new ArrayList(); headerNames.add("Accept"); Enumeration headerNameEnum = Collections.enumeration(headerNames); when(request.getHeaderNames()).thenReturn(headerNameEnum); //when(request.getHeader("Authorization")).thenReturn(bearer); - when(request.getHeader("Accept")).thenReturn("application/json"); - + when(request.getHeader("Accept")).thenReturn("application/json"); + executeTag.setParam(masonRequest); - + assertEquals(Tag.EVAL_BODY_INCLUDE, executeTag.doStartTag()); assertEquals(Tag.EVAL_PAGE, executeTag.doEndTag()); }*/ - - - @Test - public void executeTagResultProcessable() throws JspException { - when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); - - executeTag.setVar("executeOutput"); - executeTag.setOutput(true); - executeTag.setClassName("com.metamug.mason.processables.ResultExample"); - - executeTag.setParam(resultImpl); - - assertEquals(Tag.EVAL_BODY_INCLUDE, executeTag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, executeTag.doEndTag()); - } - - @Test - public void xrequestTag() throws JspException { - - when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); - - xrequestTag.addHeader(ResourceTagHandler.HEADER_ACCEPT,"application/xml"); - xrequestTag.addParameter("foo1", "bar1"); - xrequestTag.addParameter("foo2", "bar2"); - xrequestTag.setVar("xrequestOutput"); - xrequestTag.setUrl("https://postman-echo.com/get"); - xrequestTag.setOutput(true); - xrequestTag.setOutputHeaders(true); - - xrequestTag.setMethod("GET"); - assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); - - JSONObject body = new JSONObject(); - body.put("foo1", "bar1").put("foo2", "bar2"); - xrequestTag.setMethod("POST"); - xrequestTag.setRequestBody(body.toString(4)); - assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); - xrequestTag.setMethod("PUT"); - assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); - xrequestTag.setMethod("DELETE"); - assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); - } - - @Test - public void xrequestTagResponseProcessable() throws JspException { - when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); - - Map headers = new HashMap<>(); - headers.put(ResourceTagHandler.HEADER_ACCEPT,"application/json"); - xrequestTag.setHeaders(headers); - - Map parameters = new HashMap<>(); - parameters.put("foo1", "bar1"); - parameters.put("foo2", "bar2"); - xrequestTag.setParameters(parameters); - xrequestTag.setVar("xrequestOutput"); - xrequestTag.setUrl("https://postman-echo.com/get"); - xrequestTag.setOutput(true); - xrequestTag.setClassName("com.metamug.mason.processables.ResponseExample"); - xrequestTag.setMethod("GET"); - assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); - assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); - } + + + @Test + public void executeTagResultProcessable() throws JspException { + when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); + + executeTag.setVar("executeOutput"); + executeTag.setOutput(true); + executeTag.setClassName("com.metamug.mason.processables.ResultExample"); + + executeTag.setParam(resultImpl); + + assertEquals(Tag.EVAL_BODY_INCLUDE, executeTag.doStartTag()); + assertEquals(Tag.EVAL_PAGE, executeTag.doEndTag()); + } + + @Test + public void xrequestTag() throws JspException { + + when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); + + xrequestTag.addHeader(ResourceTagHandler.HEADER_ACCEPT,"application/xml"); + xrequestTag.addParameter("foo1", "bar1"); + xrequestTag.addParameter("foo2", "bar2"); + xrequestTag.setVar("xrequestOutput"); + xrequestTag.setUrl("https://postman-echo.com/get"); + xrequestTag.setOutput(true); + xrequestTag.setOutputHeaders(true); + + xrequestTag.setMethod("GET"); + assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); + assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); + + JSONObject body = new JSONObject(); + body.put("foo1", "bar1").put("foo2", "bar2"); + xrequestTag.setMethod("POST"); + xrequestTag.setRequestBody(body.toString(4)); + assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); + assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); + xrequestTag.setMethod("PUT"); + assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); + assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); + xrequestTag.setMethod("DELETE"); + assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); + assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); + } + + @Test + public void xrequestTagResponseProcessable() throws JspException { + when(context.getAttribute(MASON_OUTPUT, PageContext.PAGE_SCOPE)).thenReturn(resultMap); + + Map headers = new HashMap<>(); + headers.put(ResourceTagHandler.HEADER_ACCEPT,"application/json"); + xrequestTag.setHeaders(headers); + + Map parameters = new HashMap<>(); + parameters.put("foo1", "bar1"); + parameters.put("foo2", "bar2"); + xrequestTag.setParameters(parameters); + xrequestTag.setVar("xrequestOutput"); + xrequestTag.setUrl("https://postman-echo.com/get"); + xrequestTag.setOutput(true); + xrequestTag.setClassName("com.metamug.mason.processables.ResponseExample"); + xrequestTag.setMethod("GET"); + assertEquals(Tag.EVAL_BODY_INCLUDE, xrequestTag.doStartTag()); + assertEquals(Tag.EVAL_PAGE, xrequestTag.doEndTag()); + } }