List of usage examples for javax.servlet.http HttpServletRequest getPathInfo
public String getPathInfo();
From source file:fr.immotronic.ubikit.pems.modbus.impl.APIServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String[] pathInfo = req.getPathInfo().split("/"); // Expected path info is /command/command_param_1/command_param_2/...etc. // Notes: if the request is valid (e.g. looks like /command/command_params), // pathInfo[0] contains an empty string, // pathInfo[1] contains "command", // pathInfo[2] and next each contains a command parameter. Command parameters are "/"-separated. if (pathInfo != null && pathInfo.length > 1) { if (pathInfo[1].equals("add")) { try { DeviceProfile profile = DeviceProfile.valueOf(req.getParameter("deviceProfile")); JSONObject properties = new JSONObject(req.getParameter("properties")); AbstractPhysicalEnvironmentModelEvent addingResponseEvent = pemLauncher.createNewDevice(profile, req.getParameter("unitID"), req.getParameter("customName"), req.getParameter("location"), properties, Integer.parseInt(req.getParameter("autoReadingFrequency"))); if (addingResponseEvent != null) { if (addingResponseEvent instanceof ItemAddedEvent) { JSONObject o = new JSONObject(); try { o.put("deviceUID", addingResponseEvent.getSourceItemUID()); } catch (JSONException e) { Logger.error(LC.gi(), this, "doPost/addDevice: While building the response object."); resp.getWriter() .write(WebApiCommons.errorMessage(WebApiCommons.Errors.internal_error)); return; }/*from ww w . ja v a 2s. c o m*/ resp.getWriter().write(WebApiCommons.okMessage(o)); return; } else if (addingResponseEvent instanceof ItemAddingFailedEvent) { ItemAddingFailedEvent e = (ItemAddingFailedEvent) addingResponseEvent; resp.getWriter().write(WebApiCommons.errorMessage(e.getReason(), e.getErrorCode())); return; } } else { Logger.error(LC.gi(), this, "doPost/addDevice: While building the response object."); resp.getWriter().write(WebApiCommons.errorMessage(WebApiCommons.Errors.internal_error)); return; } } catch (JSONException e) { Logger.error(LC.gi(), this, "doPost/addDevice: Error when reading device specific properties."); resp.getWriter().write(WebApiCommons.errorMessage(WebApiCommons.Errors.internal_error)); return; } catch (NumberFormatException e) { Logger.error(LC.gi(), this, "doPost/addDevice: Automatic Reading Frequency is not an Integer."); resp.getWriter().write(WebApiCommons.errorMessage("FREQUENCY_IS_NOT_A_NUMBER", WebApiCommons.Errors.invalid_query)); return; } } } resp.getWriter().write(WebApiCommons.errorMessage(WebApiCommons.Errors.invalid_query)); }
From source file:com.jaspersoft.jasperserver.rest.RESTAbstractService.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { log.error("Method POST is not supported for this object type - request params: Path: " + req.getPathInfo()); restUtils.setStatusAndBody(HttpServletResponse.SC_METHOD_NOT_ALLOWED, resp, "Method not supported for this object type"); }
From source file:de.micromata.genome.tpsb.httpmockup.MockFilterChain.java
@Override public void doFilter(final ServletRequest req, final ServletResponse resp) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest) req; String uri = hreq.getRequestURI(); String localUri = uri;// ww w.ja v a2 s . c o m if (StringUtils.isNotBlank(hreq.getServletPath()) && StringUtils.isNotBlank(hreq.getPathInfo()) == true) { localUri = hreq.getServletPath() + hreq.getPathInfo(); } final MockFiltersConfig fc = this.mockupServletContext.getFiltersConfig(); this.filterIndex = fc.getNextFilterMapDef(localUri, this.filterIndex, this.dispatcherFlag); if (this.filterIndex == -1) { this.mockupServletContext.serveServlet((HttpServletRequest) req, (HttpServletResponse) resp); return; } final Filter f = fc.getFilterMapping().get(this.filterIndex).getFilterDef().getFilter(); ++this.filterIndex; if (log.isDebugEnabled() == true) { log.debug("Filter filter: " + f.getClass().getName()); } f.doFilter(req, resp, this); }
From source file:com.thinkberg.moxo.dav.LockHandler.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = getResourceManager().getFileObject(request.getPathInfo()); try {//from w w w . ja va 2 s . co m Lock lock = LockManager.getInstance().checkCondition(object, getIf(request)); if (lock != null) { sendLockAcquiredResponse(response, lock); return; } } catch (LockException e) { // handle locks below } try { SAXReader saxReader = new SAXReader(); Document lockInfo = saxReader.read(request.getInputStream()); //log(lockInfo); Element rootEl = lockInfo.getRootElement(); String lockScope = null, lockType = null; Object owner = null; Iterator elIt = rootEl.elementIterator(); while (elIt.hasNext()) { Element el = (Element) elIt.next(); if (TAG_LOCKSCOPE.equals(el.getName())) { lockScope = el.selectSingleNode("*").getName(); } else if (TAG_LOCKTYPE.equals(el.getName())) { lockType = el.selectSingleNode("*").getName(); } else if (TAG_OWNER.equals(el.getName())) { // TODO correctly handle owner Node subEl = el.selectSingleNode("*"); if (subEl != null && TAG_HREF.equals(subEl.getName())) { owner = new URL(el.selectSingleNode("*").getText()); } else { owner = el.getText(); } } } log("LOCK(" + lockType + ", " + lockScope + ", " + owner + ")"); Lock requestedLock = new Lock(object, lockType, lockScope, owner, getDepth(request), getTimeout(request)); try { LockManager.getInstance().acquireLock(requestedLock); sendLockAcquiredResponse(response, requestedLock); } catch (LockConflictException e) { response.sendError(SC_LOCKED); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); } } catch (DocumentException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.thinkberg.moxo.dav.CopyMoveBase.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { boolean overwrite = getOverwrite(request); FileObject object = getResourceManager().getFileObject(request.getPathInfo()); FileObject targetObject = getDestination(request); try {/*from w w w. j a v a 2s. c o m*/ // check that we can write the target LockManager.getInstance().checkCondition(targetObject, getIf(request)); // if we move, check that we can actually write on the source if ("MOVE".equals(request.getMethod())) { LockManager.getInstance().checkCondition(object, getIf(request)); } } catch (LockException e) { if (e.getLocks() != null) { response.sendError(SC_LOCKED); } else { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } return; } if (null == targetObject) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (object.equals(targetObject)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } if (targetObject.exists()) { if (!overwrite) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } response.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { FileObject targetParent = targetObject.getParent(); if (!targetParent.exists() || !FileType.FOLDER.equals(targetParent.getType())) { response.sendError(HttpServletResponse.SC_CONFLICT); } response.setStatus(HttpServletResponse.SC_CREATED); } copyOrMove(object, targetObject, getDepth(request)); }
From source file:eu.annocultor.tagger.server.controllers.SolrTaggerController.java
@RequestMapping("/doc/**/*.*") public void report(HttpServletRequest request, HttpServletResponse response) throws Exception { String path = merge(request.getServletPath(), request.getPathInfo()); path = path.substring("/doc".length()); response.setCharacterEncoding("UTF-8"); ServletOutputStream outputStream = response.getOutputStream(); try {//from w w w . j ava 2 s . com IOUtils.copy(new FileInputStream(new File(fetchDoc(), path)), outputStream); } finally { outputStream.close(); } }
From source file:de.fau.amos.FileUpload.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); System.out.println("called fileupload: " + pathInfo); boolean isImportProductionData = pathInfo != null && pathInfo.startsWith("/importProductionData"); boolean isImportEnergyData = pathInfo != null && pathInfo.startsWith("/importEnergyData"); if (ServletFileUpload.isMultipartContent(request)) { try {/*from www. j a v a2 s . c o m*/ List<FileItem> list = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem fi : list) { if (!fi.isFormField()) { String rand = ""; for (int i = 0; i < 6; i++) { rand += (int) (Math.random() * 10); } String plantId = ""; if (isImportEnergyData || isImportProductionData) { plantId = request.getPathInfo().replace((isImportEnergyData ? "/importEnergyData" : (isImportProductionData ? "/importProductionData" : "")), ""); } if (plantId == null || plantId.length() == 0) { plantId = ""; // }else{ // plantId="_"+plantId; } String name = new File(rand + "_" + fi.getName()).getName() + (isImportEnergyData ? "_impED" + plantId : (isImportProductionData ? "_impPD" + plantId : "")); File folder = null; if (isImportEnergyData || isImportProductionData) { folder = new File(System.getProperty("userdir.location"), "import"); } else { folder = new File(System.getProperty("userdir.location"), "uploads"); } if (!folder.exists()) { folder.mkdirs(); } fi.write(new File(folder, name)); } } request.setAttribute("message", "File uploaded successfully"); } catch (Exception e) { request.setAttribute("errorMessage", "File upload failed!"); } } else { request.setAttribute("errorMessage", "Something went wrong."); } if (isImportEnergyData || isImportProductionData) { // request.setAttribute("plant",request.getPathInfo().replace("/import","")); // request.getRequestDispatcher("/intern/import.jsp").forward(request, response); response.sendRedirect(request.getContextPath() + "/intern/import.jsp"); } else { response.sendRedirect(request.getContextPath() + "/intern/funktion3.jsp"); } }
From source file:com.smartgwt.extensions.fileuploader.server.DownloadServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) { // url: /thinkspace/download/project/2/..... String path = request.getPathInfo(); String[] items = path.split("/"); if (items.length < 3 || !items[1].equals("project")) { // if no path info then nothing can be downloaded reportError(response);/*from ww w.j a va2s. com*/ return; } InputStream in = null; try { int pid = Integer.parseInt(items[2]); /* Project project = ProjectService.get().getProjectById(pid); String contextName = project.getContext(); ProjectState state = (ProjectState) request.getSession().getAttribute(contextName); if (state == null) { // if no state then user has not authenticated reportError(response); return; } */ // only files in lib directories can be downloaded boolean hasPermission = false; for (int i = items.length - 1; i > 2; i--) { if (items[i].equals("lib")) { hasPermission = true; break; } } if (!hasPermission) { reportError(response); return; } /* File f = state.getFileManager().getFile(path); String type = ContentService.get().getContentType(path); response.setContentType(type); response.setContentLength((int)f.length()); response.setHeader("Content-Disposition", "inline; filename="+Util.encode(f.getName())); response.setHeader("Last-Modified",hdf.format(new Date(f.lastModified()))); in = new BufferedInputStream(new FileInputStream(f)); */ ServletOutputStream out = response.getOutputStream(); byte[] buf = new byte[8192]; int len = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); out.flush(); } catch (Exception e) { reportError(response); log.error(e); } finally { if (in != null) try { in.close(); } catch (Exception e) { } ; } }
From source file:com.aipo.social.core.oauth2.AipoOAuth2Servlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpUtil.setNoCache(response);/*from w w w . j a va 2 s . c o m*/ String path = request.getPathInfo(); if (path.endsWith(AUTHORIZE)) { sendOAuth2Response(response, authorizationHandler.handle(request, response)); } else if (path.endsWith(TOKEN)) { // token endpoint must use POST method response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "The client MUST use the HTTP \"POST\" method " + "when making access token requests."); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown URL"); } }
From source file:io.ericwittmann.corsproxy.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*www . j av a 2 s . co m*/ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = "https://issues.jboss.org" + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; try { Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }