List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java
/** * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse) *///from w w w . j a va 2s.c o m protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { RioStore store = this.getStore(); OslcResource resource = store.getOslcResource(request.getRequestURL().toString()); if (resource == null) { throw new RioServiceException(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 RioServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE); } ServletInputStream content = request.getInputStream(); OslcResource updatedResource = new OslcResource(resource.getUri()); List<RioStatement> 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 (RioServerException e) { throw new RioServiceException(IConstants.SC_BAD, e); } }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private boolean checkMultiUserDeletePreconditions(HttpServletRequest req, HttpServletResponse resp) { if (req.getContentType() == null || !req.getContentType().startsWith("application/x-www-form-urlencoded")) { resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return false; }/*from w ww. j a va 2 s .c o m*/ return true; }
From source file:com.streamsets.pipeline.stage.destination.http.TestHttpClientTarget.java
@Before public void setUp() throws Exception { int port = getFreePort(); server = new Server(port); server.setHandler(new AbstractHandler() { @Override//w w w. j a v a 2 s .c o m public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { serverRequested = true; if (returnErrorResponse) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } compressionType = request.getHeader(HttpConstants.CONTENT_ENCODING_HEADER); InputStream is = request.getInputStream(); if (compressionType != null && compressionType.equals(HttpConstants.SNAPPY_COMPRESSION)) { is = new SnappyFramedInputStream(is, true); } else if (compressionType != null && compressionType.equals(HttpConstants.GZIP_COMPRESSION)) { is = new GZIPInputStream(is); } requestPayload = IOUtils.toString(is); requestContentType = request.getContentType(); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); } }); server.start(); }
From source file:org.springfield.lou.servlet.LouServlet.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*from w w w. j av a 2s. co m*/ protected void doGet(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"); String mt = request.getContentType(); if (mt != null && mt.indexOf("text/put") != -1) { // need to check who made this and why (daniel) doPut(request, response); return; } //System.out.println("REQ="+request.getRequestURI()+" PARAMS="+request.getQueryString()+" MT="+request.getContentType()); String body = request.getRequestURI(); if (request.getParameter("method") != null) { if (request.getParameter("method").equals("post")) { //System.out.println("going for post"); doPost(request, response); return; } } // if proxy request send it to Servicehandler if (body.startsWith("/lou/proxy/")) { ProxyHandler.get("lou", request, response); return; } // need to move to be faster String params = request.getQueryString(); String hostname = request.getHeader("host"); String[] paths = urlMappingPerApplication(hostname, body); //System.out.println("PATHS="+paths+" HOST="+hostname); //System.out.println("LOU REFER="+request.getHeader("Referer")); if (paths != null) { //check if url trigger also contains params String triggerParams = null; if (paths[0].indexOf("?") != -1) { triggerParams = paths[0].substring(paths[0].indexOf("?") + 1); paths[0] = paths[0].substring(0, paths[0].indexOf("?")); } body = paths[0]; if (params != null) { if (triggerParams != null) { params += "&" + triggerParams; } } else { if (triggerParams != null) { params = triggerParams; } } //params = triggerParams; } int pos = body.indexOf("/html5application/"); if (pos != -1) { pos = body.indexOf("/lou/domain/"); if (pos != 0) { // System.out.println("Fixed get="+body); body = body.substring(pos); // System.out.println("Fixed out="+body); } doIndexRequest(body, request, response, params); } else { // should we report something back ? } return; }
From source file:jeeves.server.sources.ServiceRequestFactory.java
/** Builds the request with data supplied by tomcat. * A request is in the form: srv/<language>/<service>[!]<parameters> *///from w w w. ja v a 2 s.c o m public static ServiceRequest create(HttpServletRequest req, HttpServletResponse res, String uploadDir, int maxUploadSize) throws Exception { String url = req.getPathInfo(); // FIXME: if request character encoding is undefined set it to UTF-8 String encoding = req.getCharacterEncoding(); try { // verify that encoding is valid Charset.forName(encoding); } catch (Exception e) { encoding = null; } if (encoding == null) { try { req.setCharacterEncoding(Jeeves.ENCODING); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } } //--- extract basic info HttpServiceRequest srvReq = new HttpServiceRequest(res); srvReq.setDebug(extractDebug(url)); srvReq.setLanguage(extractLanguage(url)); srvReq.setService(extractService(url)); srvReq.setJSONOutput(extractJSONFlag(url)); String ip = req.getRemoteAddr(); String forwardedFor = req.getHeader("x-forwarded-for"); if (forwardedFor != null) ip = forwardedFor; srvReq.setAddress(ip); srvReq.setOutputStream(res.getOutputStream()); //--- discover the input/output methods String accept = req.getHeader("Accept"); if (accept != null) { int soapNDX = accept.indexOf("application/soap+xml"); int xmlNDX = accept.indexOf("application/xml"); int htmlNDX = accept.indexOf("html"); if (soapNDX != -1) srvReq.setOutputMethod(OutputMethod.SOAP); else if (xmlNDX != -1 && htmlNDX == -1) srvReq.setOutputMethod(OutputMethod.XML); } if ("POST".equals(req.getMethod())) { srvReq.setInputMethod(InputMethod.POST); String contType = req.getContentType(); if (contType != null) { if (contType.indexOf("application/soap+xml") != -1) { srvReq.setInputMethod(InputMethod.SOAP); srvReq.setOutputMethod(OutputMethod.SOAP); } else if (contType.indexOf("application/xml") != -1 || contType.indexOf("text/xml") != -1) srvReq.setInputMethod(InputMethod.XML); } } //--- retrieve input parameters InputMethod input = srvReq.getInputMethod(); if ((input == InputMethod.XML) || (input == InputMethod.SOAP)) { if (req.getMethod().equals("GET")) srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize)); else srvReq.setParams(extractXmlParameters(req)); } else { //--- GET or POST srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize)); } srvReq.setHeaders(extractHeaders(req)); return srvReq; }
From source file:info.magnolia.services.httputils.filters.InternalProxyFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String[] requestedUrl = request.getRequestURI().split("/", 4); if (!requestedUrl[1].equals(FILTER_CONTEXT)) throw new ServletException( "Requested url does not have the right context, please check the configuration of the filter."); if (StringUtils.isBlank(requestedUrl[2])) throw new ServletException("Service name is missing."); if (StringUtils.isBlank(requestedUrl[3])) throw new ServletException("No resources specified in the url"); // calculate internal url String service = requestedUrl[2]; String resource = requestedUrl[3]; WebTarget target = null;// w w w. j a v a2 s .co m //this.client.target("http://192.168.99.100:3004/").path(resource); // add query string String queryString = request.getQueryString(); if (StringUtils.isNotBlank(queryString)) target = target.path(queryString); // set content type String contentType = request.getContentType(); Invocation.Builder requestBuilder; if (StringUtils.isNotBlank(contentType)) requestBuilder = target.request(contentType); else requestBuilder = target.request(); // copy the original request body to the internal one StringBuilder internalBodyReq = new StringBuilder(); BufferedReader reader = request.getReader(); try { String line; while ((line = reader.readLine()) != null) { internalBodyReq.append(line); } } finally { reader.close(); } Response internalResp = null; // actually do the call based on the method String method = request.getMethod(); switch (method) { case "GET": internalResp = requestBuilder.get(); break; case "POST": internalResp = requestBuilder.post(Entity.entity(internalBodyReq, contentType)); break; case "PUT": internalResp = requestBuilder.put(Entity.entity(internalBodyReq, contentType)); break; case "DELETE": internalResp = requestBuilder.delete(); break; default: log.error("HTTP method not supported: " + method); break; } response.setStatus(internalResp.getStatus()); response.setContentType(internalResp.getMediaType().toString()); response.getOutputStream().print(internalResp.readEntity(String.class)); }
From source file:at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.SignedDocAttributeRequestProvider.java
public IPersonalAttributeList parse(HttpServletRequest httpReq) throws MOAIDException, UnsupportedAttributeException { Logger.debug("Beginning to extract OASIS-DSS response out of HTTP Request"); try {/* w ww. j ava 2 s .c o m*/ String base64 = httpReq.getParameter("signresponse"); Logger.debug("signresponse url: " + httpReq.getRequestURI().toString()); Logger.debug("signresponse querystring: " + httpReq.getQueryString()); Logger.debug("signresponse method: " + httpReq.getMethod()); Logger.debug("signresponse content type: " + httpReq.getContentType()); Logger.debug("signresponse parameter:" + base64); String signResponseString = new String(Base64.decodeBase64(base64), "UTF8"); Logger.debug("RECEIVED signresponse:" + signResponseString); //create SignResponse object Source response = new StreamSource(new java.io.StringReader(signResponseString)); SignResponse signResponse = ApiUtils.unmarshal(response, SignResponse.class); //Check if Signing was successfully or not if (!signResponse.getResult().getResultMajor().equals(ResultMajor.RESULT_MAJOR_SUCCESS)) { //Pass unmodifed or unmarshal & marshal?? InputStream istr = ApiUtils.marshalToInputStream(signResponse); StringWriter writer = new StringWriter(); IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse with error (unmodified):" + signResponseString); istr.close(); } else { //extract doc from signresponse DataSource dataSource = LightweightSourceResolver.getDataSource(signResponse); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), baos); byte[] data = baos.toByteArray(); baos.close(); //update doc in DTL String docId, dssId = ""; docId = signResponse.getDocUI(); //For reference dssId equals docId dssId = docId; if (dssId != null && data != null) { boolean success = false; try { success = updateDocumentInDtl(data, docId, signResponseString); } catch (Exception e) {//No document service used? Logger.info("No document service used?"); e.printStackTrace(); success = false; } if (success) { // set the url in the SignResponse DocumentWithSignature documentWithSignature = new DocumentWithSignature(); DocumentType value = new DocumentType(); if (dtlUrl.endsWith("?wsdl")) { String tmp = dtlUrl.replace("?wsdl", ""); Logger.debug("DocumentUrl ends with ? wsdl, using " + tmp + " instead."); value.setDocumentURL(tmp); } else { value.setDocumentURL(dtlUrl); } documentWithSignature.setDocument(value); if (signResponse.getOptionalOutputs() != null) { //signResponse.getOptionalOutputs().getAny().add(documentWithSignature); for (Object o : signResponse.getOptionalOutputs().getAny()) { if (o instanceof DocumentWithSignature) { signResponse.getOptionalOutputs().getAny().remove(o); signResponse.getOptionalOutputs().getAny().add(documentWithSignature); break; } } } else { AnyType anytype = new AnyType(); anytype.getAny().add(documentWithSignature); signResponse.setOptionalOutputs(anytype); } // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl); InputStream istr = ApiUtils.marshalToInputStream(signResponse); StringWriter writer = new StringWriter(); IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse overwritten:" + signResponseString); istr.close(); } else { //No document service used? // do nothing.... //TODO temporary fix because document is deleted after fetching => SP can't download Doc //Add doc to Signresponse DocumentWithSignature documentWithSignature = new DocumentWithSignature(); DocumentType value = new DocumentType(); if (signResponse.getProfile().toLowerCase().contains("xades")) { value.setBase64XML(data); } else { Base64Data base64data = new Base64Data(); base64data.setValue(data); base64data.setMimeType(dataSource.getContentType()); value.setBase64Data(base64data); } documentWithSignature.setDocument(value); if (signResponse.getOptionalOutputs() != null) { //signResponse.getOptionalOutputs().getAny().add(documentWithSignature); for (Object o : signResponse.getOptionalOutputs().getAny()) { if (o instanceof DocumentWithSignature) { signResponse.getOptionalOutputs().getAny().remove(o); signResponse.getOptionalOutputs().getAny().add(documentWithSignature); break; } } } else { AnyType anytype = new AnyType(); anytype.getAny().add(documentWithSignature); signResponse.setOptionalOutputs(anytype); } // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl); InputStream istr = ApiUtils.marshalToInputStream(signResponse); StringWriter writer = new StringWriter(); IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse overwritten:" + signResponseString); istr.close(); } } else throw new Exception("No DSS id found."); } //alter signresponse //done List<String> values = new ArrayList<String>(); values.add(signResponseString); Logger.debug("Assembling signedDoc attribute"); PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values, AttributeStatusType.AVAILABLE.value()); // pack and return the result PersonalAttributeList result = new PersonalAttributeList(); result.add(signedDocAttribute); return result; } catch (UnsupportedEncodingException e) { Logger.error("Failed to assemble signedDoc attribute"); throw new MOAIDException("stork.05", null); } catch (ApiUtilsException e) { e.printStackTrace(); Logger.error("Failed to assemble signedDoc attribute"); throw new MOAIDException("stork.05", null); } catch (IOException e) { e.printStackTrace(); Logger.error("Failed to assemble signedDoc attribute"); throw new MOAIDException("stork.05", null); } catch (Exception e) { e.printStackTrace(); Logger.error("Failed to assemble signedDoc attribute"); //throw new MOAIDException("stork.05", null); throw new UnsupportedAttributeException(); } }
From source file:com.google.nigori.server.NigoriServlet.java
/** * Handle initial request from client and dispatch to appropriate handler or return error message. *//*from w w w . j a v a 2 s .c o m*/ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { addCorsHeaders(resp); // Subset of path managed by this servlet; e.g. if URI is "/nigori/get" and servlet path // is "/nigori, then we want to retrieve "get" as the request type int startIndex = req.getServletPath().length() + 1; String requestURI = req.getRequestURI(); if (requestURI.length() <= startIndex) { ServletException s = new ServletException(HttpServletResponse.SC_BAD_REQUEST, "No request type specified.\n" + supportedTypes + "\n"); log.fine(s.toString()); s.writeHttpResponse(resp); return; } String requestType = requestURI.substring(startIndex); String requestMimetype = req.getContentType(); RequestHandlerType handlerType = new RequestHandlerType(requestMimetype, requestType); RequestHandler handler = handlers.get(handlerType); if (handler == null) { throw new ServletException(HttpServletResponse.SC_NOT_ACCEPTABLE, "Unsupported request pair: " + handlerType + "\n" + supportedTypes + "\n"); } try { handler.handle(req, resp); } catch (NotFoundException e) { ServletException s = new ServletException(HttpServletResponse.SC_NOT_FOUND, e.getLocalizedMessage()); log.fine(s.toString()); s.writeHttpResponse(resp); } catch (UnauthorisedException e) { ServletException s = new ServletException(HttpServletResponse.SC_UNAUTHORIZED, "Authorisation failed: " + e.getLocalizedMessage()); log.warning(s.toString()); s.writeHttpResponse(resp); } catch (IOException ioe) { throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error sending data to client"); } catch (MessageLibrary.JsonConversionException jce) { throw new ServletException(HttpServletResponse.SC_BAD_REQUEST, "JSON format error: " + jce.getMessage()); } catch (RuntimeException re) { log.severe(re.toString()); throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, re.toString()); } } catch (ServletException e) { log.severe(e.toString()); e.writeHttpResponse(resp); } }
From source file:org.dspace.app.webui.servlet.admin.CollectionWizardServlet.java
protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { /*/*from www . ja v a2s.c om*/ * For POST, we expect from the form: * * community_id DB ID if it was a 'create a new collection' button press * * OR * * collection_id DB ID of collection we're dealing with stage Stage * we're at (from constants above) */ // First, see if we have a multipart request // (the 'basic info' page which might include 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 processBasicInfo(context, request, response); return; } int communityID = UIUtil.getIntParameter(request, "community_id"); if (communityID > -1) { // We have a community ID, "create new collection" button pressed Community c = Community.find(context, communityID); if (c == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } // Create the collection Collection newCollection = c.createCollection(); request.setAttribute("collection", newCollection); if (AuthorizeManager.isAdmin(context)) { // set a variable to show all buttons request.setAttribute("sysadmin_button", Boolean.TRUE); } try { AuthorizeUtil.authorizeManageAdminGroup(context, newCollection); request.setAttribute("admin_create_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("admin_create_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageSubmittersGroup(context, newCollection); request.setAttribute("submitters_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("submitters_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageWorkflowsGroup(context, newCollection); request.setAttribute("workflows_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("workflows_button", Boolean.FALSE); } try { AuthorizeUtil.authorizeManageTemplateItem(context, newCollection); request.setAttribute("template_button", Boolean.TRUE); } catch (AuthorizeException authex) { request.setAttribute("template_button", Boolean.FALSE); } JSPManager.showJSP(request, response, "/dspace-admin/wizard-questions.jsp"); context.complete(); } else { // Collection already created, dealing with one of the wizard pages int collectionID = UIUtil.getIntParameter(request, "collection_id"); int stage = UIUtil.getIntParameter(request, "stage"); // Get the collection Collection collection = Collection.find(context, collectionID); // Put it in request attributes, as most JSPs will need it request.setAttribute("collection", collection); if (collection == null) { log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); return; } // All pages will need this attribute request.setAttribute("collection.id", String.valueOf(collection.getID())); switch (stage) { case INITIAL_QUESTIONS: processInitialQuestions(context, request, response, collection); break; case PERMISSIONS: processPermissions(context, request, response, collection); break; case DEFAULT_ITEM: processDefaultItem(context, request, response, collection); break; default: log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request))); JSPManager.showIntegrityError(request, response); } } }
From source file:org.jitsi.videobridge.rest.HandlerImpl.java
/** * Modifies a <tt>Conference</tt> with ID <tt>target</tt> in (the * associated) <tt>Videobridge</tt>. * * @param target the ID of the <tt>Conference</tt> to modify in (the * associated) <tt>Videobridge</tt> * @param baseRequest the original unwrapped {@link Request} object * @param request the request either as the {@code Request} object or a * wrapper of that request//from ww w . ja v a 2 s .co m * @param response the response either as the {@code Response} object or a * wrapper of that response * @throws IOException * @throws ServletException */ private void doPatchConferenceJSON(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Videobridge videobridge = getVideobridge(); if (videobridge == null) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { Conference conference = videobridge.getConference(target, null); if (conference == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else if (RESTUtil.isJSONContentType(request.getContentType())) { Object requestJSONObject = null; int status = 0; try { requestJSONObject = new JSONParser().parse(request.getReader()); if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) { status = HttpServletResponse.SC_BAD_REQUEST; } } catch (ParseException pe) { status = HttpServletResponse.SC_BAD_REQUEST; } if (status == 0) { ColibriConferenceIQ requestConferenceIQ = JSONDeserializer .deserializeConference((JSONObject) requestJSONObject); if ((requestConferenceIQ == null) || ((requestConferenceIQ.getID() != null) && !requestConferenceIQ.getID().equals(conference.getID()))) { status = HttpServletResponse.SC_BAD_REQUEST; } else { ColibriConferenceIQ responseConferenceIQ = null; try { IQ responseIQ = videobridge.handleColibriConferenceIQ(requestConferenceIQ, Videobridge.OPTION_ALLOW_NO_FOCUS); if (responseIQ instanceof ColibriConferenceIQ) { responseConferenceIQ = (ColibriConferenceIQ) responseIQ; } else { status = getHttpStatusCodeForResultIq(responseIQ); } } catch (Exception e) { status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } if (status == 0 && responseConferenceIQ != null) { JSONObject responseJSONObject = JSONSerializer .serializeConference(responseConferenceIQ); if (responseJSONObject == null) responseJSONObject = new JSONObject(); response.setStatus(HttpServletResponse.SC_OK); responseJSONObject.writeJSONString(response.getWriter()); } } } if (status != 0) response.setStatus(status); } else { response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); } } }