private void preprocessRequest(final HttpServletRequest req) throws ResourceException {
    // TODO: check Accept (including charset parameter) and Accept-Charset headers

    // Check content-type.
    final String contentType = req.getContentType();
    if (!req.getMethod().equalsIgnoreCase(HttpUtils.METHOD_GET)
        && contentType != null
        && !CONTENT_TYPE_REGEX.matcher(contentType).matches()
        && !HttpUtils.isMultiPartRequest(contentType)) {
      // TODO: i18n
      throw new BadRequestException(
          "The request could not be processed because it specified the content-type '"
              + req.getContentType()
              + "' when only the content-type '"
              + MIME_TYPE_APPLICATION_JSON
              + "' and '"
              + MIME_TYPE_MULTIPART_FORM_DATA
              + "' are supported");
    }

    if (req.getHeader("If-Modified-Since") != null) {
      // TODO: i18n
      throw new ConflictException("Header If-Modified-Since not supported");
    }

    if (req.getHeader("If-Unmodified-Since") != null) {
      // TODO: i18n
      throw new ConflictException("Header If-Unmodified-Since not supported");
    }
  }
 public static final boolean isMultipartRequest(HttpServletRequest request) {
   // inspired by org.apache.commons.fileupload
   logger.debug("content-type " + request.getContentType());
   return REQUEST_METHOD_POST.equalsIgnoreCase(request.getMethod())
       && request.getContentType() != null
       && request.getContentType().toLowerCase().startsWith(CONTENT_TYPE_MULTIPART);
 }
