Java Code Examples for org.eclipse.jetty.server.Request#setHandled()

The following examples show how to use org.eclipse.jetty.server.Request#setHandled() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JettyServerHandler.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	
	// invoke
       RpcResponse rpcResponse = doInvoke(request);

       // serialize response
       byte[] responseBytes = HessianSerializer.serialize(rpcResponse);
	
	response.setContentType("text/html;charset=utf-8");
	response.setStatus(HttpServletResponse.SC_OK);
	baseRequest.setHandled(true);
	
	OutputStream out = response.getOutputStream();
	out.write(responseBytes);
	out.flush();
	
}
 
Example 2
Source File: ArtifactCacheHandler.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(
    String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException {
  try {
    int status = handle(baseRequest, response);
    response.setStatus(status);
  } catch (Exception e) {
    LOG.error(e, "Exception when handling request %s", target);
    e.printStackTrace(response.getWriter());
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  } finally {
    response.flushBuffer();
    baseRequest.setHandled(true);
  }
}
 
Example 3
Source File: RESTParametersTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@Override
public void handle( String target, Request baseRequest, HttpServletRequest request,
                    HttpServletResponse response ) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    StringBuilder jb = new StringBuilder();
    String line;
    BufferedReader reader = request.getReader();
    while ( ( line = reader.readLine() ) != null )
    {
        jb.append( line );
    }
    gavSchema = objectMapper.readValue( jb.toString(), GAVSchema.class );
    LOGGER.info( "Read request body '{}' and read parameters '{}' and Group {} ", jb, request.getParameterMap(), gavSchema.repositoryGroup );
    baseRequest.setHandled( true );

}
 
Example 4
Source File: TestInvokeHttpCommon.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    baseRequest.setHandled(true);


    if ("Fetch".equalsIgnoreCase(request.getMethod())) {
        final int status = Integer.valueOf(target.substring("/status".length() + 1));
        response.setStatus(status);
        response.setContentType("text/plain");
        response.setContentLength(target.length());

        try (PrintWriter writer = response.getWriter()) {
            writer.print(target);
            writer.flush();
        }
    } else {

        response.setStatus(404);
        response.setContentType("text/plain");
        response.setContentLength(target.length());
    }
}
 
Example 5
Source File: RESTParametersVersionSuffixTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@Override
public void handle( String target, Request baseRequest, HttpServletRequest request,
                    HttpServletResponse response ) throws IOException, ServletException
{
    ObjectMapper objectMapper = new ObjectMapper();
    StringBuilder jb = new StringBuilder();
    String line;
    BufferedReader reader = request.getReader();
    while ( ( line = reader.readLine() ) != null )
    {
        jb.append( line );
    }
    gavSchema = objectMapper.readValue( jb.toString(), GAVSchema.class );
    LOGGER.info( "Read request body '{}' and read parameters '{}' and Group {} ", jb, request.getParameterMap(), gavSchema.repositoryGroup );
    baseRequest.setHandled( true );

}
 
Example 6
Source File: ConfirmationCodeRequestHandler.java    From vk-java-sdk with MIT License 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        return;
    }

    String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    Type typeOfClass = new TypeToken<CallbackMessage<JsonObject>>() {
    }.getType();
    CallbackMessage<JsonObject> callback = gson.fromJson(body, typeOfClass);
    if (callback == null) {
        return;
    }

    if (callback.getType() != MessageType.CONFIRMATION) {
        return;
    }

    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    baseRequest.setHandled(true);
    response.getWriter().println(confirmationCode);
}
 
Example 7
Source File: Responses.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Writes the specified content to the response with the specified status code. */
private static void writeResponse(
    String content,
    MediaType mediaType,
    Request baseRequest,
    HttpServletResponse response,
    int status)
    throws IOException {
  response.setContentType(mediaType.toString());
  response.setStatus(status);

  response.getWriter().write(content);

  response.flushBuffer();
  baseRequest.setHandled(true);
}
 
