List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:com.du.order.dist.log.LoggingFilter.java
private void logRequest(final HttpServletRequest request) { StringBuilder msg = new StringBuilder(); msg.append(REQUEST_PREFIX);/* w w w .j av a2s . c o m*/ if (request instanceof RequestWrapper) { msg.append("request id=").append(((RequestWrapper) request).getId()).append("; "); } HttpSession session = request.getSession(false); if (session != null) { msg.append("session id=").append(session.getId()).append("; "); } if (request.getMethod() != null) { msg.append("method=").append(request.getMethod()).append("; "); } if (request.getContentType() != null) { msg.append("content type=").append(request.getContentType()).append("; "); } msg.append("uri=").append(request.getRequestURI()); if (request.getQueryString() != null) { msg.append('?').append(request.getQueryString()); } if (request instanceof RequestWrapper && !isMultipart(request) && !isBinaryContent(request)) { RequestWrapper requestWrapper = (RequestWrapper) request; try { // TODO deniz check it ( String str = new String(requestWrapper.toByteArray(), charEncoding); ); String charEncoding = requestWrapper.getCharacterEncoding() != null ? requestWrapper.getCharacterEncoding() : "UTF-8"; String str = new String(requestWrapper.toByteArray(), charEncoding); str = "".equals(str) || str == null ? "{}" : str; msg.append("; payload=").append(JsonFormatter.format(new JSONObject())); } catch (UnsupportedEncodingException e) { logger.warn("Failed to parse request payload", e); } } logger.info(msg.toString()); }
From source file:com.github.isrsal.logging.LoggingFilter.java
private void logRequest(final HttpServletRequest request) { StringBuilder msg = new StringBuilder(); msg.append(REQUEST_PREFIX);//www. ja v a 2s . co m if (request instanceof RequestWrapper) { msg.append("request id=").append(((RequestWrapper) request).getId()).append("; "); } HttpSession session = request.getSession(false); if (session != null) { msg.append("session id=").append(session.getId()).append("; "); } if (request.getMethod() != null) { msg.append("method=").append(request.getMethod()).append("; "); } if (request.getContentType() != null) { msg.append("content type=").append(request.getContentType()).append("; "); } msg.append("uri=").append(request.getRequestURI()); if (request.getQueryString() != null) { msg.append('?').append(request.getQueryString()); } if (request instanceof RequestWrapper && !isMultipart(request) && !isBinaryContent(request)) { RequestWrapper requestWrapper = (RequestWrapper) request; try { String charEncoding = requestWrapper.getCharacterEncoding() != null ? requestWrapper.getCharacterEncoding() : "UTF-8"; msg.append("; payload=").append(new String(requestWrapper.toByteArray(), charEncoding)); } catch (UnsupportedEncodingException e) { logger.warn("Failed to parse request payload", e); } if (!requestWrapper.getParameterMap().isEmpty()) { msg.append("; parameters="); Map<String, String[]> parameterMap = requestWrapper.getParameterMap(); for (String key : parameterMap.keySet()) { msg.append(key + ":" + Arrays.toString(parameterMap.get(key))).append(";"); } } } logger.debug(msg.toString()); }
From source file:org.seasr.meandre.components.tools.text.io.InputData.java
@SuppressWarnings("unchecked") @Override//from w ww. j a v a 2 s.c om public void handle(HttpServletRequest request, HttpServletResponse response) throws WebUIException { console.entering(getClass().getName(), "handle", response); console.finer("Request method:\t" + request.getMethod()); console.finer("Request content-type:\t" + request.getContentType()); console.finer("Request path:\t" + request.getPathInfo()); console.finer("Request query string:\t" + request.getQueryString()); response.setStatus(HttpServletResponse.SC_OK); String action = request.getParameter("action"); console.fine("Action: " + action); if (action != null) { StreamInitiator si = new StreamInitiator(streamId); StreamTerminator st = new StreamTerminator(streamId); if (action.equals("urls")) { SortedMap<String, URL> urls = new TreeMap<String, URL>(); Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); if (paramName.startsWith("url_")) { String sUrl = request.getParameter(paramName); console.fine(paramName + ": " + sUrl); try { urls.put(paramName, new URL(sUrl)); } catch (MalformedURLException e) { console.warning(sUrl + " is not a valid URL, ignoring it."); continue; } } } if (urls.size() == 0) throw new WebUIException("No URLs provided"); try { if (_wrapAsStream) { componentContext.pushDataComponentToOutput(OUT_LABEL, si); componentContext.pushDataComponentToOutput(OUT_DATA, si); } for (URL url : urls.values()) { componentContext.pushDataComponentToOutput(OUT_LABEL, BasicDataTypesTools.stringToStrings(url.toString())); componentContext.pushDataComponentToOutput(OUT_DATA, url); } if (_wrapAsStream) { componentContext.pushDataComponentToOutput(OUT_LABEL, st); componentContext.pushDataComponentToOutput(OUT_DATA, st); } } catch (ComponentContextException e) { throw new WebUIException(e); } } else if (action.equals("text")) { String text = request.getParameter("text"); if (text == null || text.length() == 0) throw new WebUIException("No text provided"); try { if (_wrapAsStream) { componentContext.pushDataComponentToOutput(OUT_LABEL, si); componentContext.pushDataComponentToOutput(OUT_DATA, si); } componentContext.pushDataComponentToOutput(OUT_LABEL, BasicDataTypesTools.stringToStrings("text_input")); componentContext.pushDataComponentToOutput(OUT_DATA, text); if (_wrapAsStream) { componentContext.pushDataComponentToOutput(OUT_LABEL, st); componentContext.pushDataComponentToOutput(OUT_DATA, st); } } catch (ComponentContextException e) { throw new WebUIException(e); } } else if (action.equals("upload")) { if (!ServletFileUpload.isMultipartContent(request)) throw new WebUIException("File upload request needs to be done using a multipart content type"); ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> uploadedFiles; try { uploadedFiles = fileUpload.parseRequest(request); } catch (FileUploadException e) { throw new WebUIException(e); } try { if (_wrapAsStream) { componentContext.pushDataComponentToOutput(OUT_LABEL, si); componentContext.pushDataComponentToOutput(OUT_DATA, si); } for (FileItem file : uploadedFiles) { if (file == null || !file.getFieldName().startsWith("file_")) continue; console.fine("isFormField:\t" + file.isFormField()); console.fine("fieldName:\t" + file.getFieldName()); console.fine("name:\t" + file.getName()); console.fine("contentType:\t" + file.getContentType()); console.fine("size:\t" + file.getSize()); if (file.isFormField()) continue; Strings label = BasicDataTypesTools.stringToStrings(file.getName()); Bytes data = BasicDataTypesTools.byteArrayToBytes(file.get()); componentContext.pushDataComponentToOutput(OUT_LABEL, label); componentContext.pushDataComponentToOutput(OUT_DATA, data); } if (_wrapAsStream) { componentContext.pushDataComponentToOutput(OUT_LABEL, st); componentContext.pushDataComponentToOutput(OUT_DATA, st); } } catch (ComponentContextException e) { throw new WebUIException(e); } } else throw new WebUIException("Unknown action: " + action); _done = true; try { response.getWriter().println( "<html><head><meta http-equiv='REFRESH' content='1;url=/'></head><body></body></html>"); } catch (IOException e) { throw new WebUIException(e); } } else emptyRequest(response); console.exiting(getClass().getName(), "handle"); }
From source file:com.aipo.container.protocol.AipoDataServiceServlet.java
@Override protected void doPut(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { try {/* ww w . j a va 2s.c o m*/ checkContentTypes(ALLOWED_CONTENT_TYPES, servletRequest.getContentType()); executeRequest(servletRequest, servletResponse); } catch (ContentTypes.InvalidContentTypeException icte) { sendError(servletResponse, new ResponseItem(HttpServletResponse.SC_BAD_REQUEST, icte.getMessage(), AipoErrorCode.BAD_REQUEST.responseJSON())); } }
From source file:com.aipo.container.protocol.AipoDataServiceServlet.java
@Override protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { try {//from w w w. j av a2s. co m checkContentTypes(ALLOWED_CONTENT_TYPES, servletRequest.getContentType()); executeRequest(servletRequest, servletResponse); } catch (ContentTypes.InvalidContentTypeException icte) { sendError(servletResponse, new ResponseItem(HttpServletResponse.SC_BAD_REQUEST, icte.getMessage(), AipoErrorCode.BAD_REQUEST.responseJSON())); } }
From source file:org.ajax4jsf.webapp.BaseFilter.java
private boolean isMultipartRequest(HttpServletRequest request) { if (!"post".equals(request.getMethod().toLowerCase())) { return false; }/*from w ww. ja v a 2s. co m*/ String contentType = request.getContentType(); if (contentType == null) { return false; } if (contentType.toLowerCase().startsWith(MULTIPART)) { return true; } return false; }
From source file:org.ngrinder.script.controller.SvnDavController.java
@SuppressWarnings("StringConcatenationInsideStringBufferAppend") private void logRequest(HttpServletRequest request) { StringBuilder logBuffer = new StringBuilder(); logBuffer.append('\n'); logBuffer.append("request.getAuthType(): " + request.getAuthType()); logBuffer.append('\n'); logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding()); logBuffer.append('\n'); logBuffer.append("request.getContentType(): " + request.getContentType()); logBuffer.append('\n'); logBuffer.append("request.getContextPath(): " + request.getContextPath()); logBuffer.append('\n'); logBuffer.append("request.getContentLength(): " + request.getContentLength()); logBuffer.append('\n'); logBuffer.append("request.getMethod(): " + request.getMethod()); logBuffer.append('\n'); logBuffer.append("request.getPathInfo(): " + request.getPathInfo()); logBuffer.append('\n'); logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated()); logBuffer.append('\n'); logBuffer.append("request.getQueryString(): " + request.getQueryString()); logBuffer.append('\n'); logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr()); logBuffer.append('\n'); logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost()); logBuffer.append('\n'); logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser()); logBuffer.append('\n'); logBuffer.append("request.getRequestURI(): " + request.getRequestURI()); logBuffer.append('\n'); logBuffer.append("request.getServerName(): " + request.getServerName()); logBuffer.append('\n'); logBuffer.append("request.getServerPort(): " + request.getServerPort()); logBuffer.append('\n'); logBuffer.append("request.getServletPath(): " + request.getServletPath()); logBuffer.append('\n'); logBuffer.append("request.getRequestURL(): " + request.getRequestURL()); LOGGER.trace(logBuffer.toString());//from w w w. j a va2 s . c o m }
From source file:org.dspace.app.webui.servlet.BatchImportServlet.java
/** * Respond to a post request for metadata bulk importing via csv * * @param context//from w w w .j a v a2 s.c o m * The relevant DSpace Context. * @param request * Servlet's HTTP request object. * @param response * Servlet's HTTP response object. * @throws ServletException * A general exception a servlet can throw when it encounters difficulty. * @throws IOException * A general class of exceptions produced by failed or interrupted I/O operations. * @throws SQLException * An exception that provides information on a database access error or other errors. * @throws AuthorizeException * Exception indicating the current user of the context does not have permission * to perform a particular action. */ @Override protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // First, see if we have a multipart request (uploading a metadata file) String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { String message = null; // Process the file uploaded try { // Wrap multipart request to get the submission info FileUploadRequest wrapper = new FileUploadRequest(request); String inputType = wrapper.getParameter("inputType"); List<String> reqCollectionsTmp = getRepeatedParameter(wrapper, "collections", "collections"); String[] reqCollections = new String[reqCollectionsTmp.size()]; reqCollectionsTmp.toArray(reqCollections); //Get all collections List<Collection> collections = null; String colIdS = wrapper.getParameter("colId"); if (colIdS != null) { collections = new ArrayList<>(); collections.add(collectionService.findByIdOrLegacyId(context, colIdS)); } else { collections = collectionService.findAll(context); } request.setAttribute("collections", collections); Collection owningCollection = null; if (wrapper.getParameter("collection") != null) { owningCollection = collectionService.findByIdOrLegacyId(context, wrapper.getParameter("collection")); } //Get all the possible data loaders from the Spring configuration BTEBatchImportService dls = new DSpace().getSingletonService(BTEBatchImportService.class); List<String> inputTypes = dls.getFileDataLoaders(); request.setAttribute("input-types", inputTypes); if (reqCollectionsTmp != null) request.setAttribute("otherCollections", reqCollectionsTmp); if (owningCollection != null) request.setAttribute("owningCollection", owningCollection.getID()); request.setAttribute("inputType", inputType); File f = null; String zipurl = null; if (inputType.equals("saf")) { zipurl = wrapper.getParameter("zipurl"); if (StringUtils.isEmpty(zipurl)) { request.setAttribute("has-error", "true"); Locale locale = request.getLocale(); ResourceBundle msgs = ResourceBundle.getBundle("Messages", locale); try { message = msgs.getString("jsp.layout.navbar-admin.batchimport.fileurlempty"); } catch (Exception e) { message = "???jsp.layout.navbar-admin.batchimport.fileurlempty???"; } request.setAttribute("message", message); JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); return; } } else { f = wrapper.getFile("file"); if (f == null) { request.setAttribute("has-error", "true"); Locale locale = request.getLocale(); ResourceBundle msgs = ResourceBundle.getBundle("Messages", locale); try { message = msgs.getString("jsp.layout.navbar-admin.batchimport.fileempty"); } catch (Exception e) { message = "???jsp.layout.navbar-admin.batchimport.fileempty???"; } request.setAttribute("message", message); JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); return; } else if (owningCollection == null && !"safupload".equals(inputType)) { request.setAttribute("has-error", "true"); Locale locale = request.getLocale(); ResourceBundle msgs = ResourceBundle.getBundle("Messages", locale); try { message = msgs.getString("jsp.layout.navbar-admin.batchimport.owningcollectionempty"); } catch (Exception e) { message = "???jsp.layout.navbar-admin.batchimport.owningcollectionempty???"; } request.setAttribute("message", message); JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); return; } } String uploadId = wrapper.getParameter("uploadId"); if (uploadId != null) { request.setAttribute("uploadId", uploadId); } if (owningCollection == null && reqCollections != null && reqCollections.length > 0) { request.setAttribute("has-error", "true"); Locale locale = request.getLocale(); ResourceBundle msgs = ResourceBundle.getBundle("Messages", locale); String ms = msgs.getString("jsp.layout.navbar-admin.batchimport.owningcollection"); if (ms == null) { ms = "???jsp.layout.navbar-admin.batchimport.owningcollection???"; } request.setAttribute("message", ms); JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); return; } try { String finalInputType = "saf"; String filePath = zipurl; if (f != null) { finalInputType = inputType; filePath = f.getAbsolutePath(); } itemImportService.processUIImport(filePath, owningCollection, reqCollections, uploadId, finalInputType, context, true); request.setAttribute("has-error", "false"); request.setAttribute("uploadId", null); } catch (Exception e) { request.setAttribute("has-error", "true"); message = e.getMessage(); e.printStackTrace(); } } catch (FileSizeLimitExceededException e) { request.setAttribute("has-error", "true"); message = e.getMessage(); e.printStackTrace(); } catch (Exception e) { request.setAttribute("has-error", "true"); message = e.getMessage(); e.printStackTrace(); } request.setAttribute("message", message); // Show the upload screen JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); } else { request.setAttribute("has-error", "true"); // Show the upload screen JSPManager.showJSP(request, response, "/dspace-admin/batchimport.jsp"); } }
From source file:com.google.livingstories.servlet.DataImportServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { startTime = System.currentTimeMillis(); message = ""; if (req.getContentType().contains("multipart/form-data")) { try {//from w ww . j a v a 2 s. c om ServletFileUpload upload = new ServletFileUpload(); JSONObject data = null; boolean override = false; FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.getFieldName().equals("override")) { override = true; } else if (item.getFieldName().equals("data")) { data = new JSONObject(Streams.asString(item.openStream())); } } checkRunState(override); inputData = data; setUp(); } catch (FileUploadException ex) { throw new RuntimeException(ex); } catch (JSONException ex) { throw new RuntimeException(ex); } } try { process(); } catch (Exception ex) { Writer result = new StringWriter(); PrintWriter printWriter = new PrintWriter(result); ex.printStackTrace(printWriter); message = result.toString(); runState = RunState.ERROR; } finally { if (runState != RunState.RUNNING) { tearDown(); } Caches.clearAll(); } resp.setContentType("text/html"); resp.getWriter().append(message + "<br>" + runState.name()); }
From source file:com.wadpam.guja.oauth2.web.Oauth2ClientAuthenticationFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { LOGGER.debug("Oauth2 client authentication"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // Either the Authorize header or json body is used to provide the client credentials String authHeader = request.getHeader(OAuth2Filter.HEADER_AUTHORIZATION); ClientCredentials credentials = null; if (request.getContentLength() > 0 && (request.getContentType().startsWith(MediaType.APPLICATION_JSON) || request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED))) { HttpBodyRequestWrapper wrappedRequest = new HttpBodyRequestWrapper(request); if (request.getContentType().startsWith(MediaType.APPLICATION_JSON)) { // Parse JSON body credentials = objectMapper.readValue(wrappedRequest.getBody(), ClientCredentials.class); } else if (request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED)) { // Parse the form encoded request body. Remember to URL decode the parameters Map<String, String> formParams = Splitter.on("&").trimResults().withKeyValueSeparator("=") .split(wrappedRequest.getBody()); formParams = Maps.transformValues(formParams, new Function<String, String>() { @Override// w ww .j a va 2 s . co m public String apply(String value) { try { return URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.error("Not possible to URL decode {}", e); return value; } } }); LOGGER.debug("URL decoded form body {}", formParams); credentials = new ClientCredentials(); credentials.setClient_id(formParams.get("client_id")); credentials.setClient_secret((formParams.get("client_secret"))); } // Must wrap the request request = wrappedRequest; } // Check for duplicate authentication methods - invalid request if (null != authHeader && null != credentials && null != credentials.getClient_id() && null != credentials.getClient_secret()) { LOGGER.info("Bad request - duplicate client authentication credentials"); // Multiple authentication credentials (400, "invalid_request") errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST); return; } // check for header if (null != authHeader) { LOGGER.debug("{}: {}", OAuth2Filter.HEADER_AUTHORIZATION, authHeader); int beginIndex = authHeader.indexOf(PREFIX_BASIC_AUTHENTICATION); if (-1 < beginIndex) { String baString = authHeader.substring(beginIndex + PREFIX_BASIC_AUTHENTICATION.length()); String storedBaString = getBasicAuthenticationString(); LOGGER.debug("{} equals? {}", baString, storedBaString); if (!baString.equals(storedBaString)) { LOGGER.info("Unauthorized - invalid client credentials"); // Unauthorized (401, "invalid_client") response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else { // Unsupported client authentication method (401, "invalid_client") LOGGER.info("Unauthorized - client authentication method not supported"); response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else if (null != credentials) { // Check JSON LOGGER.debug(String.format("%s: %s, %s", PREFIX_BASIC_AUTHENTICATION, credentials.getClient_id(), credentials.getClient_secret())); if (null == credentials.getClient_id() && null == credentials.getClient_secret()) { // No client authentication included (401, "invalid_client") LOGGER.info("Unauthorized - no client credentials found"); errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } else if (null == credentials.getClient_id() ^ null == credentials.getClient_secret()) { LOGGER.info("Bad request - missing required parameter"); // Missing client authentication parameter (400, "invalid_request") errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST); return; } else if (!isCredentialsValid(credentials.getClient_id(), credentials.getClient_secret())) { LOGGER.info("Unauthorized - invalid client credentials"); // Unauthorized (401, "invalid_client") errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else { // No client authentication included (401, "invalid_client") LOGGER.info("Unauthorized - no client credentials found"); errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } chain.doFilter(request, response); }