List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:org.geoserver.ows.Dispatcher.java
Request init(Request request) throws ServiceException, IOException { HttpServletRequest httpRequest = request.getHttpRequest(); String reqContentType = httpRequest.getContentType(); //figure out method request.setGet("GET".equalsIgnoreCase(httpRequest.getMethod()) || isForm(reqContentType)); //create the kvp map parseKVP(request);//from w w w . j ava 2 s .com if (!request.isGet()) { // && httpRequest.getInputStream().available() > 0) { //check for a SOAP request, if so we need to unwrap the SOAP stuff if (httpRequest.getContentType() != null && httpRequest.getContentType().startsWith(SOAP_MIME)) { request.setSOAP(true); request.setInput(soapReader(httpRequest)); } else if (reqContentType != null && ServletFileUpload.isMultipartContent(httpRequest)) { // multipart form upload ServletFileUpload up = new ServletFileUpload(); up.setFileItemFactory(new DiskFileItemFactory()); // treat regular form fields as additional kvp parameters Map<String, FileItem> kvpFileItems = new CaseInsensitiveMap(new LinkedHashMap()); try { for (FileItem item : (List<FileItem>) up.parseRequest(httpRequest)) { if (item.isFormField()) { kvpFileItems.put(item.getFieldName(), item); } else { request.setInput(fileItemReader(item)); } } } catch (Exception e) { throw new ServiceException("Error handling multipart/form-data content", e); } // if no file fields were found, look for one named "body" if (request.getInput() == null) { FileItem body = kvpFileItems.get("body"); if (body != null) { request.setInput(fileItemReader(body)); kvpFileItems.remove("body"); } } Map<String, String> kvpItems = new LinkedHashMap(); for (Map.Entry<String, FileItem> e : kvpFileItems.entrySet()) { kvpItems.put(e.getKey(), e.getValue().toString()); } request.setOrAppendKvp(parseKVP(request, kvpFileItems)); } else { //regular XML POST //wrap the input stream in a buffered input stream request.setInput(reader(httpRequest)); } char[] req = new char[xmlPostRequestLogBufferSize]; int read = request.getInput().read(req, 0, xmlPostRequestLogBufferSize); if (logger.isLoggable(Level.FINE)) { if (read == -1) { request.setInput(null); } else if (read < xmlPostRequestLogBufferSize) { logger.fine("Raw XML request: " + new String(req)); } else if (xmlPostRequestLogBufferSize == 0) { // logging disabled --> do nothing } else { logger.fine("Raw XML request starts with: " + new String(req) + "..."); } } if (read == -1) request.setInput(null); else request.getInput().reset(); } // parse the request path into two components. (1) the 'path' which // is the string after the last '/', and the 'context' which is the // string before the last '/' String ctxPath = request.httpRequest.getContextPath(); String reqPath = request.httpRequest.getRequestURI(); reqPath = reqPath.substring(ctxPath.length()); //strip off leading and trailing slashes if (reqPath.startsWith("/")) { reqPath = reqPath.substring(1, reqPath.length()); } if (reqPath.endsWith("/")) { reqPath = reqPath.substring(0, reqPath.length() - 1); } String context = reqPath; String path = null; int index = context.lastIndexOf('/'); if (index != -1) { path = context.substring(index + 1); context = context.substring(0, index); } else { path = reqPath; context = null; } request.setContext(context); request.setPath(path); return fireInitCallback(request); }
From source file:axiom.servlet.AbstractServletClient.java
protected void parseParameters(HttpServletRequest request, RequestTrans reqtrans, String encoding) throws Exception { HashMap parameters = new HashMap(); try {/*from w ww . j a va 2 s . c o m*/ Context cx = Context.enter(); cx.setClassShutter(new ClassShutter() { public boolean visibleToScripts(String fullClassName) { return false; } }); ImporterTopLevel scope = new ImporterTopLevel(cx, true); // Parse any posted parameters in the input stream String contentType; boolean isPost = false, isForm = false, isJson = false, isXml = false; if ("POST".equals(request.getMethod())) { isPost = true; } if (isPost && (contentType = request.getContentType()) != null) { contentType = contentType.split(";")[0]; if ("application/x-www-form-urlencoded".equals(contentType)) { isForm = true; } else if ("text/json".equals(contentType)) { isJson = true; } else if ("text/xml".equals(contentType)) { isXml = true; } } // Parse any query string parameters from the request String queryString = request.getQueryString(); if (queryString != null) { try { parseParameters(parameters, queryString.getBytes(), encoding, isPost); Scriptable sqparam = cx.newObject(scope); for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); String[] values = (String[]) entry.getValue(); if ((values != null) && (values.length > 0)) { if (values.length == 1) { sqparam.put(key, sqparam, values[0]); } else { NativeArray na = new NativeArray(values); ScriptRuntime.setObjectProtoAndParent(na, scope); sqparam.put(key, sqparam, na); } } } reqtrans.setQueryParams(sqparam); } catch (Exception e) { System.err.println("Error parsing query string: " + e); } } if (isForm || isJson || isXml) { try { int max = request.getContentLength(); int len = 0; byte[] buf = new byte[max]; ServletInputStream is = request.getInputStream(); while (len < max) { int next = is.read(buf, len, max - len); if (next < 0) { break; } len += next; } if (isForm) { HashMap formMap = new HashMap(); parseParameters(formMap, buf, encoding, isPost); Scriptable spparam = cx.newObject(scope); for (Iterator i = formMap.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); String[] values = (String[]) entry.getValue(); if (values.length > 0) { if (values.length == 1) { spparam.put(key, spparam, values[0]); } else { NativeArray na = new NativeArray(values); ScriptRuntime.setObjectProtoAndParent(na, scope); spparam.put(key, spparam, na); } } } reqtrans.setPostBody(new String(buf, encoding)); reqtrans.setPostParams(spparam); parameters.putAll(formMap); } else if (isJson) { String json = new String(buf, encoding); Scriptable post = (Scriptable) cx.evaluateString(scope, "eval(" + json + ")", "", 0, null); reqtrans.setPostBody(post); Object[] ids = post.getIds(); int idslen = ids.length; for (int i = 0; i < idslen; i++) { parameters.put(ids[i], post.get((String) ids[i], post)); } } else if (isXml) { String xml = new String(buf, encoding); int startProlog = xml.indexOf("<?xml version="), endProlog; if (startProlog > -1 && (endProlog = xml.indexOf(">", startProlog + 1)) > -1) { xml = new StringBuffer(xml).replace(startProlog, endProlog + 1, "").toString(); } xml = xml.replaceAll("\\\"", "\\\\\"").replaceAll("\n", "").replaceAll("\r", ""); Scriptable post = (Scriptable) cx.evaluateString(scope, "new XML(\"" + xml + "\");", "", 0, null); reqtrans.setPostBody(post); } } catch (Exception e) { throw e; } } Scriptable sreqdata = cx.newObject(scope); for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); Object val = entry.getValue(); if (val != null) { if (val instanceof String[]) { String[] values = (String[]) val; if (values.length > 0) { if (values.length == 1) { sreqdata.put(key, sreqdata, values[0]); } else { NativeArray na = new NativeArray(values); ScriptRuntime.setObjectProtoAndParent(na, scope); sreqdata.put(key, sreqdata, na); } } } else { sreqdata.put(key, sreqdata, val); } } } reqtrans.setData(sreqdata); } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { Context.exit(); } }
From source file:org.apache.axis2.builder.MultipartFormDataBuilder.java
/** * @return Returns the document element. *//*from ww w.ja v a2s. c o m*/ public OMElement processDocument(InputStream inputStream, String contentType, MessageContext messageContext) throws AxisFault { MultipleEntryHashMap parameterMap; HttpServletRequest request = (HttpServletRequest) messageContext .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); // TODO: Do check ContentLength for the max size, // but it can't be configured anywhere. // I think that it cant be configured at web.xml or axis2.xml. /** * When we are building a request context without the use of Servlets, we require charset encoding and content length * parameters to be set in the transports. */ String charSetEncoding = (String) messageContext .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING); Integer contentLength = 0; Map<String, String> transportHeaders = (Map) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS); String contentLengthValue = (String) transportHeaders.get(HTTPConstants.HEADER_CONTENT_LENGTH); if (contentLengthValue != null) { try { contentLength = new Integer(contentLengthValue); } catch (NumberFormatException e) { // TODO handle this better in case we cannot find the contentLength } } RequestContextImpl nRequest; if (request == null) { // on regular transport if (charSetEncoding == null || contentLength == null) { throw new AxisFault( "multipart/form-data builder could not find charset encoding or content length in messageContext TRANSPORT_HEADERS. Please set these in the respective transport in use."); } nRequest = new RequestContextImpl(inputStream, contentType, charSetEncoding, contentLength); } else { // from servlet transport nRequest = new RequestContextImpl(inputStream, request.getContentType(), request.getCharacterEncoding(), request.getContentLength()); } try { parameterMap = getParameterMap(nRequest, charSetEncoding); return BuilderUtil.buildsoapMessage(messageContext, parameterMap, OMAbstractFactory.getSOAP12Factory()); } catch (FileUploadException e) { throw AxisFault.makeFault(e); } }
From source file:org.openecomp.sdcrests.action.rest.services.ActionsImpl.java
private Response uploadArtifactInternal(String actionInvariantUuId, String artifactName, String artifactLabel, String artifactCategory, String artifactDescription, String artifactProtection, String checksum, Attachment artifactToUpload, HttpServletRequest servletRequest) { ListResponseWrapper responseList = null; byte[] payload = null; Map<String, String> errorMap = validateRequestHeaders(servletRequest); //Artifact name empty validation if (StringUtils.isEmpty(artifactName)) { errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_NAME); } else {//from ww w . ja va 2s. c o m //Artifact name syntax check for whitespaces and invalid characters if (artifactName.matches(invalidFilenameRegex)) { errorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_ARTIFACT_INVALID_NAME); } } //Content-Type Header Validation String contentType = servletRequest.getContentType(); if (StringUtils.isEmpty(contentType)) { errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID); } if (artifactToUpload == null) { throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_FILE); } InputStream artifactInputStream = null; try { artifactInputStream = artifactToUpload.getDataHandler().getInputStream(); } catch (IOException e) { throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR); } payload = FileUtils.toByteArray(artifactInputStream); //Validate Artifact size if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) { throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR); } //Validate Checksum if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) { errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR); } //Validate artifact protection values if (StringUtils.isEmpty(artifactProtection)) artifactProtection = ActionArtifactProtection.readWrite.name(); if (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) && !artifactProtection.equals(ActionArtifactProtection.readWrite.name())) { errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE); } ActionArtifact uploadedArtifact = new ActionArtifact(); if (errorMap.isEmpty()) { String user = servletRequest.getRemoteUser(); ActionArtifact upload = new ActionArtifact(); upload.setArtifactName(artifactName); upload.setArtifactLabel(artifactLabel); upload.setArtifactDescription(artifactDescription); upload.setArtifact(payload); upload.setArtifactCategory(artifactCategory); upload.setArtifactProtection(artifactProtection); uploadedArtifact = actionManager.uploadArtifact(upload, actionInvariantUuId, user); } else { checkAndThrowError(errorMap); } return Response.ok(uploadedArtifact).build(); }
From source file:com.bigdata.rdf.sail.webapp.UpdateServlet.java
/** * Delete all statements materialized by a DESCRIBE or CONSTRUCT query and * then insert all statements in the request body. * <p>/*from w ww . ja v a 2s.c o m*/ * Note: To avoid materializing the statements, this runs the query against * the last commit time and uses a pipe to connect the query directly to the * process deleting the statements. This is done while it is holding the * unisolated connection which prevents concurrent modifications. Therefore * the entire <code>SELECT + DELETE</code> operation is ACID. */ private void doUpdateWithQuery(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final String baseURI = req.getRequestURL().toString(); final String namespace = getNamespace(req); final String queryStr = req.getParameter(QueryServlet.ATTR_QUERY); final boolean suppressTruthMaintenance = getBooleanValue(req, QueryServlet.ATTR_TRUTH_MAINTENANCE, false); if (queryStr == null) buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "Required parameter not found: " + QueryServlet.ATTR_QUERY); final Map<String, Value> bindings = parseBindings(req, resp); if (bindings == null) { // invalid bindings definition generated error response 400 while parsing return; } final String contentType = req.getContentType(); if (log.isInfoEnabled()) log.info("Request body: " + contentType); /** * <a href="https://sourceforge.net/apps/trac/bigdata/ticket/620"> * UpdateServlet fails to parse MIMEType when doing conneg. </a> */ final RDFFormat requestBodyFormat = RDFFormat.forMIMEType(new MiniMime(contentType).getMimeType()); if (requestBodyFormat == null) { buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "Content-Type not recognized as RDF: " + contentType); return; } final RDFParserFactory rdfParserFactory = RDFParserRegistry.getInstance().get(requestBodyFormat); if (rdfParserFactory == null) { buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, "Parser factory not found: Content-Type=" + contentType + ", format=" + requestBodyFormat); return; } /* * Allow the caller to specify the default context for insert. */ final Resource[] defaultContextInsert; { final String[] s = req.getParameterValues("context-uri-insert"); if (s != null && s.length > 0) { try { defaultContextInsert = toURIs(s); } catch (IllegalArgumentException ex) { buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, ex.getLocalizedMessage()); return; } } else { defaultContextInsert = null; } } /* * Allow the caller to specify the default context for delete. */ final Resource[] defaultContextDelete; { final String[] s = req.getParameterValues("context-uri-delete"); if (s != null && s.length > 0) { try { defaultContextDelete = toURIs(s); } catch (IllegalArgumentException ex) { buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN, ex.getLocalizedMessage()); return; } } else { defaultContextDelete = null; } } try { if (getIndexManager().isGroupCommit()) { // compatible with group commit serializability semantics. submitApiTask(new UpdateWithQueryMaterializedTask(req, resp, namespace, ITx.UNISOLATED, // queryStr, // baseURI, // suppressTruthMaintenance, // bindings, // rdfParserFactory, // defaultContextDelete, // defaultContextInsert// )).get(); } else { // streaming implementation. not compatible with group commit. submitApiTask(new UpdateWithQueryStreamingTask(req, resp, namespace, ITx.UNISOLATED, // queryStr, // baseURI, // suppressTruthMaintenance, // bindings, // rdfParserFactory, // defaultContextDelete, // defaultContextInsert// )).get(); } } catch (Throwable t) { launderThrowable(t, resp, "UPDATE-WITH-QUERY" + ": queryStr=" + queryStr + ", baseURI=" + baseURI + (defaultContextInsert == null ? "" : ",context-uri-insert=" + Arrays.toString(defaultContextInsert)) + (defaultContextDelete == null ? "" : ",context-uri-delete=" + Arrays.toString(defaultContextDelete))); } }
From source file:org.deegree.services.controller.OGCFrontController.java
/** * Handles HTTP POST requests./* www . j a v a 2 s.c o m*/ * <p> * An HTTP POST request specifies parameters in the request body. OGC service specifications use three different * ways to encode the parameters: * <ul> * <li><b>KVP</b>: Parameters are given as <code>key=value</code> pairs which are separated using the & * character. This is equivalent to standard HTTP GET requests, except that the parameters are not part of the query * string, but the POST body. In this case, the <code>content-type</code> field in the header must be * <code>application/x-www-form-urlencoded</code>.</li> * <li><b>XML</b>: The POST body contains an XML document. In this case, the <code>content-type</code> field in the * header has to be <code>text/xml</code>, but the implementation does not rely on this in order to be more tolerant * to clients.</li> * <li><b>SOAP</b>: TODO</li> * <li><b>Multipart</b>: TODO</li> * </ul> */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpResponseBuffer responseBuffer = createHttpResponseBuffer(request, response); try { logHeaders(request); addHeaders(responseBuffer); responseBuffer = handleCompression(responseBuffer); LOG.debug("doPost(), contentType: '" + request.getContentType() + "'"); long entryTime = System.currentTimeMillis(); try { // check if content-type implies that it's a KVP request String contentType = request.getContentType(); boolean isKVP = false; if (contentType != null) { isKVP = request.getContentType().startsWith("application/x-www-form-urlencoded"); } List<FileItem> multiParts = checkAndRetrieveMultiparts(request); InputStream is = request.getInputStream(); if (isKVP) { String queryString = readPostBodyAsString(is); LOG.debug("Treating POST input stream as KVP parameters. Raw input: '" + queryString + "'."); Map<String, String> normalizedKVPParams = null; String encoding = request.getCharacterEncoding(); if (encoding == null) { LOG.debug("Request has no further encoding information. Defaulting to '" + DEFAULT_ENCODING + "'."); normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, DEFAULT_ENCODING); } else { LOG.debug("Client encoding information :" + encoding); normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, encoding); } dispatchKVPRequest(normalizedKVPParams, request, responseBuffer, multiParts, entryTime); } else { // if( handle multiparts, get first body from multipart (?) // body->requestDoc InputStream requestInputStream = null; if (multiParts != null && multiParts.size() > 0) { for (int i = 0; i < multiParts.size() && requestInputStream == null; ++i) { FileItem item = multiParts.get(i); if (item != null) { LOG.debug("Using multipart item: " + i + " with contenttype: " + item.getContentType() + " as the request."); requestInputStream = item.getInputStream(); } } } else { requestInputStream = is; } if (requestInputStream == null) { String msg = "Could not create a valid inputstream from request " + ((multiParts != null && multiParts.size() > 0) ? "without" : "with") + " multiparts."; LOG.error(msg); throw new IOException(msg); } String dummySystemId = "HTTP Post request from " + request.getRemoteAddr() + ":" + request.getRemotePort(); XMLStreamReader xmlStream = XMLInputFactoryUtils.newSafeInstance() .createXMLStreamReader(dummySystemId, requestInputStream); // skip to start tag of root element XMLStreamUtils.nextElement(xmlStream); if (isSOAPRequest(xmlStream)) { dispatchSOAPRequest(xmlStream, request, responseBuffer, multiParts); } else { dispatchXMLRequest(xmlStream, request, responseBuffer, multiParts); } } } catch (Throwable e) { LOG.debug("Handling HTTP-POST request took: " + (System.currentTimeMillis() - entryTime) + " ms before sending exception."); LOG.debug(e.getMessage(), e); OWSException ex = new OWSException(e.getLocalizedMessage(), "InvalidRequest"); OWS ows = null; try { ows = determineOWSByPath(request); } catch (OWSException e2) { sendException(ows, e2, responseBuffer, null); return; } sendException(ows, ex, responseBuffer, null); } LOG.debug("Handling HTTP-POST request with status 'success' took: " + (System.currentTimeMillis() - entryTime) + " ms."); } finally { instance.CONTEXT.remove(); responseBuffer.flushBuffer(); if (mainConfig.isValidateResponses() != null && mainConfig.isValidateResponses()) { validateResponse(responseBuffer); } } }
From source file:neu.edu.lab08.HomeController.java
@RequestMapping(value = "/createpatient", method = RequestMethod.POST) public String createpatient(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { // String name = request.getParameter("name"); // String gender = (request.getParameter("gender")); // String dob = request.getParameter("dob"); // String insurance= request.getParameter("insurance"); // Integer amount = Integer.parseInt(request.getParameter("amount")); HttpSession session = request.getSession(); String username = (String) session.getAttribute("username"); String name = (String) session.getAttribute("name"); String gender = (String) session.getAttribute("gender"); String dob = (String) session.getAttribute("dob"); String insurance = (String) session.getAttribute("insurance"); Integer amount = (Integer) session.getAttribute("amount"); Session hibernateSession = HibernateUtil.getSessionFactory().openSession(); hibernateSession.beginTransaction(); String fileName = null;/*from w ww . j ava 2s . c o m*/ File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = "/Users/mengqingwang/Downloads/lab08/src/main/webapp/resources/picture"; // ? String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(maxMemSize); // ? maxMemSize. factory.setRepository(new File("c:\\temp")); // ?? ServletFileUpload upload = new ServletFileUpload(factory); // ? upload.setSizeMax(maxFileSize); try { // ?? List fileItems = upload.parseRequest(request); // ? Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // ?? String fieldName = fi.getFieldName(); fileName = fi.getName(); //String fileNamePath = "\\images\\"+fileName; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // 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); } } } catch (Exception ex) { System.out.println(ex); } if (insurance.equals("Insured")) { InsuredPatient ip = new InsuredPatient(); ip.setName(name); ip.setGender(gender); ip.setDob(dob); ip.setPatienttype(insurance); ip.setPicture(fileName); ip.setHospital(username); ip.setInsuredamount(amount); ip.setStatus(1); hibernateSession.save(ip); hibernateSession.getTransaction().commit(); } else if (insurance.equals("Uninsured")) { UninsuredPatient up = new UninsuredPatient(); up.setName(name); up.setGender(gender); up.setDob(dob); up.setPatienttype(insurance); up.setPicture(fileName); up.setHospital(username); up.setAccount(amount); up.setStatus(1); hibernateSession.save(up); hibernateSession.getTransaction().commit(); } } return "hospitalMenu"; }
From source file:org.apache.hadoop.test.mock.MockRequestMatcher.java
public void match(HttpServletRequest request) throws IOException { if (methods != null) { assertThat(/*from ww w.j a va 2s .co m*/ "Request " + request.getMethod() + " " + request.getRequestURL() + " is not using one of the expected HTTP methods", methods, hasItem(request.getMethod())); } if (pathInfo != null) { assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " does not have the expected pathInfo", request.getPathInfo(), is(pathInfo)); } if (requestURL != null) { assertThat( "Request " + request.getMethod() + " " + request.getRequestURL() + " does not have the expected requestURL", request.getRequestURL().toString(), is(requestURL)); } if (headers != null) { for (String name : headers.keySet()) { assertThat( "Request " + request.getMethod() + " " + request.getRequestURL() + " does not have the expected value for header " + name, request.getHeader(name), is(headers.get(name))); } } if (cookies != null) { List<Cookie> requestCookies = Arrays.asList(request.getCookies()); for (Cookie cookie : cookies) { assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " does not have the expected cookie " + cookie, requestCookies, hasItem(cookie)); } } if (contentType != null) { String[] requestContentType = request.getContentType().split(";", 2); assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " does not have the expected content type", requestContentType[0], is(contentType)); } if (characterEncoding != null) { assertThat( "Request " + request.getMethod() + " " + request.getRequestURL() + " does not have the expected character encoding", request.getCharacterEncoding(), equalToIgnoringCase(characterEncoding)); } if (contentLength != null) { assertThat( "Request " + request.getMethod() + " " + request.getRequestURL() + " does not have the expected content length", request.getContentLength(), is(contentLength)); } if (attributes != null) { for (String name : attributes.keySet()) { assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " is missing attribute '" + name + "'", request.getAttribute(name), notNullValue()); assertThat( "Request " + request.getMethod() + " " + request.getRequestURL() + " has wrong value for attribute '" + name + "'", request.getAttribute(name), is(request.getAttribute(name))); } } // Note: Cannot use any of the expect.getParameter*() methods because they will read the // body and we don't want that to happen. if (queryParams != null) { String queryString = request.getQueryString(); Map<String, String[]> requestParams = parseQueryString(queryString == null ? "" : queryString); for (String name : queryParams.keySet()) { String[] values = requestParams.get(name); assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " query string " + queryString + " is missing parameter '" + name + "'", values, notNullValue()); assertThat( "Request " + request.getMethod() + " " + request.getRequestURL() + " query string " + queryString + " is missing a value for parameter '" + name + "'", Arrays.asList(values), hasItem(queryParams.get(name))); } } if (formParams != null) { String paramString = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding()); Map<String, String[]> requestParams = parseQueryString(paramString == null ? "" : paramString); for (String name : formParams.keySet()) { String[] actualValues = requestParams.get(name); assertThat( "Request " + request.getMethod() + " " + request.getRequestURL() + " form params " + paramString + " is missing parameter '" + name + "'", actualValues, notNullValue()); String[] expectedValues = formParams.get(name); for (String expectedValue : expectedValues) { assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " form params " + paramString + " is missing a value " + expectedValue + " for parameter '" + name + "'", Arrays.asList(actualValues), hasItem(expectedValue)); } } } if (entity != null) { if (contentType != null && contentType.endsWith("/xml")) { String expectEncoding = characterEncoding; String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding)); String actualEncoding = request.getCharacterEncoding(); String actual = IOUtils.toString(request.getInputStream(), actualEncoding == null ? UTF8.name() : actualEncoding); assertThat(the(actual), isEquivalentTo(the(expect))); } else if (contentType != null && contentType.endsWith("/json")) { String expectEncoding = characterEncoding; String expect = new String(entity, (expectEncoding == null ? UTF8.name() : expectEncoding)); String actualEncoding = request.getCharacterEncoding(); String actual = IOUtils.toString(request.getInputStream(), actualEncoding == null ? UTF8.name() : actualEncoding); // System.out.println( "EXPECT=" + expect ); // System.out.println( "ACTUAL=" + actual ); assertThat(actual, sameJSONAs(expect)); } else if (characterEncoding == null || request.getCharacterEncoding() == null) { byte[] bytes = IOUtils.toByteArray(request.getInputStream()); assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " content does not match the expected content", bytes, is(entity)); } else { String expect = new String(entity, characterEncoding); String actual = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding()); assertThat("Request " + request.getMethod() + " " + request.getRequestURL() + " content does not match the expected content", actual, is(expect)); } } }
From source file:nl.nn.adapterframework.pipes.StreamPipe.java
@Override public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException { Object result = input;/* w ww . jav a2 s . com*/ String inputString; if (input instanceof String) { inputString = (String) input; } else { inputString = ""; } ParameterResolutionContext prc = new ParameterResolutionContext(inputString, session, isNamespaceAware()); Map parameters = null; ParameterList parameterList = getParameterList(); if (parameterList != null) { try { parameters = prc.getValueMap(parameterList); } catch (ParameterException e) { throw new PipeRunException(this, "Could not resolve parameters", e); } } InputStream inputStream = null; OutputStream outputStream = null; HttpServletRequest httpRequest = null; HttpServletResponse httpResponse = null; String contentType = null; String contentDisposition = null; if (parameters != null) { if (parameters.get("inputStream") != null) { inputStream = (InputStream) parameters.get("inputStream"); } if (parameters.get("outputStream") != null) { outputStream = (OutputStream) parameters.get("outputStream"); } if (parameters.get("httpRequest") != null) { httpRequest = (HttpServletRequest) parameters.get("httpRequest"); } if (parameters.get("httpResponse") != null) { httpResponse = (HttpServletResponse) parameters.get("httpResponse"); } if (parameters.get("contentType") != null) { contentType = (String) parameters.get("contentType"); } if (parameters.get("contentDisposition") != null) { contentDisposition = (String) parameters.get("contentDisposition"); } } if (inputStream == null) { if (input instanceof InputStream) { inputStream = (InputStream) input; } } try { if (httpResponse != null) { HttpSender.streamResponseBody(inputStream, contentType, contentDisposition, httpResponse, log, getLogPrefix(session)); } else if (httpRequest != null) { StringBuilder partsString = new StringBuilder("<parts>"); String firstStringPart = null; if (ServletFileUpload.isMultipartContent(httpRequest)) { log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] contains multipart content"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(httpRequest); int fileCounter = 0, stringCounter = 0; log.debug(getLogPrefix(session) + "multipart request items size [" + items.size() + "]"); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input // type="text|radio|checkbox|etc", select, etc). String fieldValue = item.getString(); if (isExtractFirstStringPart() && firstStringPart == null) { log.debug(getLogPrefix(session) + "extracting first string part [" + fieldValue + "]"); firstStringPart = fieldValue; } else { String fieldName = "part_string" + (++stringCounter > 1 ? stringCounter : ""); log.debug(getLogPrefix(session) + "setting parameter [" + fieldName + "] to [" + fieldValue + "]"); session.put(fieldName, fieldValue); partsString.append("<part type=\"string\" sessionKey=\"" + fieldName + "\" size=\"" + fieldValue.length() + "\"/>"); } } else { // Process form file field (input type="file"). String fieldName = "part_file" + (++fileCounter > 1 ? fileCounter : ""); String fileName = FilenameUtils.getName(item.getName()); InputStream is = item.getInputStream(); int size = is.available(); String mimeType = item.getContentType(); if (size > 0) { log.debug(getLogPrefix(session) + "setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]"); session.put(fieldName, is); } else { log.debug(getLogPrefix(session) + "setting parameter [" + fieldName + "] to [" + null + "]"); session.put(fieldName, null); } partsString.append("<part type=\"file\" name=\"" + fileName + "\" sessionKey=\"" + fieldName + "\" size=\"" + size + "\" mimeType=\"" + mimeType + "\"/>"); } } } else { log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] does NOT contain multipart content"); } partsString.append("</parts>"); if (isExtractFirstStringPart()) { result = adjustFirstStringPart(firstStringPart, session); session.put(getMultipartXmlSessionKey(), partsString.toString()); } else { result = partsString.toString(); } } else { Misc.streamToStream(inputStream, outputStream); } } catch (IOException e) { throw new PipeRunException(this, "IOException streaming input to output", e); } catch (FileUploadException e) { throw new PipeRunException(this, "FileUploadException getting multiparts from httpServletRequest", e); } return new PipeRunResult(getForward(), result); }
From source file:fsi_admin.admon.JAyudaPaginaDlg.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doPost(request, response); String ayuda_pagina_dlg = ""; request.setAttribute("ayuda_pagina_dlg", ayuda_pagina_dlg); String mensaje = ""; short idmensaje = -1; if (request.getContentType() != null && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) { if (!getSesion(request).getRegistrado()) { irApag("/forsetiadmin/errorAtributos.jsp", request, response); return; } else {/*ww w .j a va2s . c o m*/ if (!getSesion(request).getPermiso("ADMIN_AYUDA_CREAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_CREAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_CREAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } String proceso = "SUBIR_AYUDA"; request.setAttribute("proceso", proceso); SubirImagenAyuda(request, response); return; } } if (request.getParameter("proceso") != null && !request.getParameter("proceso").equals("")) { if (request.getParameter("proceso").equals("AGREGAR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_CREAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_CREAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_CREAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } // Solicitud de envio a procesar if (request.getParameter("subproceso") != null && request.getParameter("subproceso").equals("ENVIAR")) { // Verificacion if (VerificarParametros(request, response)) { Agregar(request, response); return; } irApag("/forsetiadmin/administracion/ayuda_pagina_dlg.jsp", request, response); return; } else // Como el subproceso no es ENVIAR, abre la ventana del proceso de AGREGADO para agregar `por primera vez { getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/administracion/ayuda_pagina_dlg.jsp", request, response); return; } } else if (request.getParameter("proceso").equals("SUBIR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_CREAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_CREAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_CREAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/administracion/ayuda_pagina_dlg_subir.jsp", request, response); return; } else if (request.getParameter("proceso").equals("EDITAR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_CAMBIAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_CAMBIAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_CAMBIAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } // Solicitud de envio a procesar if (request.getParameter("id") != null) { String[] valoresParam = request.getParameterValues("id"); if (valoresParam.length == 1) { if (request.getParameter("subproceso") != null && request.getParameter("subproceso").equals("ENVIAR")) { // Verificacion if (VerificarParametrosEdicion(request, response)) { Editar(request, response); return; } irApag("/forsetiadmin/administracion/ayuda_pagina_dlg_editar.jsp", request, response); return; } else // Como el subproceso no es ENVIAR, abre la ventana del proceso de CAMBIADO para cargar el cambio { getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/administracion/ayuda_pagina_dlg_editar.jsp", request, response); return; } } else { idmensaje = 1; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2); //"PRECAUCION: Solo se permite editar una pgina a la vez <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else { idmensaje = 3; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1); //" ERROR: Se debe enviar el identificador de la pgina que se quiere editar <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else if (request.getParameter("proceso").equals("CAMBIAR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_CAMBIAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_CAMBIAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_CAMBIAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } // Solicitud de envio a procesar if (request.getParameter("id") != null) { String[] valoresParam = request.getParameterValues("id"); if (valoresParam.length == 1) { if (request.getParameter("subproceso") != null && request.getParameter("subproceso").equals("ENVIAR")) { // Verificacion if (VerificarParametros(request, response)) { Cambiar(request, response); return; } irApag("/forsetiadmin/administracion/ayuda_pagina_dlg.jsp", request, response); return; } else // Como el subproceso no es ENVIAR, abre la ventana del proceso de CAMBIADO para cargar el cambio { getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/administracion/ayuda_pagina_dlg.jsp", request, response); return; } } else { idmensaje = 1; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2); //"PRECAUCION: Solo se permite cambiar una pgina a la vez <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else { idmensaje = 3; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1); //" ERROR: Se debe enviar el identificador de la pgina que se quiere cambiar <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else if (request.getParameter("proceso").equals("ELIMINAR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_ELIMINAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_ELIMINAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_ELIMINAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } // Solicitud de envio a procesar if (request.getParameter("id") != null) { String[] valoresParam = request.getParameterValues("id"); if (valoresParam.length == 1) { Eliminar(request, response); return; } else { idmensaje = 1; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2); //"PRECAUCION: Solo se permite eliminar una pgina a la vez <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else { idmensaje = 3; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1); //" ERROR: Se debe enviar el identificador de la pgina que se quiere eliminar <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else if (request.getParameter("proceso").equals("ENLAZAR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_CAMBIAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_CAMBIAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_CAMBIAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } // Solicitud de envio a procesar if (request.getParameter("id") != null) { String[] valoresParam = request.getParameterValues("id"); if (valoresParam.length == 1) { if (request.getParameter("subproceso") != null && request.getParameter("subproceso").equals("ENVIAR")) { // Verificacion Enlazar(request, response); return; } else // Como el subproceso no es ENVIAR, abre la ventana del proceso de CAMBIADO para cargar el cambio { getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/administracion/ayuda_pagina_dlg_enlazar.jsp", request, response); return; } } else { idmensaje = 1; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2); //"PRECAUCION: Solo se permite enlazar una pgina a la vez <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else { idmensaje = 3; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1); //" ERROR: Se debe enviar el identificador de la pgina que se quiere enlazar <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else if (request.getParameter("proceso").equals("APLICAR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_CAMBIAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_CAMBIAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_CAMBIAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } // Solicitud de envio a procesar if (request.getParameter("id") != null) { String[] valoresParam = request.getParameterValues("id"); if (valoresParam.length == 1) { Aplicar(request, response); return; } else { idmensaje = 1; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 2); //"PRECAUCION: Solo se permite aplicar una pgina a la vez <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else { idmensaje = 3; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 1); //"ERROR: Se debe enviar el identificador de la pgina que se quiere aplicar <br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else if (request.getParameter("proceso").equals("GENERAR_AYUDA")) { // Revisa si tiene permisos if (!getSesion(request).getPermiso("ADMIN_AYUDA_GENERAR")) { idmensaje = 3; mensaje += MsjPermisoDenegado(request, "SAF", "ADMIN_AYUDA_GENERAR"); getSesion(request).setID_Mensaje(idmensaje, mensaje); RDP("SAF", getSesion(request).getConBD(), "NA", getSesion(request).getID_Usuario(), "ADMIN_AYUDA_GENERAR", "AYUP||||", mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } GenerarAyuda(request, response); return; } else { idmensaje = 1; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 3); //"PRECAUCION: El parmetro de proceso no es vlido<br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } } else // si no se mandan parametros, manda a error { idmensaje = 3; mensaje += JUtil.Msj("GLB", "VISTA", "GLB", "SELEC-PROC", 3); //"ERROR: No se han mandado parmetros reales<br>"; getSesion(request).setID_Mensaje(idmensaje, mensaje); irApag("/forsetiadmin/caja_mensajes.jsp", request, response); return; } }