Example 8
Source File: TraceDataHandlerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleGetWithMultipleTraceCallback() throws IOException {
  Request baseRequest = createMock(Request.class);
  expect(baseRequest.getMethod()).andReturn("GET");
  expect(baseRequest.getPathInfo()).andReturn("/abcdef");
  expect(baseRequest.getParameter("callback")).andReturn("my.callback");
  baseRequest.setHandled(true);
  HttpServletRequest request = createMock(HttpServletRequest.class);

  HttpServletResponse response = createMock(HttpServletResponse.class);
  response.setStatus(200);
  response.setContentType("application/javascript; charset=utf-8");
  StringWriter stringWriter = new StringWriter();
  PrintWriter printWriter = new PrintWriter(stringWriter); // NOPMD required by API
  expect(response.getWriter()).andReturn(printWriter);
  response.flushBuffer();

  BuildTraces buildTraces = createMock(BuildTraces.class);
  Iterable<InputStream> traces =
      Arrays.asList(
          new ByteArrayInputStream("{\"foo\":\"bar\"}".getBytes(Charsets.UTF_8)),
          new ByteArrayInputStream("{\"baz\":\"blech\"}".getBytes(Charsets.UTF_8)));
  expect(buildTraces.getInputsForTraces("abcdef")).andReturn(traces);

  TraceDataHandler traceDataHandler = new TraceDataHandler(buildTraces);

  replayAll();
  traceDataHandler.handle("/trace/abcdef?callback=my.callback", baseRequest, request, response);
  verifyAll();

  assertEquals(
      "my.callback([{\"foo\":\"bar\"},{\"baz\":\"blech\"}]);\n", stringWriter.toString());
}
 
Example 9
Source File: ReferrerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String s, Request baseRequest, HttpServletRequest request,
                   HttpServletResponse response) throws IOException, ServletException {
  if (request.getRequestURI().endsWith("/favicon.ico")) {
    response.setStatus(204);
    baseRequest.setHandled(true);
    return;
  }

  // Don't record / requests so we can poll the server for availability in start().
  if (!"/".equals(request.getRequestURI())) {
    requests.add(new HttpRequest(
      request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + request.getQueryString()),
      request.getHeader(HttpHeaders.REFERER)));
  }

  String responseHtml;
  if (request.getRequestURI().contains("/page1.html")) {
    responseHtml = page1;
  } else if (request.getRequestURI().contains("/page2.html")) {
    responseHtml = page2;
  } else {
    responseHtml = page3;
  }

  response.setContentType("text/html; charset=utf-8");
  response.setStatus(HttpServletResponse.SC_OK);
  response.getWriter().println(responseHtml);
  baseRequest.setHandled(true);
}
 
Example 10
Source File: TraceeHttpInterceptorsIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
	final String incomingTraceeHeader = request.getHeader(TraceeConstants.TPIC_HEADER);

	assertThat(incomingTraceeHeader, equalTo("before+Request=yip"));

	httpServletResponse.setHeader(TraceeConstants.TPIC_HEADER, "responseFromServer=yes+Sir");
	httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
	request.setHandled(true);
}
 
Example 11
Source File: TestInvokeHttpCommon.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    baseRequest.setHandled(true);

    final int status = Integer.valueOf(target.substring("/status".length() + 1));
    response.setStatus(status);

    response.setContentType("text/plain");
    response.setContentLength(target.length());

    if ("GET".equalsIgnoreCase(request.getMethod())) {
        try (PrintWriter writer = response.getWriter()) {
            writer.print(target);
            writer.flush();
        }
    } else {
        response.setStatus(404);
        response.setContentType("text/plain");

        //Lorem Ipsum
        String body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
                + "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor "
                + "in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, "
                + "sunt in culpa qui officia deserunt mollit anim id est laborum.";

        response.setContentLength(body.length());
        response.setContentType("text/plain");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(body);
            writer.flush();
        }
    }

}
 
Example 12
Source File: GoServerLoadingIndicationHandler.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void respondWith503(Request baseRequest, HttpServletResponse response, String contentType, String body) throws IOException {
    addHeaders(response);
    response.setStatus(org.eclipse.jetty.http.HttpStatus.SERVICE_UNAVAILABLE_503);
    response.setContentType(contentType);
    response.getWriter().println(body);
    baseRequest.setHandled(true);
}
 