Exemple #3
0
 public static boolean isMultipart(HttpServletRequest request) {
   if (request.getContentType() != null) {
     return request.getContentType().startsWith(__MULTIPART);
   } else {
     return false;
   }
 }
  void doPost(final HttpServletRequest req, final HttpServletResponse resp) {
    try {
      // Parse out the required API versions.
      final AcceptAPIVersion acceptVersion = parseAcceptAPIVersion(req);

      // Prepare response.
      prepareResponse(req, resp);

      // Validate request.
      preprocessRequest(req);
      rejectIfNoneMatch(req);
      rejectIfMatch(req);

      final Map<String, String[]> parameters = req.getParameterMap();
      final String action = asSingleValue(PARAM_ACTION, getParameter(req, PARAM_ACTION));
      if (action.equalsIgnoreCase(ACTION_ID_CREATE)) {
        final JsonValue content = getJsonContent(req);
        final CreateRequest request = Requests.newCreateRequest(getResourceName(req), content);
        for (final Map.Entry<String, String[]> p : parameters.entrySet()) {
          final String name = p.getKey();
          final String[] values = p.getValue();
          if (parseCommonParameter(name, values, request)) {
            continue;
          } else if (name.equalsIgnoreCase(PARAM_ACTION)) {
            // Ignore - already handled.
          } else if (HttpUtils.isMultiPartRequest(req.getContentType())) {
            // Ignore - multipart content adds form parts to the parameter set
          } else {
            request.setAdditionalParameter(name, asSingleValue(name, values));
          }
        }
        doRequest(req, resp, acceptVersion, request);
      } else {
        // Action request.
        final JsonValue content = getJsonActionContent(req);
        final ActionRequest request =
            Requests.newActionRequest(getResourceName(req), action).setContent(content);
        for (final Map.Entry<String, String[]> p : parameters.entrySet()) {
          final String name = p.getKey();
          final String[] values = p.getValue();
          if (parseCommonParameter(name, values, request)) {
            continue;
          } else if (name.equalsIgnoreCase(PARAM_ACTION)) {
            // Ignore - already handled.
          } else if (HttpUtils.isMultiPartRequest(req.getContentType())) {
            // Ignore - multipart content adds form parts to the parameter set
          } else {
            request.setAdditionalParameter(name, asSingleValue(name, values));
          }
        }
        doRequest(req, resp, acceptVersion, request);
      }
    } catch (final Exception e) {
      fail(req, resp, e);
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/plain");

    resp.getWriter().println("<h1>Hi, there!</h1>");

    String parameterMapString =
        Joiner.on(", ").withKeyValueSeparator(" => ").join(req.getParameterMap());
    resp.getWriter().println(parameterMapString);

    resp.getWriter().println("Content-type: " + req.getContentType());
    resp.getWriter().println("Request URL: " + req.getRequestURL());
    resp.getWriter().println("Request URI: " + req.getRequestURI());
    resp.getWriter().println("Servlet path: " + req.getServletPath());

    resp.getWriter()
        .println("First param is: " + this.getServletContext().getInitParameter("paramOne"));
    resp.getWriter()
        .println("Who is a titan: " + this.getServletContext().getInitParameter("titan"));

    resp.getWriter()
        .println("Databas is: " + this.getServletConfig().getInitParameter("databaseName"));
  }
Exemple #6
0
  /**
   * Wrap and return the given request or return the original request object. This method
   * transparently handles multipart data as a wrapped class around the given request. Override this
   * method to handle multipart requests in a special way or to handle other types of requests.
   * Note, {@link org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper} is flexible -
   * look first to that object before overriding this method to handle multipart data.
   *
   * @param request the HttpServletRequest object.
   * @param servletContext Our ServletContext object
   * @return a wrapped request or original request.
   * @see org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper
   * @throws java.io.IOException on any error.
   */
  public HttpServletRequest wrapRequest(HttpServletRequest request, ServletContext servletContext)
      throws IOException {
    // don't wrap more than once
    if (request instanceof StrutsRequestWrapper) {
      return request;
    }

    String content_type = request.getContentType();
    if (content_type != null && content_type.indexOf("multipart/form-data") != -1) {
      MultiPartRequest mpr = null;
      // check for alternate implementations of MultiPartRequest
      Set<String> multiNames = getContainer().getInstanceNames(MultiPartRequest.class);
      if (multiNames != null) {
        for (String multiName : multiNames) {
          if (multiName.equals(multipartHandlerName)) {
            mpr = getContainer().getInstance(MultiPartRequest.class, multiName);
          }
        }
      }
      if (mpr == null) {
        mpr = getContainer().getInstance(MultiPartRequest.class);
      }
      request = new MultiPartRequestWrapper(mpr, request, getSaveDir(servletContext));
    } else {
      request = new StrutsRequestWrapper(request);
    }

    return request;
  }
  // 上传文件数据处理过程
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
      logger.debug("type=" + request.getParameter("type"));
      logger.debug("ptype=" + request.getParameter("ptype"));
      logger.debug("puid=" + request.getParameter("puid"));
      logger.debug("absolute=" + "1".equals(request.getParameter("a")));
    }

    // 防止缓存的设置
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);

    if ("application/octet-stream".equals(request.getContentType())) {
      logger.debug("doPost4Html5");
      // HTML5上传
      doPost4Html5(request, response);
    } else {
      logger.debug("doPost4Html4");
      // HTML4普通文件上传
      doPost4Html4(request, response);
    }
  }
Exemple #8
0
  @Override
  public void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
      throws IOException {
    if (!REQ_TYPE.equals(req.getContentType())) {
      rsp.sendError(SC_UNSUPPORTED_MEDIA_TYPE);
      return;
    }

    final Repository db = getRepository(req);
    try {
      final UploadPack up = uploadPackFactory.create(req, db);
      up.setBiDirectionalPipe(false);
      rsp.setContentType(RSP_TYPE);

      final SmartOutputStream out = new SmartOutputStream(req, rsp);
      up.upload(getInputStream(req), out, null);
      out.close();

    } catch (ServiceNotAuthorizedException e) {
      rsp.reset();
      rsp.sendError(SC_UNAUTHORIZED);
      return;

    } catch (ServiceNotEnabledException e) {
      rsp.reset();
      rsp.sendError(SC_FORBIDDEN);
      return;

    } catch (IOException e) {
      getServletContext().log("Internal error during upload-pack", e);
      rsp.reset();
      rsp.sendError(SC_INTERNAL_SERVER_ERROR);
      return;
    }
  }
