protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    logger.debug("Request URL: " + request.getRequestURI());
    logger.debug("Request Path Info: " + request.getPathInfo());
    logger.debug("Request Param: " + request.getQueryString());

    RestRequest restRequest = null;
    try {
      String url = request.getPathInfo();
      if (request.getQueryString() != null) url += "?" + request.getQueryString();
      restRequest = new RestRequest(url, HttpMethod.POST.name());
    } catch (ServletException e) {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("Invalid URL!");
      return;
    }

    String serviceId = restRequest.getId();
    String format = restRequest.getFormat();

    for (String s : request.getParameterMap().keySet())
      logger.debug(s + " --- " + request.getParameterMap().get(s).toString());
    logger.debug("Id: " + serviceId);
    logger.debug("Format: " + format);

    // request.setCharacterEncoding(CharEncoding.ISO_8859_1);
    logger.info("Content-Type: " + request.getContentType());

    String formData = null;
    String inputLang = "";
    if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_XML))
      inputLang = SerializationLang.XML;
    if (request.getContentType().startsWith(MimeType.TEXT_XML)) inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_XML))
      inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_N3))
      inputLang = SerializationLang.N3;
    if (request.getContentType().startsWith(MimeType.APPLICATION_FORM_URLENCODED)) {
      inputLang = SerializationLang.N3; // default for html forms
      formData = request.getParameter("rdf");
      logger.debug(formData);
    } else {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("The content type is neither rdf+xml nor rdf+n3");
      return;
    }

    InputStream in = request.getInputStream();

    if (formData != null) {
      in = new ByteArrayInputStream(formData.getBytes());
    }

    new PostRequestManager(serviceId, in, inputLang, format, response).HandleRequest();

    response.flushBuffer();
  }
Exemplo n.º 2
0
  /* ------------------------------------------------------------ */
  @Override
  public void push() {
    if (HttpMethod.POST.is(_method) || HttpMethod.PUT.is(_method))
      throw new IllegalStateException("Bad Method " + _method);

    if (_path == null || _path.length() == 0) throw new IllegalStateException("Bad Path " + _path);

    String path = _path;
    String query = _queryString;
    int q = path.indexOf('?');
    if (q >= 0) {
      query =
          (query != null && query.length() > 0)
              ? (_path.substring(q + 1) + '&' + query)
              : _path.substring(q + 1);
      path = _path.substring(0, q);
    }

    if (!path.startsWith("/")) path = URIUtil.addPaths(_request.getContextPath(), path);

    String param = null;
    if (_sessionId != null) {
      if (_request.isRequestedSessionIdFromURL()) param = "jsessionid=" + _sessionId;
      // TODO else
      //      _fields.add("Cookie","JSESSIONID="+_sessionId);
    }

    if (_conditional) {
      if (_etag != null) _fields.add(HttpHeader.IF_NONE_MATCH, _etag);
      else if (_lastModified != null) _fields.add(HttpHeader.IF_MODIFIED_SINCE, _lastModified);
    }

    HttpURI uri =
        HttpURI.createHttpURI(
            _request.getScheme(),
            _request.getServerName(),
            _request.getServerPort(),
            _path,
            param,
            query,
            null);
    MetaData.Request push = new MetaData.Request(_method, uri, _request.getHttpVersion(), _fields);

    if (LOG.isDebugEnabled())
      LOG.debug(
          "Push {} {} inm={} ims={}",
          _method,
          uri,
          _fields.get(HttpHeader.IF_NONE_MATCH),
          _fields.get(HttpHeader.IF_MODIFIED_SINCE));

    _request.getHttpChannel().getHttpTransport().push(push);
    _path = null;
    _etag = null;
    _lastModified = null;
  }
Exemplo n.º 3
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    final boolean isSmile = QueryResource.APPLICATION_SMILE.equals(request.getContentType());
    final ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;

    String host = hostFinder.getDefaultHost();
    Query inputQuery = null;
    boolean hasContent = request.getContentLength() > 0 || request.getContentType() != null;
    boolean isQuery = request.getMethod().equals(HttpMethod.POST.asString());
    long startTime = System.currentTimeMillis();

    // queries only exist for POST
    if (isQuery) {
      try {
        inputQuery = objectMapper.readValue(request.getInputStream(), Query.class);
        if (inputQuery != null) {
          host = hostFinder.getHost(inputQuery);
          if (inputQuery.getId() == null) {
            inputQuery = inputQuery.withId(UUID.randomUUID().toString());
          }
        }
      } catch (IOException e) {
        log.warn(e, "Exception parsing query");
        final String errorMessage = e.getMessage() == null ? "no error message" : e.getMessage();
        requestLogger.log(
            new RequestLogLine(
                new DateTime(),
                request.getRemoteAddr(),
                null,
                new QueryStats(
                    ImmutableMap.<String, Object>of("success", false, "exception", errorMessage))));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType(QueryResource.APPLICATION_JSON);
        objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));

        return;
      } catch (Exception e) {
        handleException(response, objectMapper, e);
        return;
      }
    }

    URI rewrittenURI = rewriteURI(host, request);
    if (rewrittenURI == null) {
      onRewriteFailed(request, response);
      return;
    }

    final Request proxyRequest =
        getHttpClient()
            .newRequest(rewrittenURI)
            .method(request.getMethod())
            .version(HttpVersion.fromString(request.getProtocol()));

    // Copy headers
    for (Enumeration<String> headerNames = request.getHeaderNames();
        headerNames.hasMoreElements(); ) {
      String headerName = headerNames.nextElement();

      if (HttpHeader.TRANSFER_ENCODING.is(headerName)) {
        hasContent = true;
      }

      for (Enumeration<String> headerValues = request.getHeaders(headerName);
          headerValues.hasMoreElements(); ) {
        String headerValue = headerValues.nextElement();
        if (headerValue != null) {
          proxyRequest.header(headerName, headerValue);
        }
      }
    }

    // Add proxy headers
    addViaHeader(proxyRequest);

    addXForwardedHeaders(proxyRequest, request);

    final AsyncContext asyncContext = request.startAsync();
    // We do not timeout the continuation, but the proxy request
    asyncContext.setTimeout(0);
    proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);

    if (hasContent) {
      if (inputQuery != null) {
        proxyRequest.content(new BytesContentProvider(jsonMapper.writeValueAsBytes(inputQuery)));
      } else {
        proxyRequest.content(proxyRequestContent(proxyRequest, request));
      }
    }

    customizeProxyRequest(proxyRequest, request);

    if (isQuery) {
      proxyRequest.send(
          newMetricsEmittingProxyResponseListener(request, response, inputQuery, startTime));
    } else {
      proxyRequest.send(newProxyResponseListener(request, response));
    }
  }