Example 13
Source File: TestJFrogArtifactoryClientHelper.java    From artifactory_ssh_proxy with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String path, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException
{
    
    String statusCode = httpRequest.getParameter("status");
    if (path.contains("/api/storage")){
        if (Integer.valueOf(statusCode) == 500){
            retryCountMetaData++;
        }
    }else if (path.contains("/testrepo/test.txt")){
        if (Integer.valueOf(statusCode) == 500){
            retryCountContent++;
        }
    }
    StringBuilder storageJson = new StringBuilder();
    storageJson.append("{")
    .append("\"created\": \"2016-04-05\",")
    .append("\"size\": \"1024\"")
    .append("}");
    request.setHandled(true);
    httpResponse.setStatus(Integer.valueOf(statusCode));
    OutputStream out=httpResponse.getOutputStream();
    byte[] bytes=storageJson.toString().getBytes(StandardCharsets.UTF_8);
    out.write(bytes);
    out.flush();
    out.close();
}
 
Example 14
Source File: TraceHandlerDelegateTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleGet() throws IOException, ServletException {
  Request baseRequest = createMock(Request.class);
  expect(baseRequest.getPathInfo()).andReturn("/abcdef");
  baseRequest.setHandled(true);
  HttpServletRequest request = createMock(HttpServletRequest.class);

  HttpServletResponse response = createMock(HttpServletResponse.class);
  response.setStatus(200);
  response.setContentType("text/html; charset=utf-8");
  StringWriter stringWriter = new StringWriter();
  PrintWriter printWriter = new PrintWriter(stringWriter); // NOPMD required by API
  expect(response.getWriter()).andReturn(printWriter);
  response.flushBuffer();

  BuildTraces buildTraces = createMock(BuildTraces.class);
  expect(buildTraces.getTraceAttributesFor("abcdef"))
      .andReturn(new TraceAttributes(Optional.of("buck build buck"), FileTime.fromMillis(2000L)));
  Handler traceHandler = new TemplateHandler(new TraceHandlerDelegate(buildTraces));

  replayAll();
  traceHandler.handle("/trace/abcdef", baseRequest, request, response);
  verifyAll();

  String expectedScriptTag = "<script src=\"/tracedata/abcdef?callback=onTracesLoaded\">";
  String html = stringWriter.toString();
  assertThat(html, containsString(expectedScriptTag));
  assertThat(html, containsString("buck build buck"));
}
 
Example 15
Source File: JmxWebHandler.java    From simplejmx with ISC License 5 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
		throws IOException {
	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
	if (mbeanServer == null) {
		mbeanServer = ManagementFactory.getPlatformMBeanServer();
	}
	processRequest(request, response, writer);
	baseRequest.setHandled(true);
	writer.close();
}
 
Example 16
Source File: HttpMessageTranslatorTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
@Override
public void handle( String target, Request baseRequest, HttpServletRequest request,
                    HttpServletResponse response )
                throws IOException, ServletException
{
    response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
    baseRequest.setHandled( true );
    response.getWriter().println( "{\"errorType\":\"Communication with remote repository failed\"}");
}
 
Example 17
Source File: DoctorCommandIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private AbstractHandler createEndpointHttpdHandler(String expectedMethod, String expectedBody) {
  return new AbstractHandler() {
    @Override
    public void handle(
        String s,
        Request request,
        HttpServletRequest httpRequest,
        HttpServletResponse httpResponse)
        throws IOException {
      httpResponse.setStatus(200);
      request.setHandled(true);

      if (request.getHttpURI().getPath().equals("/status.php")) {
        return;
      }

      httpResponse.setContentType("application/json");
      httpResponse.setCharacterEncoding("utf-8");

      requestPath.set(request.getHttpURI().getPath());
      requestMethod.set(request.getMethod());
      requestBody.set(ByteStreams.toByteArray(httpRequest.getInputStream()));

      assertTrue(requestMethod.get().equalsIgnoreCase(expectedMethod));
      assertThat(
          "Request should contain the uuid.",
          new String(requestBody.get(), Charsets.UTF_8),
          Matchers.containsString(expectedBody));

      try (DataOutputStream out = new DataOutputStream(httpResponse.getOutputStream())) {
        ObjectMappers.WRITER.writeValue((DataOutput) out, doctorResponse);
      }
    }
  };
}
 