Exemple #9
0
 protected Object exec(Object[] args, Context context) {
   int nargs = args.length;
   if (nargs != 1 && nargs != 2) {
     undefined(args, context);
     return null;
   }
   HttpServletRequest request = (HttpServletRequest) args[0];
   String enc;
   if (nargs == 1) {
     enc = ServletEncoding.getDefaultInputEncoding(context);
   } else {
     enc = (String) args[1];
   }
   String contentType = request.getContentType();
   if (contentType != null && contentType.startsWith("multipart/form-data")) {
     throw new RuntimeException("not yet implemented");
   } else {
     try {
       ByteArrayOutputStream bout = new ByteArrayOutputStream();
       byte[] buf = new byte[512];
       int n;
       InputStream in = request.getInputStream();
       while ((n = in.read(buf, 0, buf.length)) != -1) {
         bout.write(buf, 0, n);
       }
       in.close();
       String qs = new String(bout.toByteArray());
       Map map = URLEncoding.parseQueryString(qs, enc);
       return new ServletParameter(map);
     } catch (IOException e) {
       throw new PnutsException(e, context);
     }
   }
 }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletInputStream is = request.getInputStream();
    ServletOutputStream os = response.getOutputStream();

    System.out.println(request.getContentLength());
    System.out.println(request.getContentType());
    int clength = request.getContentLength();
    byte[] data = new byte[clength];
    int offset = 0;
    do {
      int rc = is.read(data, offset, data.length - offset);
      if (-1 == rc) {
        break;
      }
      offset += rc;
    } while (offset < data.length);

    // Echo input stream to output stream
    os.println(header);
    os.print(new String(data, 0, offset));
    os.println();
    os.println(footer);

    response.setContentType("text/html");

    is.close();
    os.close();
  }
 private Optional<MediaType> getContentType(HttpServletRequest request) {
   String contentType = request.getContentType();
   if (contentType != null) {
     return Optional.of(MediaType.parseMediaType(contentType));
   }
   return Optional.empty();
 }
  @Test
  @SuppressWarnings("unchecked")
  public void Can_create_a_user_for_a_specific_content_type() {

    final MediaType contentTypeOne = APPLICATION_FORM_URLENCODED;
    final MediaType contentTypeTwo = APPLICATION_JSON;
    final UserFactory<HttpServletRequest> userFactoryOne = mock(UserFactory.class);
    final UserFactory<HttpServletRequest> userFactoryTwo = mock(UserFactory.class);
    final Map<MediaType, UserFactory<HttpServletRequest>> factories =
        new HashMap<MediaType, UserFactory<HttpServletRequest>>() {
          {
            put(contentTypeOne, userFactoryOne);
            put(contentTypeTwo, userFactoryTwo);
          }
        };

    final HttpServletRequest request = mock(HttpServletRequest.class);

    final User expected = mock(PersistedUser.class);

    // Given
    given(request.getContentType()).willReturn(contentTypeTwo.toString());
    given(userFactoryTwo.create(request)).willReturn(expected);

    // When
    final User actual = new ContentTypeUserFactory(factories).create(request);

    // Then
    assertThat(actual, equalTo(expected));
  }
 /**
  * Enforces the content-type to be application/octet-stream for POST and PUT requests.
  *
  * @param request servlet request.
  * @param response servlet response.
  * @param chain filter chain.
  * @throws IOException thrown if an IO error occurrs.
  * @throws ServletException thrown if a servet error occurrs.
  */
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   boolean contentTypeOK = true;
   HttpServletRequest httpReq = (HttpServletRequest) request;
   HttpServletResponse httpRes = (HttpServletResponse) response;
   String method = httpReq.getMethod();
   if (method.equals("PUT") || method.equals("POST")) {
     String op = httpReq.getParameter(HttpFSFileSystem.OP_PARAM);
     if (op != null && UPLOAD_OPERATIONS.contains(op.toUpperCase())) {
       if ("true"
           .equalsIgnoreCase(httpReq.getParameter(HttpFSParametersProvider.DataParam.NAME))) {
         String contentType = httpReq.getContentType();
         contentTypeOK = HttpFSFileSystem.UPLOAD_CONTENT_TYPE.equalsIgnoreCase(contentType);
       }
     }
   }
   if (contentTypeOK) {
     chain.doFilter(httpReq, httpRes);
   } else {
     httpRes.sendError(
         HttpServletResponse.SC_BAD_REQUEST,
         "Data upload requests must have content-type set to '"
             + HttpFSFileSystem.UPLOAD_CONTENT_TYPE
             + "'");
   }
 }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
      req.setCharacterEncoding("UTF-8");
      resp.setContentType(req.getContentType());

      IOUtils.copy(req.getReader(), resp.getWriter());
    }
  public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance)
      throws InterceptionException {
    Consumes consumesAnnotation = method.getMethod().getAnnotation(Consumes.class);
    List<String> supported = Arrays.asList(consumesAnnotation.value());

    String contentType = request.getContentType();
    if (!supported.isEmpty() && !supported.contains(contentType)) {
      unsupported(
          String.format(
              "Request with media type [%s]. Expecting one of %s.", contentType, supported));
      return;
    }

    try {
      Deserializer deserializer = deserializers.deserializerFor(contentType, container);
      if (deserializer == null) {
        unsupported(
            String.format("Unable to handle media type [%s]: no deserializer found.", contentType));
        return;
      }

      Object[] deserialized = deserializer.deserialize(request.getInputStream(), method);
      Object[] parameters = methodInfo.getParameters();

      for (int i = 0; i < deserialized.length; i++) {
        if (deserialized[i] != null) {
          parameters[i] = deserialized[i];
        }
      }

      stack.next(method, resourceInstance);
    } catch (IOException e) {
      throw new InterceptionException(e);
    }
  }
  @Test
  public void getBodyTest() throws IOException {
    TeeHttpServletRequest tee = new TeeHttpServletRequest(request);

    // Map content types to whether they should be logged as text or base64 encoded
    Map<String, Boolean> types = new HashMap<String, Boolean>();
    types.put(MediaType.APPLICATION_JSON, true);
    types.put(MediaType.APPLICATION_ATOM_XML, true);
    types.put(MediaType.TEXT_PLAIN, true);
    types.put(MediaType.TEXT_HTML, true);
    types.put(MediaType.TEXT_XML, true);
    types.put(MediaType.APPLICATION_FORM_URLENCODED, true);
    types.put(MediaType.APPLICATION_OCTET_STREAM, false);
    types.put("multipart/form-data", false);
    types.put("application/zip", false);

    for (String type : types.keySet()) {
      when(request.getContentType()).thenReturn(type);
      if (types.get(type)) {
        assertEquals(type + " failed!", "this is my body", tee.getBody());
      } else {
        assertEquals(type + " failed!", Util.toBase64("this is my body".getBytes()), tee.getBody());
      }
    }
  }
