List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:nl.tue.iot.reservation.ReservationServlet.java
private WriteResponse writeRequest(Client client, String target, HttpServletRequest req, HttpServletResponse resp) throws IOException { Map<String, String> parameters = new HashMap<String, String>(); String contentType = HttpFields.valueParameters(req.getContentType(), parameters); if ("text/plain".equals(contentType)) { String content = IOUtils.toString(req.getInputStream(), parameters.get("charset")); int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1)); WriteRequest writeRequest = new WriteRequest(Mode.REPLACE, ContentFormat.TEXT, target, LwM2mSingleResource.newStringResource(rscId, content)); return server.send(client, writeRequest, TIMEOUT); } else if ("application/json".equals(contentType)) { String content = IOUtils.toString(req.getInputStream(), parameters.get("charset")); JsonObject jsonObject = gson.fromJson(content, JsonObject.class); String vehicleId = jsonObject.get("value").getAsString(); String action = jsonObject.get("action").getAsString(); // hack to reserve parking spot-------------------------- String content2 = ""; String target2 = ""; String contentColor = ""; String targetColor = ""; if ("reserve".equalsIgnoreCase(action)) { content2 = "{'id':'32801','value':'reserved'}"; int i = target.lastIndexOf('/'); target2 = target.substring(0, i + 1) + "32801"; contentColor = "{'id':'5527','value':'orange'}"; targetColor = "/3341/0/5527"; LwM2mNode node2 = null;/*from w ww .ja v a 2 s. co m*/ LwM2mNode nodeColor = null; try { node2 = gson.fromJson(content2, LwM2mNode.class); nodeColor = gson.fromJson(contentColor, LwM2mNode.class); } catch (JsonSyntaxException e) { throw new IllegalArgumentException("unable to parse json to tlv:" + e.getMessage(), e); } server.send(client, new WriteRequest(Mode.REPLACE, null, targetColor, nodeColor), TIMEOUT); server.send(client, new WriteRequest(Mode.REPLACE, null, target2, node2), TIMEOUT); //get spot info String spotTarget = "/32700"; ReadRequest spotRequest = new ReadRequest(spotTarget); ReadResponse cSpotResponse = server.send(client, spotRequest, TIMEOUT); LwM2mObject spotNode = (LwM2mObject) cSpotResponse.getContent(); LwM2mObjectInstance spotInstance = spotNode.getInstance(0); String spotId = (String) spotInstance.getResource(32800).getValue(); //String spotState = (String) spotInstance.getResource(32801).getValue(); Double billingRate = (Double) spotInstance.getResource(32803).getValue(); //write reservation info to mongodb ReservationDao.writeEventToDatabase(client.getEndpoint(), spotId, vehicleId, billingRate, action); } // hack --------------------- LwM2mNode node = null; try { node = gson.fromJson(content, LwM2mNode.class); } catch (JsonSyntaxException e) { throw new IllegalArgumentException("unable to parse json to tlv:" + e.getMessage(), e); } return server.send(client, new WriteRequest(Mode.REPLACE, null, target, node), TIMEOUT); } else { throw new IllegalArgumentException( "content type " + req.getContentType() + " not supported for write requests"); } }
From source file:com.weitaomi.systemconfig.filter.LoggingFilter.java
private void logRequest(final HttpServletRequest request) { StringBuilder msg = new StringBuilder(); if (request instanceof RequestWrapper) { msg.append("request_id:").append(((RequestWrapper) request).getId()).append(";"); }/*from w ww .java 2 s . c o m*/ msg.append("user_id:").append(request.getHeader("userId")).append(";"); msg.append("from:").append(request.getHeader("from")).append(";"); if (request.getContentType() != null && request.getContentType().contains("application/json")) { RequestWrapper requestWrapper = (RequestWrapper) request; try { String charEncoding = requestWrapper.getCharacterEncoding() != null ? requestWrapper.getCharacterEncoding() : "UTF-8"; msg.append("params:").append(new String(requestWrapper.toByteArray(), charEncoding)).append(";"); } catch (UnsupportedEncodingException e) { logger.warn("Failed to parse request payload", e); } } else { msg.append("params:").append(getPostParamsStr(request)); } // logger.info(msg.toString()); }
From source file:org.artofsolving.jodconverter.sample.web.ConverterServiceServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { WebappContext webappContext = WebappContext.get(getServletContext()); OfficeDocumentConverter converter = webappContext.getDocumentConverter(); DocumentFormatRegistry registry = converter.getFormatRegistry(); String inputMimeType = request.getContentType(); if (inputMimeType == null) { throw new IllegalArgumentException("Content-Type not set in request"); }/*from w w w. j av a2s. c o m*/ DocumentFormat inputFormat = registry.getFormatByMediaType(inputMimeType); if (inputFormat == null) { throw new IllegalArgumentException("unsupported input mime-type: " + inputMimeType); } String outputMimeType = request.getHeader("Accept"); if (outputMimeType == null) { throw new IllegalArgumentException("Accept header not set in request"); } DocumentFormat outputFormat = registry.getFormatByMediaType(outputMimeType); if (outputFormat == null) { throw new IllegalArgumentException("unsupported output mime-type: " + outputMimeType); } response.setContentType(outputFormat.getMediaType()); //response.setContentLength(???); - should cache result in a buffer first // Generate temporary files and convert File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(request.getInputStream(), inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getExtension()); converter.convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new ServletException("conversion failed", ioException); } catch (OfficeException officeException) { throw new ServletException("conversion failed", officeException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } }
From source file:org.alfresco.module.vti.web.actions.VtiBaseAction.java
/** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// www.ja v a2 s .c o m protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VtiFpRequest vtiRequest = new VtiFpRequest(request); VtiFpResponse vtiResponse = new VtiFpResponse(response); if ("application/x-vermeer-urlencoded".equals(request.getContentType()) && request.getContentLength() > 0) { StringBuffer formString = new StringBuffer(); InputStream inputStream = request.getInputStream(); char c = '\n'; do { c = (char) inputStream.read(); formString.append(c); } while (c != '\n'); String encoding = request.getCharacterEncoding(); if (encoding == null || encoding.trim().length() == 0) { encoding = "UTF-8"; } String[] paramValues = formString.toString().split("&"); for (String string : paramValues) { String[] paramValue = string.split("="); String decodedParamName = URLDecoder.decode(paramValue[0], encoding); String decodedParamValue = null; if (paramValue.length > 1) { decodedParamValue = URLDecoder.decode(paramValue[1], encoding); } else { decodedParamValue = new String(); } vtiRequest.setParameter(decodedParamName, decodedParamValue); } } doPost(vtiRequest, vtiResponse); }
From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java
/** * Processes requests for both HTTP// ww w. j a v a2 s. c o m * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); boolean isMultiPart = ServletFileUpload.isMultipartContent(request); log("isMultipartContent: " + isMultiPart); log("Content-Type: " + request.getContentType()); if (isMultiPart) { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); /* * Set the file size limit in bytes. This should be set as an * initialization parameter */ diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB. // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); // Parse the request List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException ex) { log("Could not parse request", ex); } PrintWriter out = response.getWriter(); out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>"); ListIterator li = items.listIterator(); while (li.hasNext()) { FileItem fileItem = (FileItem) li.next(); if (fileItem.isFormField()) { processFormField(fileItem); } else { out.append(processUploadedFile(fileItem)); } } out.print("</body></html>"); out.flush(); out.close(); } }
From source file:com.novartis.pcs.ontology.rest.servlet.OntologiesServlet.java
@Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mediaType = StringUtils.trimToNull(request.getContentType()); String encoding = StringUtils.trimToNull(request.getCharacterEncoding()); String pathInfo = StringUtils.trimToNull(request.getPathInfo()); Curator curator = loadCurator(request); if (mediaType != null && mediaType.indexOf(';') > 0) { mediaType = mediaType.substring(0, mediaType.indexOf(';')); }/*from w w w . jav a 2s . c o m*/ if (!StringUtils.equalsIgnoreCase(mediaType, MEDIA_TYPE_OBO) || !StringUtils.equalsIgnoreCase(encoding, "utf-8")) { log("Failed to import ontology: invalid media type or encoding " + mediaType + ";charset=" + encoding); response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } else if (pathInfo == null || pathInfo.length() <= 1) { log("Failed to import ontology: ontology name not include in path"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else if (curator == null) { log("Failed to import ontology: curator not found in request"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); } else { try { String ontologyName = pathInfo.substring(1); importService.importOntology(ontologyName, request.getInputStream(), curator); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Cache-Control", "public, max-age=0"); } catch (DuplicateEntityException e) { log("Failed to import ontology: duplicate term", e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (InvalidEntityException e) { log("Failed to import ontology: invalid entity", e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (InvalidFormatException e) { log("Failed to import ontology: invalid format", e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } catch (Exception e) { log("Failed to import ontology: system error", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } response.setContentLength(0); }
From source file:org.apache.any23.servlet.Servlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { final WebResponder responder = new WebResponder(this, resp); final boolean report = isReport(req); final boolean annotate = isAnnotated(req); if (req.getContentType() == null) { responder.sendError(400, "Invalid POST request, no Content-Type for the message body specified", report);//w ww . ja v a 2 s. c om return; } final String uri = getInputIRIFromRequest(req); final String format = getFormatFromRequestOrNegotiation(req); if (format == null) { responder.sendError(406, "Client accept header does not include a supported output format", report); return; } final ExtractionParameters eps = getExtractionParameters(req); if ("application/x-www-form-urlencoded".equals(getContentTypeHeader(req))) { if (uri != null) { log("Attempting conversion to '" + format + "' from IRI <" + uri + ">"); responder.runExtraction(createHTTPDocumentSource(responder, uri, report), eps, format, report, annotate); return; } if (req.getParameter("body") == null) { responder.sendError(400, "Invalid POST request, parameter 'uri' or 'body' required", report); return; } String type = null; if (req.getParameter("type") != null && !"".equals(req.getParameter("type"))) { type = req.getParameter("type"); } log("Attempting conversion to '" + format + "' from body parameter"); responder.runExtraction( new StringDocumentSource(req.getParameter("body"), Servlet.DEFAULT_BASE_IRI, type), eps, format, report, annotate); return; } log("Attempting conversion to '" + format + "' from POST body"); responder.runExtraction(new ByteArrayDocumentSource(req.getInputStream(), Servlet.DEFAULT_BASE_IRI, getContentTypeHeader(req)), eps, format, report, annotate); }
From source file:com.tbodt.jswerve.servlet.JSwerveServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getMethod().equals("OPTIONS")) { serviceOptions(req, resp);// w w w . j av a 2 s . c o m return; } HttpMethod method = HttpMethod.valueOf(req.getMethod()); URI uri = extractUri(req); Headers headers = translateHeaders(req); Content content = new Content(IOUtils.toByteArray(req.getInputStream()), req.getContentType()); Request request = new Request(method, uri, headers, content); try { Response response = website.service(request); resp.setStatus(response.getStatus().getCode()); for (Map.Entry<String, String> header : response.getHeaders()) resp.setHeader(header.getKey(), header.getValue()); resp.getOutputStream().write(response.getBody().getData()); } catch (StatusCodeException ex) { resp.setStatus(ex.getStatusCode().getCode()); ex.printStackTrace(resp.getWriter()); } }
From source file:de.eorganization.crawler.server.servlets.JSONImportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w ww . ja v a 2s . c om resp.setContentType("text/plain"); InputStream stream = req.getInputStream(); log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from " + req.getRemoteAddr()); String amiId = req.getHeader("AMI-ID"); log.info("Got AMI ID:" + amiId); String repository = req.getHeader("REPO"); log.info("Got REPO:" + repository); if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) { log.severe("AMI ID and REPO HTTP Header required."); return; } // Gson gson = new Gson(); // log.info("Parsed Gson " + gson.fromJson(new // InputStreamReader(stream), JsonObject.class)); String jsonString = IOUtils.toString(stream); log.info("Got JSON String " + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1)); JSONObject json = new JSONObject(); try { json = new JSONObject(jsonString); log.fine("Parsed Json " + json); log.finer("Json has keys: " + json.names()); } catch (JSONException e) { log.severe("No JSON sent or wrong format."); return; } JSONObject software = json.optJSONObject("software"); if (software != null) { log.finer("Software JSON " + software); JSONArray softwareNames = software.names(); log.finer("Key Array JSON " + softwareNames); for (int i = 0; i < softwareNames.length(); i++) { log.fine("software " + softwareNames.getString(i) + " with version " + software.getJSONObject(softwareNames.getString(i)).getString("version")); Map<String, String> softAttributes = new HashMap<String, String>(); JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names(); for (int j = 0; j < softwareAttributes.length(); j++) softAttributes.put(softwareAttributes.getString(j), software.getJSONObject(softwareNames.getString(i)) .getString(softwareAttributes.getString(j))); Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i), software.getJSONObject(softwareNames.getString(i)).getString("version"), softAttributes); if (soft != null) { log.fine("Saved/restored software " + soft); // soft.getAttributes().putAll(softAttributes); // AmiManager.updateSoftware(soft); // log.fine("Saved object " + soft); } else log.severe("Not able to save software information for given Ami Id " + amiId + "!"); } List<String> names = new ArrayList<String>(); for (int i = 0; i < softwareNames.length(); i++) names.add(softwareNames.getString(i)); AmiManager.updateSoftwareNames(names); log.info("Saved " + softwareNames.length() + " software objects"); } JSONObject languages = json.optJSONObject("languages"); if (languages != null) { log.finer("Languages JSON " + languages); JSONArray languagesNames = languages.names(); log.finer("Key Array JSON " + languagesNames); for (int i = 0; i < languagesNames.length(); i++) { log.fine("languages " + languagesNames.getString(i) + " with version " + languages.getJSONObject(languagesNames.getString(i)).getString("version")); Map<String, String> langAttributes = new HashMap<String, String>(); JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names(); for (int j = 0; j < languageAttributes.length(); j++) langAttributes.put(languageAttributes.getString(j), languages.getJSONObject(languagesNames.getString(i)) .getString(languageAttributes.getString(j))); Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i), languages.getJSONObject(languagesNames.getString(i)).getString("version"), langAttributes); if (lang != null) { log.fine("Saved/restored programming language " + lang); lang.getAttributes().putAll(langAttributes); AmiManager.updateLanguage(lang); log.fine("Saved object " + lang); } else log.severe("Not able to save programming language information for given Ami Id " + amiId + "!"); } log.info("Saved " + languagesNames.length() + " programming language objects"); } resp.getWriter().println( "Saving software packages and programming languages for " + amiId + " (" + repository + ")."); } catch (JSONException e) { log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace()); log.throwing(JSONImportServlet.class.getName(), "doPost", e); e.printStackTrace(); } catch (Exception ex) { log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace()); log.throwing(JSONImportServlet.class.getName(), "doPost", ex); ex.printStackTrace(); } // log.info("returning to referer " + req.getHeader("referer")); // resp.sendRedirect(req.getHeader("referer") != null && // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") : // "localhost:8088"); }
From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java
private RequestContext createRequestContext(final HttpServletRequest req) { return new RequestContext() { public String getCharacterEncoding() { return req.getCharacterEncoding(); }//ww w.j a v a 2 s.c o m public String getContentType() { return req.getContentType(); } public int getContentLength() { return req.getContentLength(); } public InputStream getInputStream() throws IOException { return req.getInputStream(); } }; }