List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:org.bibsonomy.rest.RestServlet.java
/** * @param request/* w w w . j a v a2 s . c om*/ * the servletrequest * @param response * the servletresponse * @param method * httpMethod to use, see {@link HttpMethod} * @throws IOException */ private void handle(final HttpServletRequest request, final HttpServletResponse response, final HttpMethod method) throws IOException { log.debug("Incoming Request: " + method.name() + " " + request.getRequestURL() + " from IP " + request.getHeader("x-forwarded-for")); final long start = System.currentTimeMillis(); try { // validate the requesting user's authorization final LogicInterface logic = validateAuthorization(request); // parse the request object to retrieve a list with all items of the // http request final MultiPartRequestParser parser = new MultiPartRequestParser(request); // choose rendering format (defaults to xml) final RenderingFormat renderingFormat = RESTUtils.getRenderingFormatForRequest( request.getParameterMap(), request.getHeader(HeaderUtils.HEADER_ACCEPT), request.getContentType()); // create Context final Reader reader = RESTUtils.getInputReaderForStream(request.getInputStream(), REQUEST_ENCODING); final Context context = new Context(method, getPathInfo(request), renderingFormat, this.urlRenderer, reader, parser.getList(), logic, request.getParameterMap(), additionalInfos); // validate request context.canAccess(); // set some response headers final String userAgent = request.getHeader(HeaderUtils.HEADER_USER_AGENT); log.debug("[USER-AGENT] " + userAgent); response.setContentType(context.getContentType(userAgent)); response.setCharacterEncoding(RESPONSE_ENCODING); // send answer if (method.equals(HttpMethod.POST)) { // if a POST request completes successfully this means that a // resource has been created response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setStatus(HttpServletResponse.SC_OK); } // just define an ByteArrayOutputStream to store all outgoing data final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream(); context.perform(cachingStream); /* * XXX: note: cachingStream.size() != * cachingStream.toString().length() !! the correct value is the * first one! */ response.setContentLength(cachingStream.size()); // some more logging log.debug("Size of output sent:" + cachingStream.size()); final long elapsed = System.currentTimeMillis() - start; log.debug("Processing time: " + elapsed + " ms"); cachingStream.writeTo(response.getOutputStream()); } catch (final AuthenticationException e) { log.warn(e.getMessage()); response.setHeader("WWW-Authenticate", "Basic realm=\"" + RestProperties.getInstance().getBasicRealm() + "\""); sendError(request, response, HttpURLConnection.HTTP_UNAUTHORIZED, e.getMessage()); } catch (final InternServerException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (final NoSuchResourceException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } catch (final BadRequestOrResponseException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (final AccessDeniedException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (final ResourceMovedException e) { log.error(e.getMessage()); /* * sending new location TODO: add date using */ response.setHeader("Location", urlRenderer.createHrefForResource(e.getUserName(), e.getNewIntraHash())); sendError(request, response, HttpServletResponse.SC_MOVED_PERMANENTLY, e.getMessage()); } catch (final DatabaseException e) { final StringBuilder returnMessage = new StringBuilder(""); for (final String hash : e.getErrorMessages().keySet()) { for (final ErrorMessage em : e.getErrorMessages(hash)) { log.error(em.toString()); returnMessage.append(em.toString() + "\n "); } } sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, returnMessage.toString()); } catch (final Exception e) { log.error(e, e); // well, lets fetch each and every error... sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.intermine.webservice.server.lists.ListUploadService.java
/** * Get the reader for the identifiers uploaded with this request. * @param request The request object.// w ww. ja v a2 s .c om * @return A buffered reader for reading the identifiers. */ protected BufferedReader getReader(final HttpServletRequest request) { BufferedReader r = null; if (ServletFileUpload.isMultipartContent(request)) { final ServletFileUpload upload = new ServletFileUpload(); try { final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); final String fieldName = item.getFieldName(); if (!item.isFormField() && "identifiers".equalsIgnoreCase(fieldName)) { final InputStream stream = item.openStream(); final InputStreamReader in = new InputStreamReader(stream); r = new BufferedReader(in); break; } } } catch (FileUploadException e) { throw new InternalErrorException("Could not read request body", e); } catch (IOException e) { throw new InternalErrorException(e); } } else { if (!requestIsOfSuitableType()) { throw new BadRequestException("Bad content type - " + request.getContentType() + USAGE); } try { r = request.getReader(); } catch (IOException e) { throw new InternalErrorException(e); } } if (r == null) { throw new BadRequestException("No identifiers found in request." + USAGE); } return r; }
From source file:org.eclipse.rdf4j.http.server.repository.transaction.TransactionController.java
private ModelAndView processModificationOperation(Transaction transaction, 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 ww.ja v a 2 s . co m*/ final Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, SimpleValueFactory.getInstance()); final boolean preserveNodeIds = ProtocolUtil.parseBooleanParam(request, Protocol.PRESERVE_BNODE_ID_PARAM_NAME, false); try { RDFFormat format = null; switch (action) { case ADD: format = Rio.getParserFormatForMIMEType(request.getContentType()) .orElseThrow(Rio.unsupportedFormat(request.getContentType())); transaction.add(request.getInputStream(), baseURI, format, preserveNodeIds, contexts); break; case DELETE: format = Rio.getParserFormatForMIMEType(request.getContentType()) .orElseThrow(Rio.unsupportedFormat(request.getContentType())); transaction.delete(format, request.getInputStream(), baseURI); break; case UPDATE: return getSparqlUpdateResult(transaction, request, response); case COMMIT: transaction.commit(); // If commit fails with an exception, deregister should be skipped so the user // has a chance to do a proper rollback. See #725. ActiveTransactionRegistry.INSTANCE.deregister(transaction); 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:org.springfield.lou.servlet.LouServlet.java
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.addHeader("Access-Control-Allow-Origin", alloworigin); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "Content-Type,Range,If-None-Match,Accept-Ranges"); response.addHeader("Access-Control-Expose-Headers", "Content-Range"); //read the data from the put request //System.out.println("PUT REQ="+request.getRequestURI()); String mt = request.getContentType(); if (mt.equals("application/data")) { handleFileUpload(request);//from w w w . j a v a 2 s .c o m return; } InputStream inst = request.getInputStream(); String data; // reads the data from inputstring to a normal string. java.util.Scanner s = new java.util.Scanner(inst).useDelimiter("\\A"); data = (s.hasNext()) ? s.next() : null; if (data == null) { return; } //System.out.println("DATA="+data); Map<String, String[]> params = request.getParameterMap(); // lets find the correct nlication Html5ApplicationInterface app = null; String url = request.getRequestURI(); int pos = url.indexOf("/domain/"); if (pos != -1) { String tappname = url.substring(pos); app = ApplicationManager.instance().getApplication(tappname); } if (data.indexOf("put(") == 0) { // System.out.println("DO PUT WAS CALLED"); app.putData(data); return; } if (data.indexOf("stop(") == 0) { //System.out.println("RECIEVED STOP FROP CLIENT"); String screenid = data.substring(5, data.length() - 1); app.removeScreen(screenid, null); return; } //build an org.w3c.dom.Document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(data)); Document doc = builder.parse(is); //get the the user information from the xml Element root = (Element) doc.getElementsByTagName("fsxml").item(0); Element screenxml = (Element) root.getElementsByTagName("screen").item(0); String screenId = screenxml.getElementsByTagName("screenId").item(0).getTextContent(); // does this screen already have a id ? //System.out.println("SCREENID="+screenId); if (!screenId.equals("-1") && app.getScreen(screenId) != null) { // ok so we should find it and its attached app Screen screen = app.getScreen(screenId); screen.setSeen(); screen.setParameters(params); //System.out.println("OLD SCREEN = "+screen.getId()); response.setContentType("text/xml; charset=UTF-8"); OutputStream out = response.getOutputStream(); //PrintWriter out = response.getWriter(); String msg = screen.getMsg(); if (msg == null) { // bad bad bad try { synchronized (screen) { //screen.wait(); screen.wait(2 * 1000); // turned into 'highspeed' for testing so 2 seconds instead of 60, also means eddie.js change } } catch (InterruptedException e) { // System.out.println("got interrupt.. getting data"); } msg = screen.getMsg(); //System.out.println("MSG="+msg); if (msg == null) { // simulated a drop connection //System.out.println("SIM DROP"); msg = "set(synctime)=" + new Date().toString(); out.write(msg.getBytes()); out.flush(); out.close(); return; } } long starttime = new Date().getTime(); //System.out.println("data2="+msg); out.write(msg.getBytes()); out.flush(); out.close(); long endtime = new Date().getTime(); PerformanceManager.addNetworkCallTime(endtime - starttime); } else { //System.out.println("lost flow why ? screenId="+screenId+" "+app.getScreen(screenId)); if (!screenId.equals("-1")) { System.out.println("Sending stop"); response.setContentType("text/xml; charset=UTF-8"); OutputStream out = response.getOutputStream(); //PrintWriter out = response.getWriter(); out.write(XMLHelper.createScreenIdFSXML("-1", false).getBytes()); out.flush(); out.close(); } else { //System.out.println("PARAMS="+params); Capabilities caps = getCapabilities(root); // extend this with Location info caps.addCapability("ipnumber", request.getRemoteAddr()); caps.addCapability("servername", request.getServerName()); String ref = request.getHeader("Referer"); //System.out.println("REF="+ref); if (ref != null) { caps.addCapability("referer", ref); } else { caps.addCapability("referer", ""); } Screen screen = app.getNewScreen(caps, params); //System.out.println("PARAMSET="+params); screen.setParameters(params); // see if we need to override the location //String ploc = screen.getParameter("location"); //if (ploc!=null) screen.getLocation().setId(ploc); response.setContentType("text/xml; charset=UTF-8"); OutputStream out = response.getOutputStream(); out.write(XMLHelper.createScreenIdFSXML(screen.getId(), true).getBytes()); out.flush(); out.close(); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return; }
From source file:org.dspace.webmvc.controller.admin.EditCommunitiesController.java
@RequestMapping(method = RequestMethod.POST, params = "submit_upload") protected String uploadFile(@RequestAttribute Context context, ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam("file") CommonsMultipartFile file) throws ServletException, IOException, SQLException, AuthorizeException { // First, see if we have a multipart request (uploading a logo) String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) { // This is a multipart request, so it's a file upload return processUploadLogo(context, model, request, response, file); } //end if/*from w w w.j ava 2 s .com*/ return ""; }
From source file:edu.pitt.servlets.processAddMedia.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*ww w. j a v a 2 s. c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); String userID = (String) session.getAttribute("userID"); String error = "select correct format "; session.setAttribute("error", error); response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Process only if its multipart content // Create a factory for disk-based file items File file; // We might need to play with the file sizes int maxFileSize = 50000 * 1024; int maxMemSize = 50000 * 1024; ServletContext context = this.getServletContext(); // Note that this file path refers to a virtual path // relative to this servlet. The uploads directory // is part of this project. The physical path varies // from the virtual path String filePath = context.getRealPath("/uploads") + "/"; out.println("Physical folder is located at: " + filePath + "<br />"); // Verify the content type String contentType = request.getContentType(); // This is very important - make sure that the web form that // uploads the file is actually set to enctype="multipart/form-data" // An example of upload form for this project is in index.html if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(filePath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); out.println("field name" + fieldName); String fileName = fi.getName(); out.println("file name" + fileName); // file name is present boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // out.println("file size"+ sizeInBytes); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); // out.println("Uploaded Filename: " + filePath + fileName + "<br />"); String savepath = filePath + fileName; // to check correct format is entered or not int dotindex = fileName.indexOf("."); if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) { response.sendRedirect("./pages/addMedia.jsp"); } // receives projectID from listProjects.jsp from edit href link , adding in existing project // corresponding constructor is used if (session.getAttribute("projectID") != null) { Integer projectID = (Integer) session.getAttribute("projectID"); media = new Media(projectID, fileName); } // first time when user enters media for project , this constructor is used else { media = new Media(userID, fileName); } System.out.println("Into the media constructor"); // redirected to listProject response.sendRedirect("./pages/listProject.jsp"); // media constructor // response.redirect(listprojects.jsp); processRequest(request, response); } } } catch (FileUploadException ex) { Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same standard * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are * configuring to send a standard request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the data to be sent via the {@link EntityEnclosingMethod} *//*from w ww . j a v a2s .co m*/ @SuppressWarnings("unchecked") private void handleEntity(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws IOException { // Get the client POST data as a Map Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap(); // Create a List to hold the NameValuePairs to be passed to the PostMethod List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>(); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParamterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue); listNameValuePairs.add(nameValuePair); } } RequestEntity entity = null; String contentType = httpServletRequest.getContentType(); if (contentType != null) { contentType = contentType.toLowerCase(); if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application") || contentType.contains("text")) { String body = IOHelpers.readFully(httpServletRequest.getReader()); entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding()); entityEnclosingMethod.setRequestEntity(entity); } } NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[] {}); if (entity != null) { // TODO add as URL parameters? //postMethodProxyRequest.addParameters(parameters); } else { // Set the proxy request POST data if (entityEnclosingMethod instanceof PostMethod) { ((PostMethod) entityEnclosingMethod).setRequestBody(parameters); } } }
From source file:byps.http.HHttpServlet.java
protected void doPostMessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (log.isDebugEnabled()) log.debug("doPostMessage("); if (log.isDebugEnabled()) log.debug("read message"); String contentType = request.getContentType(); String contentLength = request.getHeader("Content-Length"); if (log.isDebugEnabled()) log.debug("contentType=" + contentType + ", contentLength=" + contentLength); InputStream is = request.getInputStream(); ByteBuffer ibuf = BWire.bufferFromStream(is); if (log.isDebugEnabled()) { log.debug(BBuffer.toDetailString(ibuf)); }/*from www . java2s .c om*/ doMessage(request, response, ibuf); if (log.isDebugEnabled()) log.debug(")doPostMessage"); }