Exemple #17
0
  private static InputStream extractPartInputStream(
      HttpServletRequest request, HttpServletResponse response) throws IOException {
    String ct = request.getContentType();
    if (!ct.startsWith("multipart/form-data")) {
      setResponseStatus(response, HttpServletResponse.SC_BAD_REQUEST);
      response.getWriter().write("Content type must be multipart/form-data");
      return null;
    }

    String boundaryString;
    int idx = ct.indexOf("boundary=");
    if (idx < 0) {
      setResponseStatus(response, HttpServletResponse.SC_BAD_REQUEST);
      response.getWriter().write("Boundary missing");
      return null;
    }

    boundaryString = ct.substring(idx + "boundary=".length());
    byte[] boundary = boundaryString.getBytes();

    // Consume headers of the mime part.
    InputStream is = request.getInputStream();
    String line = readLine(is);
    while ((line != null) && (line.trim().length() > 0)) {
      line = readLine(is);
    }

    return new InputStreamWrapper(is, boundary);
  }
  @Test
  public void testStandardParseParamsAndFillStreams() throws Exception {
    ArrayList<ContentStream> streams = new ArrayList<ContentStream>();
    Map<String, String[]> params = new HashMap<String, String[]>();
    params.put("q", new String[] {"hello"});

    // Set up the expected behavior
    String[] ct =
        new String[] {
          "application/x-www-form-urlencoded",
          "Application/x-www-form-urlencoded",
          "application/x-www-form-urlencoded; charset=utf-8",
          "application/x-www-form-urlencoded;"
        };

    for (String contentType : ct) {
      HttpServletRequest request = createMock(HttpServletRequest.class);
      expect(request.getMethod()).andReturn("POST").anyTimes();
      expect(request.getContentType()).andReturn(contentType).anyTimes();
      expect(request.getParameterMap()).andReturn(params).anyTimes();
      replay(request);

      MultipartRequestParser multipart = new MultipartRequestParser(1000000);
      RawRequestParser raw = new RawRequestParser();
      StandardRequestParser standard = new StandardRequestParser(multipart, raw);

      SolrParams p = standard.parseParamsAndFillStreams(request, streams);

      assertEquals("contentType: " + contentType, "hello", p.get("q"));
    }
  }
  protected Properties getParams(HttpServletRequest req)
      throws UnsupportedEncodingException, IOException, ServletException {
    String contentType = req.getContentType();
    Collection<Part> parts = null;
    try {
      parts = req.getParts();
    } catch (Exception e) {
      log.debug("Error parsing request parts " + e.getMessage());
    }

    if (parts != null && !parts.isEmpty()) {
      Properties props = new Properties();
      for (Part p : parts) {
        String realContent = getContentFromPart(p);
        props.put(p.getName(), realContent);
      }
      return props;
    } else {
      Properties props = null;
      if (contentType.indexOf("application/x-www-form-urlencoded") >= 0) {
        String result = URLDecoder.decode(getFullContent(req), encoding);
        props = ParamGetter.getProps(result);

      } else if (contentType.indexOf("multipart/form-data") >= 0) {
        MultipartParser parser = new MultipartParser(req, MAXPARAMSIZE);
        props = ParamGetter.getProps(parser);
      } else {
        log.error("Cannot parse contentType of " + contentType);
        throw new IOException("Bad content type of " + contentType);
      }
      return props;
    }
  }
