List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:com.zimbra.cs.service.FileUploadServlet.java
/** * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream} * * @param req/*from w w w.jav a 2s .co m*/ * @param resp * @param fmt * @param acct * @param limitByFileUploadMaxSize * @return * @throws IOException * @throws ServiceException */ List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize) throws IOException, ServiceException { // metadata is encoded in the response's HTTP headers ContentType ctype = new ContentType(req.getContentType()); String contentType = ctype.getContentType(), filename = ctype.getParameter("name"); if (filename == null) { filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); } if (filename == null || filename.trim().equals("")) { mLog.info("Rejecting upload with no name."); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null); return Collections.emptyList(); } // Unescape the filename so it actually displays correctly filename = StringEscapeUtils.unescapeHtml(filename); // store the fetched file as a normal upload ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize); FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename); try { // write the upload to disk, but make sure not to exceed the permitted max upload size long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true, upload.getSizeMax() * 3); if ((upload.getSizeMax() >= 0 /* -1 would mean "no limit" */) && (size > upload.getSizeMax())) { mLog.debug("handlePlainUpload(): deleting %s", fi); fi.delete(); mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId()); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null); return Collections.emptyList(); } } catch (IOException ioe) { mLog.warn("Unable to store upload. Deleting %s", fi, ioe); fi.delete(); drainRequestStream(req); sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null); return Collections.emptyList(); } List<FileItem> items = new ArrayList<FileItem>(1); items.add(fi); Upload up = new Upload(acct.getId(), fi, filename); mLog.info("Received plain: %s", up); synchronized (mPending) { mPending.put(up.uuid, up); } List<Upload> uploads = Arrays.asList(up); sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items); return uploads; }
From source file:org.apache.struts.action.RequestProcessor.java
/** * <p>If this is a multipart request, wrap it with a special wrapper. * Otherwise, return the request unchanged.</p> * * @param request The HttpServletRequest we are processing * @return A wrapped request, if the request is multipart; otherwise the * original request./* w w w . j a va2 s . c o m*/ */ protected HttpServletRequest processMultipart(HttpServletRequest request) { if (!"POST".equalsIgnoreCase(request.getMethod())) { return (request); } String contentType = request.getContentType(); if ((contentType != null) && contentType.startsWith("multipart/form-data")) { return (new MultipartRequestWrapper(request)); } else { return (request); } }
From source file:org.openrdf.http.server.repository.transaction.TransactionController.java
private ModelAndView processModificationOperation(RepositoryConnection conn, Action action, HttpServletRequest request, HttpServletResponse response) throws IOException, HTTPException { ProtocolUtil.logRequestParameters(request); Map<String, Object> model = new HashMap<String, Object>(); String baseURI = request.getParameter(Protocol.BASEURI_PARAM_NAME); if (baseURI == null) { baseURI = ""; }/*from w w w . j a v a2 s. co m*/ try { switch (action) { case ADD: conn.add(request.getInputStream(), baseURI, Rio.getParserFormatForMIMEType(request.getContentType()) .orElseThrow(Rio.unsupportedFormat(request.getContentType()))); break; case DELETE: RDFParser parser = Rio.createParser(Rio.getParserFormatForMIMEType(request.getContentType()) .orElseThrow(Rio.unsupportedFormat(request.getContentType())), conn.getValueFactory()); parser.setRDFHandler(new WildcardRDFRemover(conn)); parser.getParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true); parser.parse(request.getInputStream(), baseURI); break; case UPDATE: return getSparqlUpdateResult(conn, request, response); case COMMIT: conn.commit(); conn.close(); ActiveTransactionRegistry.INSTANCE.deregister(getTransactionID(request)); break; default: logger.warn("transaction modification action '{}' not recognized", action); throw new ClientHTTPException("modification action not recognized: " + action); } model.put(SimpleResponseView.SC_KEY, HttpServletResponse.SC_OK); return new ModelAndView(SimpleResponseView.getInstance(), model); } catch (Exception e) { if (e instanceof ClientHTTPException) { throw (ClientHTTPException) e; } else { throw new ServerHTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Transaction handling error: " + e.getMessage(), e); } } }
From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java
private void dump(HttpServletRequest request, StringBuffer log) throws IOException { String hN;/* w w w. j a v a2 s .c om*/ log.append("-- DUMP HttpServletRequest START").append("\n"); log.append("Method : ").append(request.getMethod()).append("\n"); log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n"); log.append("Scheme : ").append(request.getScheme()).append("\n"); log.append("IsSecure : ").append(request.isSecure()).append("\n"); log.append("Protocol : ").append(request.getProtocol()).append("\n"); log.append("ContextPath : ").append(request.getContextPath()).append("\n"); log.append("PathInfo : ").append(request.getPathInfo()).append("\n"); log.append("QueryString : ").append(request.getQueryString()).append("\n"); log.append("RequestURI : ").append(request.getRequestURI()).append("\n"); log.append("RequestURL : ").append(request.getRequestURL()).append("\n"); log.append("ContentType : ").append(request.getContentType()).append("\n"); log.append("ContentLength : ").append(request.getContentLength()).append("\n"); log.append("CharacterEncoding : ").append(request.getCharacterEncoding()).append("\n"); log.append("---- Headers START\n"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { hN = headerNames.nextElement(); log.append("[" + hN + "]="); Enumeration<String> headers = request.getHeaders(hN); while (headers.hasMoreElements()) { log.append("[" + headers.nextElement() + "]"); } log.append("\n"); } log.append("---- Headers END\n"); log.append("---- Body START\n"); log.append(IOUtils.toString(request.getInputStream(), "UTF-8")).append("\n"); log.append("---- Body END\n"); log.append("-- DUMP HttpServletRequest END \n"); }
From source file:com.att.nsa.cambria.service.impl.EventsServiceImpl.java
/** * @throws missingReqdSetting /*from w ww .j a v a2 s .c o m*/ * */ @Override public void pushEvents(DMaaPContext ctx, final String topic, InputStream msg, final String defaultPartition, final String requestTime) throws ConfigDbException, AccessDeniedException, TopicExistsException, CambriaApiException, IOException, missingReqdSetting, DMaaPAccessDeniedException { // is this user allowed to write to this topic? final NsaApiKey user = DMaaPAuthenticatorImpl.getAuthenticatedUser(ctx); final Topic metatopic = ctx.getConfigReader().getfMetaBroker().getTopic(topic); boolean isAAFTopic = false; // was this host blacklisted? final String remoteAddr = Utils.getRemoteAddress(ctx); if (ctx.getConfigReader().getfIpBlackList().contains(remoteAddr)) { ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN, DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), "Source address [" + remoteAddr + "] is blacklisted. Please contact the cluster management team.", null, Utils.getFormattedDate(new Date()), topic, Utils.getUserApiKey(ctx.getRequest()), ctx.getRequest().getRemoteHost(), null, null); LOG.info(errRes.toString()); throw new CambriaApiException(errRes); } String topicNameStd = null; // topicNameStd= ctx.getConfigReader().getSettings().getString("enforced.topic.name.AAF"); topicNameStd = com.att.ajsc.beans.PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop, "enforced.topic.name.AAF"); String metricTopicname = com.att.ajsc.filemonitor.AJSCPropertiesMap .getProperty(CambriaConstants.msgRtr_prop, "metrics.send.cambria.topic"); if (null == metricTopicname) metricTopicname = "msgrtr.apinode.metrics.dmaap"; boolean topicNameEnforced = false; if (null != topicNameStd && topic.startsWith(topicNameStd)) { topicNameEnforced = true; } //Here check if the user has rights to publish on the topic //( This will be called when no auth is added or when UEB API Key Authentication is used) //checkUserWrite(user) method will throw an error when there is no Auth header added or when the //user has no publish rights if (null != metatopic && null != metatopic.getOwner() && !("".equals(metatopic.getOwner())) && null == ctx.getRequest().getHeader("Authorization") && !topic.equalsIgnoreCase(metricTopicname)) { metatopic.checkUserWrite(user); } // if headers are not provided then user will be null if (topicNameEnforced || (user == null && null != ctx.getRequest().getHeader("Authorization") && !topic.equalsIgnoreCase(metricTopicname))) { // the topic name will be sent by the client // String permission = "com.att.dmaap.mr.topic"+"|"+topic+"|"+"pub"; DMaaPAAFAuthenticator aaf = new DMaaPAAFAuthenticatorImpl(); String permission = aaf.aafPermissionString(topic, "pub"); if (!aaf.aafAuthentication(ctx.getRequest(), permission)) { ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_UNAUTHORIZED, DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(), errorMessages.getNotPermitted1() + " publish " + errorMessages.getNotPermitted2() + topic, null, Utils.getFormattedDate(new Date()), topic, Utils.getUserApiKey(ctx.getRequest()), ctx.getRequest().getRemoteHost(), null, null); LOG.info(errRes.toString()); throw new DMaaPAccessDeniedException(errRes); } isAAFTopic = true; } final HttpServletRequest req = ctx.getRequest(); // check for chunked input boolean chunked = false; if (null != req.getHeader(TRANSFER_ENCODING)) { chunked = req.getHeader(TRANSFER_ENCODING).contains("chunked"); } // get the media type, or set it to a generic value if it wasn't // provided String mediaType = req.getContentType(); if (mediaType == null || mediaType.length() == 0) { mediaType = MimeTypes.kAppGenericBinary; } if (mediaType.contains("charset=UTF-8")) { mediaType = mediaType.replace("; charset=UTF-8", "").trim(); } String istransidUEBtopicreqd = AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop, "transidUEBtopicreqd"); boolean istransidreqd = false; if (null != istransidUEBtopicreqd && istransidUEBtopicreqd.equalsIgnoreCase("true")) { istransidreqd = true; } if (isAAFTopic || istransidreqd) { pushEventsWithTransaction(ctx, msg, topic, defaultPartition, requestTime, chunked, mediaType); } else { pushEvents(ctx, topic, msg, defaultPartition, chunked, mediaType); } }
From source file:org.apache.camel.component.http.CamelServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isTraceEnabled()) { log.trace("Service: " + request); }/*ww w . j a v a 2s . co m*/ // Is there a consumer registered for the request. HttpConsumer consumer = resolve(request); if (consumer == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // are we suspended? if (consumer.isSuspended()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // create exchange and set data on it Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut); if (consumer.getEndpoint().isBridgeEndpoint()) { exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); } if (consumer.getEndpoint().isDisableStreamCache()) { exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE); } HttpHelper.setCharsetFromContentType(request.getContentType(), exchange); exchange.setIn(new HttpMessage(exchange, request, response)); try { if (log.isTraceEnabled()) { log.trace("Processing request for exchangeId: " + exchange.getExchangeId()); } // process the exchange consumer.getProcessor().process(exchange); } catch (Exception e) { exchange.setException(e); } try { if (log.isTraceEnabled()) { log.trace("Writing response for exchangeId: " + exchange.getExchangeId()); } // now lets output to the response consumer.getBinding().writeResponse(exchange, response); } catch (IOException e) { log.error("Error processing request", e); throw e; } catch (Exception e) { log.error("Error processing request", e); throw new ServletException(e); } }
From source file:org.apache.axis2.transport.http.AxisServlet.java
/** * Implementaion of POST interface/*from w ww . j a v a2s.c om*/ * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //set the initial buffer for a larger value response.setBufferSize(BUFFER_SIZE); preprocessRequest(request); MessageContext msgContext; OutputStream out = response.getOutputStream(); String contentType = request.getContentType(); if (!HTTPTransportUtils.isRESTRequest(contentType)) { msgContext = createMessageContext(request, response); msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType); try { // adding ServletContext into msgContext; String url = request.getRequestURL().toString(); OutputStream bufferedOut = new BufferedOutputStream(out); InvocationResponse pi = HTTPTransportUtils.processHTTPPostRequest(msgContext, new BufferedInputStream(request.getInputStream()), bufferedOut, contentType, request.getHeader(HTTPConstants.HEADER_SOAP_ACTION), url); Boolean holdResponse = (Boolean) msgContext.getProperty(RequestResponseTransport.HOLD_RESPONSE); if (pi.equals(InvocationResponse.SUSPEND) || (holdResponse != null && Boolean.TRUE.equals(holdResponse))) { ((RequestResponseTransport) msgContext.getProperty(RequestResponseTransport.TRANSPORT_CONTROL)) .awaitResponse(); } // if data has not been sent back and this is not a signal response if (!TransportUtils.isResponseWritten(msgContext) && (((RequestResponseTransport) msgContext .getProperty(RequestResponseTransport.TRANSPORT_CONTROL)) .getStatus() != RequestResponseTransport.RequestResponseTransportStatus.SIGNALLED)) { response.setStatus(HttpServletResponse.SC_ACCEPTED); // only set contentType in this scenario, not if response already set log.debug("Response not written. Setting response contentType to text/xml; " + "charset=" + msgContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING)); response.setContentType("text/xml; charset=" + msgContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING)); } // Make sure that no data remains in the BufferedOutputStream even if the message // formatter doesn't call flush bufferedOut.flush(); } catch (AxisFault e) { setResponseState(msgContext, response); log.debug(e); if (msgContext != null) { processAxisFault(msgContext, response, out, e); } else { throw new ServletException(e); } } catch (Throwable t) { log.error(t.getMessage(), t); try { // If the fault is not going along the back channel we should be 202ing if (AddressingHelper.isFaultRedirected(msgContext)) { response.setStatus(HttpServletResponse.SC_ACCEPTED); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); AxisBindingOperation axisBindingOperation = (AxisBindingOperation) msgContext .getProperty(Constants.AXIS_BINDING_OPERATION); if (axisBindingOperation != null) { AxisBindingMessage axisBindingMessage = axisBindingOperation .getFault((String) msgContext.getProperty(Constants.FAULT_NAME)); if (axisBindingMessage != null) { Integer code = (Integer) axisBindingMessage .getProperty(WSDL2Constants.ATTR_WHTTP_CODE); if (code != null) { response.setStatus(code.intValue()); } } } } handleFault(msgContext, out, new AxisFault(t.toString(), t)); } catch (AxisFault e2) { log.info(e2); throw new ServletException(e2); } } finally { closeStaxBuilder(msgContext); TransportUtils.deleteAttachments(msgContext); } } else { if (!disableREST) { new RestRequestProcessor(Constants.Configuration.HTTP_METHOD_POST, request, response) .processXMLRequest(); } else { showRestDisabledErrorMessage(response); } } }
From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceService.java
/** * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse) *//*w ww .j a v a 2 s . com*/ protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ShareStore store = this.getStore(); OslcResource resource = store.getOslcResource(request.getRequestURL().toString()); if (resource == null) { throw new ShareServiceException(IConstants.SC_NOT_FOUND); } checkConditionalHeaders(request, resource); // cache the created and creator Date created = resource.getCreated(); String creator = resource.getCreator(); // ok, then we update this resource String contentType = request.getContentType(); if (!contentType.startsWith(IConstants.CT_RDF_XML)) { throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE); } ServletInputStream content = request.getInputStream(); OslcResource updatedResource = new OslcResource(resource.getUri()); List<ShareStatement> statements = store.parse(resource.getUri(), content, contentType); updatedResource.addStatements(statements); updatedResource.setCreated(created); updatedResource.setCreator(creator); String userId = request.getRemoteUser(); String userUri = this.getUserUri(userId); store.update(updatedResource, userUri); updatedResource = store.getOslcResource(resource.getUri()); response.setStatus(IConstants.SC_OK); response.addHeader(IConstants.HDR_ETAG, updatedResource.getETag()); response.addHeader(IConstants.HDR_LOCATION, updatedResource.getUri()); String lastModified = StringUtils.rfc2822(updatedResource.getModified()); response.addHeader(IConstants.HDR_LAST_MODIFIED, lastModified); } catch (ShareServerException e) { throw new ShareServiceException(IConstants.SC_BAD, e); } }
From source file:com.krawler.esp.servlets.importProjectPlanCSV.java
private String doImport(HttpServletRequest request, Connection conn) throws SessionExpiredException, ServiceException, IOException, JSONException { String contentType = request.getContentType(); CsvReader csvReader = null;/*from w ww. j a v a2 s .c om*/ String header = ""; FileInputStream fstream = null; try { if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { String fileid = UUID.randomUUID().toString(); String f1 = uploadDocument(request, fileid); if (f1.length() != 0) { String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "importplans"; File csv = new File(destinationDirectory + StorageHandler.GetFileSeparator() + f1); fstream = new FileInputStream(csv); csvReader = new CsvReader(new InputStreamReader(fstream)); csvReader.readRecord(); int i = 0; while (!(StringUtil.isNullOrEmpty(csvReader.get(i)))) { header += "{\"header\":\"" + csvReader.get(i) + "\",\"index\":" + i + "},"; i++; } header = header.substring(0, header.length() - 1); header = "{\"success\": true,\"FileName\":\"" + f1 + "\",\"Headers\":[" + header + "]}"; String fileName = request.getParameter("realfilename"); String userid = AuthHandler.getUserid(request); String companyid = AuthHandler.getCompanyid(request); String projectid = request.getParameter("projectid"); int c = ImportLogHandler.insertImportLog(conn, fileid, fileName, f1, "CSV", "", "Project plan", userid, companyid, projectid, "", "pm.common.projectplan"); if (c != 1) throw ServiceException.FAILURE("Failed to insert log", new Throwable()); // e.g. Header= "{'Task Name':0,'Start Date':1,'End Date':2,'Proirity':3,'Percent Completed':4,'Notes':5}"; } } } catch (FileNotFoundException ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); } catch (ConfigurationException ex) { KrawlerLog.op.warn("Problem Storing Data In DB [importProjectPlanCSV.storeInDB()]:" + ex); throw ServiceException.FAILURE("importProjectPlanCSV.getfile", ex); } finally { if (csvReader != null) csvReader.close(); if (fstream != null) fstream.close(); } return header; }
From source file:org.wrml.server.WrmlServlet.java
Model readModelFromRequestEntity(final HttpServletRequest request, final Method requestMethod, final URI uri) throws ServletException { if (!requestMethod.isEntityAllowedInRequestMessage()) { LOGGER.debug("This type of request does not carry a payload [{}]", new Object[] { requestMethod }); return null; }// ww w. j a v a 2 s . c o m MediaType requestEntityMediaType = null; if (request.getContentType() != null) { try { requestEntityMediaType = new MediaType(request.getContentType()); } catch (final MediaTypeException ex) { LOGGER.error("Unable to create request media type.", ex); } } final URI requestEntitySchemaUri = getRequestEntitySchemaUri(requestEntityMediaType, requestMethod, uri); final URI requestEntityFormatUri = getRequestFormatUri(requestEntityMediaType); if (requestEntitySchemaUri == null) { LOGGER.debug("The request schema URI is null, returning null"); return null; } Model model = null; InputStream in; try { in = request.getInputStream(); } catch (final Exception e) { throw new ServletException("Failed to read HTTP request content."); } try { model = getContext().readModel(in, uri, requestEntitySchemaUri, requestEntityFormatUri); } catch (final ModelReadingException e) { throw new ServletException("Failed to read model graph from HTTP response input stream (URI = " + request.getRequestURI() + ", Schema = [" + requestEntitySchemaUri + "]).", e); } finally { try { // TODO: Is this the appropriate way to finish with the InputStream? in.close(); } catch (final IOException e) { throw new ServletException("Failed to close model graph input stream.", e); } } return model; }