List of usage examples for javax.servlet.http HttpServletRequest getMethod
public String getMethod();
From source file:com.centurylink.mdw.hub.servlet.RestServlet.java
protected String handleRequest(HttpServletRequest request, HttpServletResponse response, Map<String, String> metaInfo) throws ServiceException, IOException { if (logger.isMdwDebugEnabled()) { logger.mdwDebug(// w w w .ja v a2s . com getClass().getSimpleName() + " " + request.getMethod() + ":\n " + request.getRequestURI() + (request.getQueryString() == null ? "" : ("?" + request.getQueryString()))); } String requestString = null; // DELETE can have a body in some containers if (!"GET".equalsIgnoreCase(request.getMethod())) { BufferedReader reader = request.getReader(); StringBuffer requestBuffer = new StringBuffer( request.getContentLength() < 0 ? 0 : request.getContentLength()); String line; while ((line = reader.readLine()) != null) requestBuffer.append(line).append('\n'); // log request requestString = requestBuffer.toString(); if (logger.isMdwDebugEnabled()) { logger.mdwDebug( getClass().getSimpleName() + " " + request.getMethod() + " Request:\n" + requestString); } } authenticate(request, metaInfo, requestString); if (metaInfo.containsKey(Listener.METAINFO_REQUEST_PAYLOAD)) { requestString = metaInfo.get(Listener.METAINFO_REQUEST_PAYLOAD); metaInfo.remove(Listener.METAINFO_REQUEST_PAYLOAD); } Set<String> reqHeaderKeys = new HashSet<String>(metaInfo.keySet()); String responseString = new ListenerHelper().processEvent(requestString, metaInfo); populateResponseHeaders(reqHeaderKeys, metaInfo, response); if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) == null) response.setContentType("application/json"); else response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE)); if (metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE) != null && !metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE).equals("0")) response.setStatus(Integer.parseInt(metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE))); if (logger.isMdwDebugEnabled()) { logger.mdwDebug( getClass().getSimpleName() + " " + request.getMethod() + " Response:\n" + responseString); } return responseString; }
From source file:org.jetbrains.webdemo.handlers.ServerHandler.java
private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response, Map<String, String> postParameters) { final boolean hasoutbody = (request.getMethod().equals("POST")); try {//from w ww . j a va2 s.co m final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/" + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); final Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { final String header = headers.nextElement(); final Enumeration<String> values = request.getHeaders(header); while (values.hasMoreElements()) { final String value = values.nextElement(); conn.addRequestProperty(header, value); } } conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setUseCaches(false); conn.setDoOutput(hasoutbody); if (postParameters != null && !postParameters.isEmpty()) { conn.setRequestMethod("POST"); try (OutputStream requestBody = conn.getOutputStream()) { boolean first = true; for (Map.Entry<String, String> entry : postParameters.entrySet()) { if (entry.getValue() == null) continue; if (first) { first = false; } else { requestBody.write('&'); } requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes()); requestBody.write('='); requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes()); } } } else { conn.setRequestMethod("GET"); } StringBuilder responseBody = new StringBuilder(); if (conn.getResponseCode() >= 400) { StringBuilder serverMessage = new StringBuilder(); try (InputStream errorStream = conn.getErrorStream()) { if (errorStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = errorStream.read(buffer); if (read <= 0) break; serverMessage.append(new String(buffer, 0, read)); } } } switch (conn.getResponseCode()) { case HttpServletResponse.SC_NOT_FOUND: responseBody.append("Kotlin compile server not found"); break; case HttpServletResponse.SC_SERVICE_UNAVAILABLE: responseBody.append("Kotlin compile server is temporary overloaded"); break; default: responseBody = serverMessage; break; } } else { try (InputStream inputStream = conn.getInputStream()) { if (inputStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = inputStream.read(buffer); if (read <= 0) break; responseBody.append(new String(buffer, 0, read)); } } } } writeResponse(request, response, responseBody.toString(), conn.getResponseCode()); } catch (SocketTimeoutException e) { writeResponse(request, response, "Compile server connection timeout", HttpServletResponse.SC_GATEWAY_TIMEOUT); } catch (Exception e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "", "Can't forward request to Kotlin compile server"); writeResponse(request, response, "Can't send your request to Kotlin compile server", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.codemucker.testserver.capturing.CapturedRequest.java
public CapturedRequest(final HttpServletRequest req) { scheme = req.getScheme();//from www . java2 s . c o m host = req.getServerName(); port = req.getServerPort(); contextPath = req.getContextPath(); servletPath = req.getServletPath(); pathInfo = req.getPathInfo(); characterEncoding = req.getCharacterEncoding(); method = req.getMethod(); final Cookie[] cookies = req.getCookies(); // cookies if (cookies != null) { for (final Cookie cookie : cookies) { this.cookies.add(new CapturedCookie(cookie)); } } // headers for (@SuppressWarnings("unchecked") final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) { final String name = names.nextElement(); @SuppressWarnings("unchecked") final Enumeration<String> values = req.getHeaders(name); if (values != null) { for (; values.hasMoreElements();) { this.addHeader(new CapturedHeader(name, values.nextElement())); } } } // if we use the normal 'toString' on maps, and arrays, we get pretty // poor results // Use ArrayLists instead to get a nice output @SuppressWarnings("unchecked") final Map<String, String[]> paramMap = req.getParameterMap(); if (paramMap != null) { for (final String key : paramMap.keySet()) { final String[] vals = paramMap.get(key); this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals))); } } // handle multipart posts if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items final FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(factory); try { @SuppressWarnings("unchecked") final List<FileItem> items = upload.parseRequest(req); for (final FileItem item : items) { fileItems.add(new CapturedFileItem(item)); } } catch (final FileUploadException e) { throw new RuntimeException("Error handling multipart content", e); } } }
From source file:com.boxedfolder.carrot.config.general.filter.CORSFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Accept, Content-Type, Origin, Authorization, x-auth-token"); response.addHeader("Access-Control-Expose-Headers", "x-auth-token"); if (request.getMethod().equals("OPTIONS")) { try {/* w ww .jav a 2 s .c o m*/ response.getWriter().print("OK"); response.getWriter().flush(); } catch (IOException e) { Logger log = LoggerFactory.getLogger(getClass()); log.error("Exception thrown: " + e.getMessage()); } } else { chain.doFilter(request, response); } }
From source file:com.jaspersoft.jasperserver.rest.utils.Utils.java
public boolean isMultipartContent(HttpServletRequest request) { if (!(RESTAbstractService.HTTP_PUT.equals(request.getMethod().toLowerCase()) || RESTAbstractService.HTTP_POST.equals(request.getMethod().toLowerCase()))) { return false; }// ww w. j ava 2 s. c om String contentType = request.getContentType(); if (contentType == null) { return false; } if (contentType.toLowerCase().startsWith("multipart/")) { return true; } return false; }
From source file:com.nn.cfw.web.security.CustomCsrfPreventionFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletResponse wResponse = null;//from w w w . ja v a2 s. c om if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; boolean skipNonceCheck = false; if (Constants.METHOD_GET.equals(req.getMethod()) && entryPoints.contains(getRequestedPath(req))) { skipNonceCheck = true; } HttpSession session = req.getSession(false); @SuppressWarnings("unchecked") LruCache<String> nonceCache = (session == null) ? null : (LruCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME); if (!skipNonceCheck) { String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM); if (nonceCache == null || previousNonce == null || !nonceCache.contains(previousNonce)) { res.sendError(getDenyStatus()); return; } } if (nonceCache == null) { nonceCache = new LruCache<String>(nonceCacheSize); if (session == null) { session = req.getSession(true); } session.setAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache); } String newNonce = generateNonce(); nonceCache.add(newNonce); wResponse = new CsrfResponseWrapper(res, newNonce); } else { wResponse = response; } chain.doFilter(request, wResponse); }
From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java
@SuppressWarnings("unchecked") protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ("GET".equalsIgnoreCase(request.getMethod())) { //just render blank page for upload String pageUuid = request.getParameter("puuid"); String spaceUname = request.getParameter("uname"); String draft = request.getParameter("draft"); request.setAttribute("pageUuid", pageUuid); request.setAttribute("spaceUname", spaceUname); request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value())); request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response); return;/*from w ww. j a v a2 s . c o m*/ } //post - upload // if(WikiUtil.getUser().isAnonymous()){ // //anonymous can not allow to upload any files PageService pageService = getPageService(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); List<FileNode> files = new ArrayList<FileNode>(); String pageUuid = null, spaceUname = null; try { int status = PageType.NONE_DRAFT.value(); // index->filename Map<String, FileItem> fileMap = new HashMap<String, FileItem>(); Map<String, String> descMap = new HashMap<String, String>(); // index->index Map<String, String> indexMap = new HashMap<String, String>(); //offline submission, filename put into hidden variable rather than <input type="file> tag Map<String, String> filenameMap = new HashMap<String, String>(); //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check: //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case Map<String, String> versionMap = new HashMap<String, String>(); Map<String, Boolean> bulkMap = new HashMap<String, Boolean>(); Map<String, Boolean> sharedMap = new HashMap<String, Boolean>(); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { String name = item.getFieldName(); if (StringUtils.equals(name, "spaceUname")) { spaceUname = item.getString(Constants.UTF8); } else if (StringUtils.equals(name, "pageUuid")) { pageUuid = item.getString(); } else if (name.startsWith("draft")) { // check this upload is from "click save button" or "auto upload in draft status" status = Integer.parseInt(item.getString()); } else if (name.startsWith("file")) { fileMap.put(name.substring(4), item); indexMap.put(name.substring(4), name.substring(4)); } else if (name.startsWith("desc")) { descMap.put(name.substring(4), item.getString(Constants.UTF8)); } else if (name.startsWith("shar")) { sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString())); } else if (name.startsWith("name")) { filenameMap.put(name.substring(4), item.getString()); } else if (name.startsWith("vers")) { versionMap.put(name.substring(4), item.getString()); } else if (name.startsWith("bulk")) { bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString())); } } if (StringUtils.isBlank(pageUuid)) { log.error("Attachment can not be load because of page does not save successfully."); throw new PageException("Attachment can not be load because of page does not save successfully."); } List<FileNode> bulkFiles = new ArrayList<FileNode>(); String username = request.getRemoteUser(); // put file/desc pair into final Map for (String id : fileMap.keySet()) { FileItem item = fileMap.get(id); if (item == null || item.getInputStream() == null || item.getSize() <= 0) { log.warn("Empty upload item:" + (item != null ? item.getName() : "")); continue; } FileNode node = new FileNode(); node.setComment(descMap.get(id)); node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id)); node.setFile(item.getInputStream()); String filename = item.getName(); if (StringUtils.isBlank(filename)) { //this could be offline submission, get name from map filename = filenameMap.get(id); } node.setFilename(FileUtil.getFileName(filename)); node.setContentType(item.getContentType()); node.setIndex(indexMap.get(id)); node.setType(RepositoryService.TYPE_ATTACHMENT); node.setIdentifier(pageUuid); node.setCreateor(username); node.setStatus(status); node.setSize(item.getSize()); node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id)); files.add(node); if (node.isBulkZip()) bulkFiles.add(node); } if (spaceUname != null && pageUuid != null && files.size() > 0) { files = pageService.uploadAttachments(spaceUname, pageUuid, files, false); //only save non-draft uploaded attachment if (status == 0) { try { getActivityLog().logAttachmentUploaded(spaceUname, pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files); } catch (Exception e) { log.warn("Activity log save error for attachment upload", e); } } //as bulk files won't in return list in PageService.uploadAttachments(), here need //append to all return list, but only for client side "uploading panel" clean purpose files.addAll(bulkFiles); //TODO: if version come in together, then do check // if(versionMap.size() > 0){ // for (FileNode node: files) { // // } // } } } catch (RepositoryQuotaException e) { FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.quota.exhaust")); files = Arrays.asList(att); } catch (AuthenticationException e) { String redir = ((RedirectResponseWrapper) response).getRedirect(); if (redir == null) redir = WikiConstants.URL_LOGIN; log.info("Send Authentication redirect URL " + redir); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.authentication.required")); files = Arrays.asList(att); } catch (AccessDeniedException e) { String redir = ((RedirectResponseWrapper) response).getRedirect(); if (redir == null) redir = WikiConstants.URL_ACCESS_DENIED; log.info("Send AccessDenied redirect URL " + redir); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.access.denied")); files = Arrays.asList(att); } catch (Exception e) { // FileUploadException,RepositoryException log.error("File upload failed ", e); FileNode att = new FileNode(); att.setError(getMessageService().getMessage("err.upload")); files = Arrays.asList(att); } try { String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(), getUserReadingService()); //TODO: does not compress request in Gzip, refer to //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first byte[] reply = json.getBytes(Constants.UTF8); response.setContentLength(reply.length); response.setContentType("text/plain; charset=utf-8"); response.getOutputStream().write(reply); } catch (IOException e) { log.error(e.toString(), e); } }
From source file:waffle.spring.NegotiateSecurityFilter.java
@Override public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; NegotiateSecurityFilter.LOGGER.debug("{} {}, contentlength: {}", request.getMethod(), request.getRequestURI(), Integer.valueOf(request.getContentLength())); final AuthorizationHeader authorizationHeader = new AuthorizationHeader(request); // authenticate user if (!authorizationHeader.isNull() && this.provider.isSecurityPackageSupported(authorizationHeader.getSecurityPackage())) { // log the user in using the token IWindowsIdentity windowsIdentity; try {// w ww . j av a2 s . c om windowsIdentity = this.provider.doFilter(request, response); if (windowsIdentity == null) { return; } } catch (final IOException e) { NegotiateSecurityFilter.LOGGER.warn("error logging in user: {}", e.getMessage()); NegotiateSecurityFilter.LOGGER.trace("{}", e); this.sendUnauthorized(response, true); return; } if (!this.allowGuestLogin && windowsIdentity.isGuest()) { NegotiateSecurityFilter.LOGGER.warn("guest login disabled: {}", windowsIdentity.getFqn()); this.sendUnauthorized(response, true); return; } try { NegotiateSecurityFilter.LOGGER.debug("logged in user: {} ({})", windowsIdentity.getFqn(), windowsIdentity.getSidString()); final WindowsPrincipal principal = new WindowsPrincipal(windowsIdentity, this.principalFormat, this.roleFormat); NegotiateSecurityFilter.LOGGER.debug("roles: {}", principal.getRolesString()); final Authentication authentication = new WindowsAuthenticationToken(principal, this.grantedAuthorityFactory, this.defaultGrantedAuthority); if (!this.setAuthentication(request, response, authentication)) { return; } NegotiateSecurityFilter.LOGGER.info("successfully logged in user: {}", windowsIdentity.getFqn()); } finally { windowsIdentity.dispose(); } } chain.doFilter(request, response); }
From source file:com.adobe.acs.commons.http.headers.impl.AbstractDispatcherCacheHeaderFilter.java
@SuppressWarnings("unchecked") protected boolean accepts(final HttpServletRequest request) { Enumeration<String> agentsEnum = request.getHeaders(SERVER_AGENT_NAME); List<String> serverAgents = agentsEnum != null ? Collections.list(agentsEnum) : Collections.<String>emptyList(); // Only inject when: // - GET request // - No Params // - From Dispatcher if (StringUtils.equalsIgnoreCase("get", request.getMethod()) && request.getParameterMap().isEmpty() && serverAgents.contains(DISPATCHER_AGENT_HEADER_VALUE)) { return true; }//w ww. ja va 2 s . co m return false; }