Exemple #20
0
 /**
  * Utility method that determines whether the content of the given request is a
  * multipart/form-data.
  *
  * <p><i>Important: This function just test the content-type of the request. The HTTP method (e.g.
  * GET, POST, ...) is not tested. </i>
  *
  * @param request The servlet request to be evaluated. Must be non-null.
  * @return <i>true</i> if the request is multipart, <i>false</i> otherwise.
  */
 public static final boolean isMultipartContent(final HttpServletRequest request) {
   // Extract the content type and determine if it is a multipart request (its content type should
   // start by multipart/form-data"):
   String contentType = request.getContentType();
   if (contentType == null) return false;
   else if (contentType.toLowerCase().startsWith(EXPECTED_CONTENT_TYPE)) return true;
   else return false;
 }
 private boolean requestIsOfType(String type, HttpServletRequest request) {
   String header = request.getHeader("Accept");
   String contentType = request.getContentType();
   String url = request.getRequestURI();
   return header != null && header.contains(type)
       || url != null && url.endsWith(type)
       || contentType != null && contentType.contains(type);
 }
Exemple #22
0
  /**
   * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as
   * was sent in the given {@link HttpServletRequest}.
   *
   * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard
   *     POST request
   * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent
   *     via the {@link PostMethod}
   */
  private void handleContentPost(
      PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
      throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (; ; ) {
      String line = reader.readLine();
      if (line == null) {
        break;
      }
      content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this
    // servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module
    // 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
      String clientHost = httpServletRequest.getLocalName();
      if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
        clientHost = "localhost";
      }

      int clientPort = httpServletRequest.getLocalPort();
      String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
      String serverUrl =
          targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

      // Replace more completely if destination server is https :
      if (targetSsl) {
        clientUrl = "http://" + clientUrl;
        serverUrl = "https://" + serverUrl;
      }
      postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace(
        "POST Content Type: {} Encoding: {} Content: {}",
        new Object[] {contentType, encoding, postContent});
    StringRequestEntity entity;
    try {
      entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
      throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
  }
Exemple #23
0
  public static boolean isHTMLForm(HttpServletRequest httpRequest) {
    String s = httpRequest.getContentType();
    if (s == null) return false;

    AcceptItem aItem = new AcceptItem(s);
    String t1 = aItem.getType();
    String t2 = aItem.getSubType();

    return (t1.equalsIgnoreCase("application") && t2.equalsIgnoreCase("x-www-form-urlencoded"));
  }
  protected Command getCommand(HttpServletRequest req, HttpServletResponse res) throws Exception {
    if (!this.httpCommandConverter.isSupport(req)) {
      throw new CommandHandleException(
          415, "Not support the httpCommandConvert[" + req.getContentType() + "]");
    }

    Command eCommand = this.httpCommandConverter.createCommand(req);
    getLogger().debug("Handle commands now");
    return eCommand;
  }
Exemple #25
0
  /**
   * Build a InMessage from an HttpServletrequest
   *
   * @param request The HttpservletRequest
   */
  public InMessage(HttpServletRequest request) {

    // TODO : Check this code : WSDL request are not well recorded !
    this.method = request.getMethod();
    // Set the headers
    this.headers = new Headers();
    Enumeration<String> headerNameEnum = request.getHeaderNames();
    while (headerNameEnum.hasMoreElements()) {
      String headerName = headerNameEnum.nextElement();
      this.headers.addHeader(new Header(headerName, request.getHeader(headerName)));
    }
    // Set protocol, server, port, path
    this.protocol = request.getProtocol().substring(0, request.getProtocol().indexOf('/'));
    this.protocolVersion = request.getProtocol().substring(request.getProtocol().indexOf('/') + 1);
    this.server = request.getServerName();
    this.port = request.getServerPort();
    this.path = request.getRequestURI();
    this.remoteHost = request.getRemoteHost();
    // this.completeUrl = request.getRequestURL().toString();
    // Set url parameters
    this.queryString = new QueryString();
    Enumeration<String> parametersNameEnum = request.getParameterNames();
    while (parametersNameEnum.hasMoreElements()) {
      String parameterName = parametersNameEnum.nextElement();
      for (String parameterValue : request.getParameterValues(parameterName)) {
        this.queryString.addQueryParam(new QueryParam(parameterName, parameterValue));
      }
    }
    this.messageContent = new MessageContent();
    StringBuffer requestBody = new StringBuffer();
    BufferedReader requestBodyReader = null;
    CharBuffer buffer = CharBuffer.allocate(512);
    try {
      requestBodyReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
      while (requestBodyReader.read(buffer) >= 0) {
        requestBody.append(buffer.flip());
        buffer.clear();
      }
      this.messageContent.setRawContent(requestBody.toString());
      this.messageContent.setSize(requestBody.length());
      this.messageContent.setMimeType(request.getContentType());
    } catch (Exception ex) {
      logger.warn("Error while reading request body !", ex);
    } finally {
      try {
        if (requestBodyReader != null) {
          requestBodyReader.close();
        }
      } catch (IOException ex) {
        // logger.warn("Error while closing the requestBodyReader !",
        // ex);
      }
    }
    this.comment = "";
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    Optional<ContentFactoryPair> factoryOptional =
        inputConfig.getFactory(Optional.of(request.getContentType()).map(MediaType::valueOf));

    if (!factoryOptional.isPresent()) {
      response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
      String msg = "Unsupported Content-Type: " + request.getContentType();
      response.getOutputStream().write(msg.getBytes(StandardCharsets.UTF_8));
      return;
    }

    TTransport transport =
        new TIOStreamTransport(request.getInputStream(), response.getOutputStream());

    TProtocol inputProtocol = factoryOptional.get().getProtocol(transport);

    Optional<String> acceptHeader = Optional.ofNullable(request.getHeader(ACCEPT));
    Optional<MediaType> acceptType = Optional.empty();
    if (acceptHeader.isPresent()) {
      try {
        acceptType = acceptHeader.map(MediaType::valueOf);
      } catch (IllegalArgumentException e) {
        // Thrown if the Accept header contains more than one type or something else we can't
        // parse, we just treat is as no header (which will pick up the default value).
        acceptType = Optional.empty();
      }
    }

    ContentFactoryPair outputProtocolFactory = outputConfig.getFactory(acceptType);

    response.setContentType(outputProtocolFactory.getOutputType().toString());
    TProtocol outputProtocol = outputProtocolFactory.getProtocol(transport);
    try {
      processor.process(inputProtocol, outputProtocol);
      response.getOutputStream().flush();
    } catch (TException e) {
      throw new ServletException(e);
    }
  }
  private void request(HttpServletRequest request) {
    System.out.println(request.getCharacterEncoding());
    System.out.println(request.getContentType());
    System.out.println(request.getProtocol());

    Enumeration<String> e = request.getHeaderNames();
    while (e.hasMoreElements()) {
      Object o = e.nextElement();
      System.out.println(o + ":" + request.getHeader((String) o));
    }
  }
Exemple #28
0
  public static boolean isFormUrlEncoded(HttpServletRequest request) {

    String contentTypeStr = request.getContentType();
    if ("POST".equalsIgnoreCase(request.getMethod())
        && contentTypeStr != null
        && contentTypeStr.startsWith(AccessConstants.X_WWW_FORM_URLECODED)) {
      return true;
    } else {
      return false;
    }
  }
Exemple #29
0
  public void doPost(HttpServletRequest request, HttpServletResponse response) {
    InputStream xmlStream = null;
    IParameterizedQuery query = null;
    try {

      HttpSession session = request.getSession();
      SessionDataBean sdb =
          (SessionDataBean)
              session.getAttribute(edu.wustl.common.util.global.Constants.SESSION_DATA);

      String queryName = request.getParameter("queryName");
      QueryExportImport queryExim = new QueryExportImport();

      if (request.getContentType() != null
          && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        if (items != null || !items.isEmpty()) {
          xmlStream = items.get(1).getInputStream();
          query = queryExim.getQuery(xmlStream);
        }
      } else if (queryName != null || !queryName.isEmpty()) {
        query = (IParameterizedQuery) session.getAttribute("deSerializedQueryObj");
        query.setName(queryName);
      }

      boolean isQueryImported = queryExim.importQuery(query, sdb);

      if (isQueryImported) {
        response.getWriter().write("Success :'" + query.getName() + "'");
        session.removeAttribute("deSerializedQueryObj");
      } else {
        session.setAttribute("deSerializedQueryObj", query);
        response.getWriter().write("Error:");
      }

    } catch (Exception e) {
      throw new RuntimeException("Error occured during importing query", e);
    }
  }
 @SuppressWarnings("unchecked")
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String contentType = request.getContentType();
   if (contentType != null && contentType.startsWith("application/json")) {
     doPostJSON(request, response);
   } else if (contentType != null && contentType.startsWith("application/xml")) {
     doPostXml(request, response);
   } else {
     doPostForm(request, response);
   }
 }