List of usage examples for javax.servlet.http HttpServletRequest getPathInfo
public String getPathInfo();
From source file:com.jaspersoft.jasperserver.rest.services.RESTUser.java
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { try {/*from ww w .ja v a2 s .c om*/ String userName = restUtils.extractResourceName(req.getPathInfo()); WSUser user = restUtils.populateServiceObject(restUtils.unmarshal(WSUser.class, req.getInputStream())); if (log.isDebugEnabled()) { log.debug("un Marshaling OK"); } if (validateUserForPutOrUpdate(user)) { if (!isAlreadyAUser(user)) { userAndRoleManagementService.putUser(user); restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, ""); } else { throw new ServiceException(HttpServletResponse.SC_FORBIDDEN, "user " + user.getUsername() + "already exists"); } } else throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters"); } catch (AxisFault axisFault) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage()); } catch (IOException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage()); } catch (JAXBException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage()); } }
From source file:de.mpg.escidoc.services.syndication.presentation.RestServlet.java
/** * {@inheritDoc}/*from ww w .ja va 2 s . c o m*/ */ @Override protected final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String url = null; try { url = PropertyReader.getProperty("escidoc.syndication.service.url") + req.getServletPath() + req.getPathInfo(); } catch (Exception e) { handleException(e, resp); } String q = req.getQueryString(); if (Utils.checkVal(q)) { url += "?" + q; } Feed feed = synd.getFeeds().matchFeedByUri(url); //set correct mime-type resp.setContentType("application/" + (url.contains("rss_") ? "rss" : "atom") + "+xml; charset=utf-8"); //cache handling String ttl = feed.getCachingTtl(); if (Utils.checkVal(ttl)) { long ttlLong = Long.parseLong(ttl) * 1000L; resp.setHeader("control-cache", "max-age=" + ttl + ", must-revalidate"); DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); df.setTimeZone(TimeZone.getTimeZone("GMT")); resp.setHeader("Expires", df.format(new Date(System.currentTimeMillis() + ttlLong))); } try { synd.getFeed(url, resp.getWriter()); } catch (SyndicationException e) { handleException(e, resp); } catch (URISyntaxException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong URI syntax: " + url); return; } catch (FeedException e) { handleException(e, resp); } }
From source file:com.centurylink.mdw.hub.servlet.RestServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CodeTimer timer = new CodeTimer("RestServlet.doPost()", true); if (request.getPathInfo() != null && request.getPathInfo().startsWith("/SOAP")) { // forward to SOAP servlet RequestDispatcher requestDispatcher = request.getRequestDispatcher(request.getPathInfo()); requestDispatcher.forward(request, response); return;//from w w w. j a v a 2 s .c o m } Map<String, String> metaInfo = buildMetaInfo(request); try { String responseString = handleRequest(request, response, metaInfo); response.getOutputStream().print(responseString); } catch (ServiceException ex) { logger.severeException(ex.getMessage(), ex); response.setStatus(ex.getCode()); response.getWriter().println(createErrorResponseMessage(request, metaInfo, ex)); } finally { timer.stopAndLogTiming(""); } }
From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationFilterTest.java
@Test public void doFilterTestRootPath() throws IOException, ServletException { HttpServletRequest servletRequest = mock(HttpServletRequest.class); HttpServletResponse servletResponse = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); HttpSession httpSession = mock(HttpSession.class); when(servletRequest.getHeader(anyString())).thenReturn("3df25213cac246f8bccad5c70cb3582e"); when(servletRequest.getPathInfo()).thenReturn("/"); when(servletRequest.getSession()).thenReturn(httpSession); when(httpSession.getId()).thenReturn("1234"); openStackAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain); }
From source file:de.mpg.escidoc.pubman.servlet.RedirectServlet.java
/** * {@inheritDoc}/*w w w . j av a2s .co m*/ */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getPathInfo().substring(1); boolean download = ("download".equals(req.getParameter("mode"))); boolean tme = ("tme".equals(req.getParameter("mode"))); String userHandle = req.getParameter(LoginHelper.PARAMETERNAME_USERHANDLE); // no component -> viewItemOverviewPage if (!id.contains("/component/")) { StringBuffer redirectUrl = new StringBuffer(); LoginHelper loginHelper = (LoginHelper) req.getSession().getAttribute("LoginHelper"); if (loginHelper != null && loginHelper.isDetailedMode()) { redirectUrl.append("/pubman/faces/viewItemFullPage.jsp?itemId=" + id); } else { redirectUrl.append("/pubman/faces/viewItemOverviewPage.jsp?itemId=" + id); } if (userHandle != null) { redirectUrl.append("&" + LoginHelper.PARAMETERNAME_USERHANDLE + "=" + userHandle); } resp.sendRedirect(redirectUrl.toString()); return; } // is component if (id.contains("/component/")) { String[] pieces = id.split("/"); if (pieces.length != 4) { resp.sendError(404, "File not found"); } // open component or download it if (req.getParameter("mode") == null || download) { try { InputStream input = getContentAsInputStream(req, resp, download, pieces); if (input == null) { return; } byte[] buffer = new byte[2048]; int numRead; long numWritten = 0; OutputStream out = resp.getOutputStream(); while ((numRead = input.read(buffer)) != -1) { logger.debug(numRead + " bytes read."); out.write(buffer, 0, numRead); resp.flushBuffer(); numWritten += numRead; } input.close(); out.close(); } catch (URISyntaxException e) { throw new ServletException(e); } } // view technical metadata if (tme) { OutputStream out = resp.getOutputStream(); resp.setCharacterEncoding("UTF-8"); try { if ("jhove".equals(PropertyReader.getProperty("escidoc.pubman.tme.configuration"))) { String technicalMetadata = getTechnicalMetadataByJhove(pieces); resp.setHeader("Content-Type", "text/xml; charset=UTF-8"); out.write(technicalMetadata.getBytes()); } else { InputStream input = getContentAsInputStream(req, resp, false, pieces); if (input == null) { return; } String b = new String(); try { b = getTechnicalMetadataByTika(input); } catch (TikaException e) { logger.warn("TikaException when parsing " + pieces[3], e); } catch (SAXException e) { logger.warn("SAXException when parsing " + pieces[3], e); } resp.setHeader("Content-Type", "text/plain; charset=UTF-8"); out.write(b.toString().getBytes()); return; } } catch (Exception e) { throw new ServletException(e); } } } }
From source file:es.tid.cep.esperanza.Rules.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from ww w. j a va 2 s . co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("application/json;charset=UTF-8"); try { String ruleName = request.getPathInfo(); ruleName = ruleName == null ? "" : ruleName.substring(1); logger.debug("rule asked for " + ruleName); EPAdministrator epa = epService.getEPAdministrator(); if (ruleName.length() != 0) { EPStatement st = epa.getStatement(ruleName); if (st == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); out.printf("{\"error\":\"%s not found\"}\n", ruleName); } else { out.println(Utils.Statement2JSONObject(st)); } } else { String[] sttmntNames = epa.getStatementNames(); JSONArray ja = new JSONArray(); for (String name : sttmntNames) { logger.debug("getting rule " + name); EPStatement st = epa.getStatement(name); ja.put(Utils.Statement2JSONObject(st)); } out.println(ja.toString()); } } catch (EPException epe) { logger.error("getting statement", epe); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage())); } finally { out.close(); } }
From source file:com.example.cloud.bigtable.helloworld.JsonServlet.java
/** * doGet() - for a given row, put all values into a simple JSON request. * (basically a simple map<key,v>) * * Column Family CF1 is well known, so we don't mention it in the JSON output, any additional * families will be encoded as family:col, which is valid JSON, but not valid javascript. * * This is fairly simple code, so if there is a column with invalid syntax for JSON, there will be * an error.// www. j ava2 s . c o m * Bigtable (and hbase) fields are basically blobs, so I've chosen to recognize a few "datatypes" * bool is defined as 1 byte (either 0x00 / 0x01) for (false / true) * counter (long) 64 bits 8 bytes and the first 4 bytes are either 0 or -128 * doubles we will keep as text in Bigtable / hbase **/ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); String key; JSONObject json = new JSONObject(); if (path.length() < 5) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); log("doGet-bad length-" + path.length()); return; } // IMPORTANT - This try() is a java7 try w/ resources which will close() the table at the end. try (Table t = BigtableHelper.getConnection().getTable(TABLE)) { Get g = new Get(Bytes.toBytes(path.substring(1))); g.setMaxVersions(1); Result r = t.get(g); log(r.toString()); NavigableMap<byte[], NavigableMap<byte[], byte[]>> map = r.getNoVersionMap(); if (map == null) { resp.setContentType("application/json"); resp.getWriter().print("{}"); return; } // For Every Family for (Map.Entry<byte[], NavigableMap<byte[], byte[]>> family : map.entrySet()) { String cFamily = Bytes.toString(family.getKey()); // Each column for (Map.Entry<byte[], byte[]> entry : family.getValue().entrySet()) { String col = Bytes.toString(entry.getKey()); byte[] val = entry.getValue(); if (cFamily.equals(cf1)) { key = col; } else { key = cFamily + ":" + col; } // Based on data type, create the json. 8 bytes (leading 0) is an int (counter) // 1 byte (0/1) = (false/true) else string switch (val.length) { case 8: if ((val[0] == 0 && val[1] == 0 && val[2] == 0 && val[3] == 0) || (val[0] == -1 && val[1] == -1 && val[2] == -1 && val[3] == -1)) { json.put(key, Bytes.toLong(val)); } else { String temp = Bytes.toString(val); if (isNumeric(temp)) { if (isDigits(temp)) { json.put(key, Long.parseLong(temp)); } else { json.put(key, Double.parseDouble(temp)); } } else { json.put(key, temp); } } break; case 1: switch (val[0]) { case 0: json.put(key, false); continue; case 1: json.put(key, true); continue; default: } default: String temp = Bytes.toString(val); if (isNumeric(temp)) { if (isDigits(temp)) { json.put(key, Long.parseLong(temp)); } else { json.put(key, Double.parseDouble(temp)); } } else { json.put(key, temp); } } } } resp.addHeader("Access-Control-Allow-Origin", "*"); resp.setContentType("application/json"); json.write(resp.getWriter()); } catch (Exception e) { log("doGet", e); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } resp.setStatus(HttpServletResponse.SC_OK); }
From source file:net.sourceforge.vulcan.web.ProjectFileServlet.java
private String getFallbackParentPath(HttpServletRequest request, String workDir) { final StringBuilder pathInfo = new StringBuilder(request.getPathInfo()); while (!getFile(workDir, pathInfo.toString(), true).exists()) { pathInfo.delete(pathInfo.lastIndexOf("/"), pathInfo.length()); }// w w w . ja v a 2s .co m final StringBuilder buf = new StringBuilder(request.getContextPath()); buf.append(request.getServletPath()); buf.append(pathInfo); buf.append("/"); return buf.toString(); }
From source file:com.jd.survey.web.settings.GlobalSettingsController.java
@Secured({ "ROLE_ADMIN" }) @RequestMapping(method = RequestMethod.PUT, produces = "text/html") public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid GlobalSettings globalSettings, BindingResult bindingResult, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("update(): handles PUT"); try {/*w ww . j a v a 2s. c o m*/ User user = userService.user_findByLogin(principal.getName()); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { if (bindingResult.hasErrors()) { populateEditForm(uiModel, globalSettings, user); return "settings/globalSettings/update"; } uiModel.asMap().clear(); globalSettings = applicationSettingsService.globalSettings_merge(globalSettings); return "redirect:/settings/globalSettings/" + encodeUrlPathSegment(globalSettings.getId().toString(), httpServletRequest); } else { return "redirect:/settings/globalSettings/" + encodeUrlPathSegment(globalSettings.getId().toString(), httpServletRequest); } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:com.anite.ocelot.MultipleRequestFilter.java
/** * /* w ww . ja v a 2s . c o m*/ * ensure we only get activated for requests that were kicked off * from submits, etc * * Note: a request can also be for images, JavaScript, CSS files, * etc, so we have to be careful to only deal with appropriate * multiple requests * * @param httpRequest * @return */ private boolean checkIfShouldHandle(HttpServletRequest httpRequest) { if (httpRequest.getPathInfo() != null) { if (httpRequest.getPathInfo().startsWith("/action/")) { return false; } else if (httpRequest.getPathInfo().startsWith("/template/")) { return false; } } else { return false; } if (httpRequest.getParameter(SKIP_OCELOT) != null) { return false; } return true; }