Example 18
Source File: ArtifactCachesIntegrationTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(
    String s,
    Request request,
    HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse)
    throws IOException {

  X509Certificate[] certs =
      (X509Certificate[])
          httpServletRequest.getAttribute("javax.servlet.request.X509Certificate");
  peerCertificates.add(certs);
  if (isThrift) {
    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

    BuckCacheResponse response = new BuckCacheResponse();
    response.setWasSuccessful(true);

    if (isStore) {
      BuckCacheStoreResponse storeResponse = new BuckCacheStoreResponse();
      response.setStoreResponse(storeResponse);
    } else {
      BuckCacheMultiFetchResponse multiFetchResponse = new BuckCacheMultiFetchResponse();
      List<FetchResult> fetchResults = new ArrayList<>();
      fetchResults.add(new FetchResult().setResultType(FetchResultType.MISS));
      multiFetchResponse.setResults(fetchResults);
      response.setMultiFetchResponse(multiFetchResponse);
    }

    byte[] serialized = ThriftUtil.serialize(ThriftArtifactCache.PROTOCOL, response);
    httpServletResponse.setContentType("application/octet-stream");
    httpServletResponse
        .getOutputStream()
        .write(ByteBuffer.allocate(4).putInt(serialized.length).array());
    httpServletResponse.getOutputStream().write(serialized);
    httpServletResponse.getOutputStream().close();
  } else {
    if (isStore) {
      httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    } else {
      httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
  }
  request.setHandled(true);
}
 
Example 19
Source File: ResourceHandler.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override public void handle(
    String url,
    Request request,
    HttpServletRequest httpServletRequest,
    HttpServletResponse response) throws IOException, ServletException {

    String[] path = url.split("/");

    String fileName = path[path.length - 1];

    String servicePath = url.substring(0, url.length() - fileName.length());

    switch (servicePath) {
        case IGNITE_PREFIX:
            handleRequest(response, "application/zip-archive", igniteDir + "/" + fileName);

            request.setHandled(true);
            break;

        case LIBS_PREFIX:
            handleRequest(response, "application/java-archive", libsDir + "/" + fileName);

            request.setHandled(true);
            break;

        case CONFIG_PREFIX:
            handleRequest(response, "application/xml", cfgPath);

            request.setHandled(true);
            break;

        case DEFAULT_CONFIG:
            handleRequest(response, "application/xml",
                Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName),
                fileName);

            request.setHandled(true);
            break;
    }
}
 
Example 20
Source File: KeePassHttpHandler.java    From KeePassJava2 with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {

    logger.debug("Got a request");

    InputStream is = new LogginInputStream(request.getInputStream(), logger);
    OutputStream outputStream = new LogginOutputStream(httpServletResponse.getOutputStream(), logger);
    Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream));

    Message.Request request1 = gson.fromJson(new BufferedReader(new InputStreamReader(is)),Message.Request.class);
    if (request1 == null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        request.setHandled(true);
        writer.write("That's a 400. JSON not parsed. " + request.getRemoteAddr());
        return;
    }
    if (request1.RequestType == null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        request.setHandled(true);
        writer.write("That's a 400. No request type found. " + request.getRemoteAddr());
        return;
    }

    Message.Response response = new Message.Response(request1.RequestType, adaptor.getHash());

    // set the crypto key on associate
    if (request1.RequestType.equals(Message.Type.ASSOCIATE)) {
        crypto.setKey(Helpers.decodeBase64Content(request1.Key.getBytes(), false));
    }

    // send OK even when it's fail
    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

    // normal part of the protocol to fail verification on test-associate
    if (!crypto.verify(request1)) {
        logger.debug("Request failed verification");
        response.Success = false;
    } else {
        try {
            // processor is responsible for setting success
            processor.process(request1, response);
            response.Id = adaptor.getId();
        } catch (Exception e) {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.Success = false;
            response.Error = "Error processing request " + e.getMessage();
        }
    }
    // presumably errors need to be verifiable?
    crypto.makeVerifiable(response);
    gson.toJson(response, writer);
    writer.flush();
    request.setHandled(true);
}