List of usage examples for java.net URLDecoder decode
public static String decode(String s, Charset charset)
From source file:com.o2o.util.WebUtils.java
/** * ?cookie/*from ww w . j a va 2 s . c o m*/ * * @param request * HttpServletRequest * @param name * cookie?? * @return ?null */ public static String getCookie(HttpServletRequest request, String name) { if (null == name) { return null; } Assert.notNull(request); Assert.hasText(name); Cookie[] cookies = request.getCookies(); if (cookies != null) { try { name = URLEncoder.encode(name, "UTF-8"); for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return URLDecoder.decode(cookie.getValue(), "UTF-8"); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return null; }
From source file:net.paoding.rose.web.RequestPath.java
public RequestPath(HttpServletRequest request) { // method//from ww w .ja v a 2 s . c o m setMethod(parseMethod(request)); // ctxpath setCtxpath(request.getContextPath()); String invocationCtxpath = null; // includeinvocationCtxPathincludectxpath // dispather, uri, ctxpath String uri; if (WebUtils.isIncludeRequest(request)) { setDispatcher(Dispatcher.INCLUDE); uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE); invocationCtxpath = ((String) request.getAttribute(WebUtils.INCLUDE_CONTEXT_PATH_ATTRIBUTE)); setRosePath((String) request.getAttribute(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE)); } else { uri = request.getRequestURI(); this.setRosePath(request.getServletPath()); if (request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) == null) { this.setDispatcher(Dispatcher.REQUEST); } else { this.setDispatcher(Dispatcher.FORWARD); } } if (uri.startsWith("http://") || uri.startsWith("https://")) { int start = uri.indexOf('/', 9); if (start == -1) { uri = ""; } else { uri = uri.substring(start); } } if (uri.indexOf('%') != -1) { try { String encoding = request.getCharacterEncoding(); if (encoding == null || encoding.length() == 0) { encoding = "UTF-8"; } uri = URLDecoder.decode(uri, encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } this.setUri(uri); // requestPathctxpathincludeinvocationCtxpath if (getCtxpath().length() <= 1) { setRosePath(getUri()); } else { setRosePath( getUri().substring((invocationCtxpath == null ? getCtxpath() : invocationCtxpath).length())); } }
From source file:com.networknt.light.server.handler.RestHandler.java
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return;/*from www.j av a 2s .co m*/ } exchange.startBlocking(); // check if it is get or post String json = null; Map<String, Object> jsonMap = null; if (Methods.GET.equals(exchange.getRequestMethod())) { Map params = exchange.getQueryParameters(); String cmd = ((Deque<String>) params.get("cmd")).getFirst(); json = URLDecoder.decode(cmd, "UTF8"); } else if (Methods.POST.equals(exchange.getRequestMethod())) { json = new Scanner(exchange.getInputStream(), "UTF-8").useDelimiter("\\A").next(); } else { logger.error("Invalid Request Method"); exchange.setResponseCode(400); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Invalid Request Method".getBytes("utf-8")))); return; } //logger.debug("json = {}", json); // convert json string to map here. It it cannot be converted, then it is invalid command. try { jsonMap = ServiceLocator.getInstance().getMapper().readValue(json, new TypeReference<HashMap<String, Object>>() { }); } catch (Exception e) { exchange.setResponseCode(400); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("invalid_command".getBytes("utf-8")))); return; } // TODO validate with json schema to make sure the input json is valid. return an error message otherwise. // you need to get the schema from db again for the one sent from browser might be modified. String cmdRuleClass = Util.getCommandRuleId(jsonMap); boolean readOnly = (boolean) jsonMap.get("readOnly"); if (!readOnly) { JsonSchema schema = AbstractValidationRule.getSchema(cmdRuleClass); if (schema != null) { // validate only if schema is not null. JsonNode jsonNode = mapper.valueToTree(jsonMap); ProcessingReport report = schema.validate(jsonNode.get("data")); logger.debug("report" + report); if (!report.isSuccess()) { exchange.setResponseCode(400); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); JsonNode messages = ((ListProcessingReport) report).asJson(); exchange.getResponseSender().send((ByteBuffer.wrap(messages.toString().getBytes("utf-8")))); return; } } } HeaderMap headerMap = exchange.getRequestHeaders(); Map<String, Object> payload = null; try { payload = getTokenPayload(headerMap); } catch (IllegalStateException e) { //e.printStackTrace(); String msg = e.getMessage(); if (msg != null && msg.startsWith(JwtUtil.TOKEN_EXPIRED_MESSAGE)) { // return 401 status and let client to refresh the token. exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("token_expired".getBytes("utf-8")))); return; } else { // invalid token, return 401 status and let client to discard the token. exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("invalid_token".getBytes("utf-8")))); return; } } GetAccessRule rule = new GetAccessRule(); Map<String, Object> access = rule.getAccessByRuleClass(cmdRuleClass); if (access != null) { // authorization rule available, check it. String accessLevel = (String) access.get("accessLevel"); switch (accessLevel) { case "A": // Access by anyone. break; case "N": // Not accessible exchange.setResponseCode(400); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Not accessible".getBytes("utf-8")))); return; case "C": // client id is in the jwt token like userId and roles. if (payload == null) { exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8")))); return; } else { Map<String, Object> user = (Map<String, Object>) payload.get("user"); String clientId = (String) user.get("clientId"); List<String> clients = (List) access.get("clients"); if (!clients.contains(clientId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8")))); return; } } break; case "R": // role only if (payload == null) { exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8")))); return; } else { Map<String, Object> user = (Map<String, Object>) payload.get("user"); List userRoles = (List) user.get("roles"); List<String> accessRoles = (List) access.get("roles"); boolean found = false; for (String role : accessRoles) { if (userRoles.contains(role)) { found = true; break; } } if (!found) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8")))); return; } } break; case "U": //user only if (payload == null) { exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8")))); return; } else { Map<String, Object> user = (Map<String, Object>) payload.get("user"); String userId = (String) user.get("userId"); List<String> users = (List) access.get("users"); if (!users.contains(userId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8")))); return; } } break; case "CR": // client and role if (payload == null) { exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8")))); return; } else { Map<String, Object> user = (Map<String, Object>) payload.get("user"); String clientId = (String) user.get("clientId"); List<String> clients = (List) access.get("clients"); if (!clients.contains(clientId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8")))); return; } // client is ok, check roles List userRoles = (List) user.get("roles"); List<String> accessRoles = (List) access.get("roles"); boolean found = false; for (String role : accessRoles) { if (userRoles.contains(role)) { found = true; break; } } if (!found) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8")))); return; } } break; case "CU": // client and user if (payload == null) { exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8")))); return; } else { Map<String, Object> user = (Map<String, Object>) payload.get("user"); String clientId = (String) user.get("clientId"); List<String> clients = (List) access.get("clients"); if (!clients.contains(clientId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8")))); return; } // client is ok, check user String userId = (String) user.get("userId"); List<String> users = (List) access.get("users"); if (!users.contains(userId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8")))); return; } } break; case "RU": // role and user if (payload == null) { exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8")))); return; } else { Map<String, Object> user = (Map<String, Object>) payload.get("user"); List userRoles = (List) user.get("roles"); List<String> accessRoles = (List) access.get("roles"); boolean found = false; for (String role : accessRoles) { if (userRoles.contains(role)) { found = true; break; } } if (!found) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8")))); return; } // role is OK, now check userId String userId = (String) user.get("userId"); List<String> users = (List) access.get("users"); if (!users.contains(userId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8")))); return; } } break; case "CRU": // client, role and user if (payload == null) { exchange.setResponseCode(401); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender().send((ByteBuffer.wrap("Login is required".getBytes("utf-8")))); return; } else { Map<String, Object> user = (Map<String, Object>) payload.get("user"); String clientId = (String) user.get("clientId"); List<String> clients = (List) access.get("clients"); if (!clients.contains(clientId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Client permission denied".getBytes("utf-8")))); return; } // client is ok, check roles List userRoles = (List) user.get("roles"); List<String> accessRoles = (List) access.get("roles"); boolean found = false; for (String role : accessRoles) { if (userRoles.contains(role)) { found = true; break; } } if (!found) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("Role permission denied".getBytes("utf-8")))); return; } // role is OK, now check userId String userId = (String) user.get("userId"); List<String> users = (List) access.get("users"); if (!users.contains(userId)) { exchange.setResponseCode(403); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); exchange.getResponseSender() .send((ByteBuffer.wrap("User permission denied".getBytes("utf-8")))); return; } } break; default: logger.error("Invalid Access Level: " + accessLevel); } } if (payload != null) { // put payload as part of the map jsonMap.put("payload", payload); } // TODO should I remove the port number here? // inject host into the data in command if there is no host in the json map. // that means the rules to be accessed are common and host should be part of the data. // if there is host in the command, then the corresponding rule should be host specific // and table(s) to be accessed should be host specific as well. if (jsonMap.get("host") == null) { String host = headerMap.getFirst("host"); if (host.indexOf(':') != -1) { host = host.substring(0, host.indexOf(":")); } Map<String, Object> data = (Map<String, Object>) jsonMap.get("data"); if (data == null) { data = new HashMap<String, Object>(); jsonMap.put("data", data); data.put("host", host); } else { // do not replace host as it might be owner doing something for one host from another. if (data.get("host") == null) { data.put("host", host); } } } // inject ip address into the command here and saved as part of event in order to identify // users that are not logged in. jsonMap.put("ipAddress", getIpAddress(exchange)); // TODO Apply request transform rules. For example routing here for A/B testing. GetTransformRequestRule transformRule = new GetTransformRequestRule(); List<Map<String, Object>> transforms = transformRule.getTransformRequest(cmdRuleClass); for (Map<String, Object> transform : transforms) { jsonMap.put("transformData", transform.get("transformData")); RuleEngine.getInstance().executeRule((String) transform.get("transformRule"), jsonMap); } // two types of rules (Command Rule and Event Rule) // Command Rule is responsible for validation and return result to client and enrich the command to event that // can be replayed at anytime without side effect.Once this is done, return to client. Also, it there are any // calls to the outside system, they should be performed here in order to avoid side effects. // // Event rule is responsible to update domain model based on the event enriched by Command Rule. if (readOnly) { // get data from memory and return it, it call a command rule to get the data and result will be in the jsonMap as "result" key // call the right rule to execute the command, return error code and message if validation fails. RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap); } else { // this is a update command or impacting to external system. // TODO validate version number in itself and dependencies to make sure the event is valid. Reject it back if not. // TODO This is the command that need to be executed, and it should be done only once to eliminate side effect. // Once this is done, the jsonMap is enriched so that the event is created and can be replayed. // It is very possible that something needs to be returned, put it in "result" key in jsonMap. boolean valid = RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap); if (valid) { // persist event into event store. Map<String, Object> eventMap = (Map<String, Object>) jsonMap.get("eventMap"); DbService.persistEvent(eventMap); // Publish the event to subscribers here to update snapshot and cache and etags. // This is the async call to update domain model after the fact. Nothing should be returned from here. // Basically, this is to apply event generated by the Command Rule RuleEngine.getInstance().executeRuleAsync(Util.getEventRuleId(eventMap), eventMap); } } // orientdb most likely return ODocument and ODocument collection, convert to json string by rules String result = null; Integer responseCode = (Integer) jsonMap.get("responseCode"); if (responseCode != null) { // there is an error exchange.setResponseCode(responseCode); result = (String) jsonMap.get("error"); logger.debug("response error: {}", result); // TODO should I log the response error here or in the response interceptor? // do I have all the info here? } else { // no error result = (String) jsonMap.get("result"); // TODO apply response transform rule. Not supported currently yet. logger.debug("response success: {} ", result); } exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ServerConstants.JSON_UTF8); if (result != null) { exchange.getResponseSender().send(ByteBuffer.wrap(result.getBytes("utf-8"))); } }
From source file:de.rub.nds.burp.espresso.gui.UIOptions.java
/** * Creates new form UIOptions//from w w w. j a v a2s .c o m */ public UIOptions() { initComponents(); hideAllUnsedComponents(); String path = System.getProperty("user.home") + "/EsPReSSO"; String decoded_path = null; try { if (path != null) { decoded_path = URLDecoder.decode(path, "UTF-8"); if (decoded_path != null) { File file = new File(decoded_path); if (!file.exists()) { file.mkdir(); } path = decoded_path + "/config.json"; file = new File(path); if (!file.exists()) { // First start no config created file.createNewFile(); configText1.setText(path); saveConfig(path); } else { // load previous config configText1.setText(path); loadConfig(path); } } } } catch (UnsupportedEncodingException ex) { JOptionPane.showMessageDialog(this, ex.toString(), "ERROR 2", JOptionPane.ERROR_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(this, ex.toString(), "ERROR 2", JOptionPane.ERROR_MESSAGE); } }
From source file:argendata.api.DatasetAPIService.java
@GET @Path("/by/publisher/{p}.rdf") @Produces("application/xml") public String getDatasetsByPublisherRDFXML(@PathParam(value = "p") String publisher) { try {/*from w w w .j av a 2 s . c o m*/ publisher = URLDecoder.decode(publisher, "UTF-8"); validate(publisher); publisher = Parsing.withoutSpecialCharacters(publisher); } catch (Exception e1) { throw new NotFoundException("Recurso no encontrado"); } QName qName = new QName(properties.getNamespace(), "Organization:" + publisher); String rdfxml; try { rdfxml = repositoryGateway.getDatasetRDFByPublisher(qName); } catch (Exception e) { throw new NotFoundException("Recurso no encontrado"); } return rdfxml; }
From source file:com.flexive.war.servlet.TestRunnerServlet.java
/** * {@inheritDoc}/*from w w w.j a va 2 s. c o m*/ */ @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; String cmd = URLDecoder.decode(request.getRequestURI(), "UTF8"); if (cmd != null && cmd.lastIndexOf('/') > 0) cmd = cmd.substring(cmd.lastIndexOf('/') + 1); if (CMD_AVAILABLE.equals(cmd)) { boolean available = false; try { Class.forName("com.flexive.testRunner.FxTestRunner"); available = true; } catch (Exception e) { LOG.error(e); } response.setStatus(available ? HttpServletResponse.SC_OK : HttpServletResponse.SC_SERVICE_UNAVAILABLE); response.getWriter().write(String.valueOf(available)); } else if (CMD_RUN.equals(cmd)) { String outputPath = request.getParameter(PARAM_OUTPUTPATH); try { Class runner = Class.forName("com.flexive.testRunner.FxTestRunner"); Method check = runner.getMethod("checkTestConditions", String.class, Boolean.class); Boolean status = false; if (!StringUtils.isEmpty(outputPath)) status = (Boolean) check.invoke(null, String.valueOf(outputPath), Boolean.FALSE); if (!status) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); response.getWriter() .write("Invalid output path, assertations not enabled or test division not definied!"); return; } Method exec = runner.getMethod("runTests", String.class); exec.invoke(null, outputPath); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write("Tests started."); } catch (Exception e) { LOG.error(e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write("Error: " + e.getMessage()); } } else if (CMD_RUNNING.equals(cmd)) { try { Class runner = Class.forName("com.flexive.testRunner.FxTestRunner"); Method check = runner.getMethod("isTestInProgress"); Boolean status = (Boolean) check.invoke(null); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write(String.valueOf(status)); } catch (Exception e) { LOG.error(e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write("Error: " + e.getMessage()); } } else { response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); response.getWriter().write("Unknown command: " + cmd); } }
From source file:com.roncoo.pay.controller.common.BaseController.java
/** * add by Along// ww w .ja va2s . co m * * @param name * @param request * @param defaultValue * * @return */ public String getStringByRequest(String name, HttpServletRequest request, String defaultValue) { String resultStr = request.getParameter(name); if (resultStr == null || "".equals(resultStr) || "null".equals(resultStr) || "undefined".equals(resultStr)) { return defaultValue; } else { try { String decode = URLDecoder.decode(resultStr, UTF_8); return decode; } catch (UnsupportedEncodingException e) { logger.info(e); return defaultValue; } } }
From source file:com.agiletec.plugins.jpcrowdsourcing.aps.system.services.ideainstance.ApiIdeaInstanceInterface.java
/** * GET http://localhost:8080/<portal>/api/rs/en/ideaInstances? * @param properties//from w w w . j ava 2 s . co m * @return * @throws Throwable */ public List<String> getIdeaInstancesForApi(Properties properties) throws Throwable { List<String> idList = new ArrayList<String>(); try { Collection<String> groupCodes = this.extractGroups(properties); String codeParam = properties.getProperty("code"); if (StringUtils.isNotBlank(codeParam)) codeParam = URLDecoder.decode(codeParam, "UTF-8"); idList = this.getIdeaInstanceManager().getIdeaInstances(groupCodes, codeParam); } catch (Throwable t) { _logger.error("Error extracting ideaInstances", t); throw new ApsSystemException("Error extracting ideaInstances", t); } return idList; }
From source file:eu.e43.impeller.Utils.java
public static Map<String, String> getQueryMap(String query) { try {//from www . ja v a 2 s .c om String[] params = query.split("&"); Map<String, String> map = new HashMap<String, String>(); for (String param : params) { String[] parts = param.split("=", 2); String name; name = URLDecoder.decode(parts[0], "UTF-8"); String value = URLDecoder.decode(parts[1], "UTF-8"); map.put(name, value); } return map; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }