org.eclipse.jetty.server.Request Java Examples

The following examples show how to use org.eclipse.jetty.server.Request. 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: ResponsesTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteFailedResponse() throws IOException {
  Request baseRequest = createMock(Request.class);
  baseRequest.setHandled(true);

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

  replayAll();
  Responses.writeFailedResponse(baseRequest, response);
  verifyAll();

  assertEquals("ERROR", stringWriter.toString());
}
 
Example #2
Source File: ErrorController.java    From codenjoy with GNU General Public License v3.0 6 votes vote down vote up
private ResponseEntity<ModelMap> error(Exception exception, HttpServletRequest req, ModelMap model) {
    String url = req.getRequestURL().toString();

    // для "not found" запросов вытаскиваем доп инфо
    if (req instanceof SecurityContextHolderAwareRequestWrapper) {
        ServletRequest request = ((SecurityContextHolderAwareRequestWrapper) req).getRequest();
        if (request instanceof FirewalledRequest) {
            ServletRequest request2 = ((FirewalledRequest) request).getRequest();
            if (request2 instanceof Request) {
                url = String.format("%s [%s]",
                        url, ((Request)request2).getOriginalURI());
            }
        }
    }

    ModelAndView view = ticket.get(url, exception);
    model.mergeAttributes(view.getModel());

    return new ResponseEntity<>(model,
            HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example #3
Source File: ChaosHttpProxyTest.java    From chaos-http-proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void testContentLengthNotStrippedByJettyBug() throws Exception {
    // Set up a handler that asserts the presence of a content-length
    httpBin.stop();
    final AtomicReference<Boolean> gotContentLength =
            new AtomicReference<>(false);
    setupHttpBin(new HttpBin(httpBinEndpoint, new HttpBinHandler() {
            @Override
            public void handle(String target, Request baseRequest,
                    HttpServletRequest request,
                    HttpServletResponse servletResponse)
                    throws IOException {
                if (request.getHeader(
                        HttpHeader.CONTENT_LENGTH.asString()) != null) {
                    gotContentLength.set(true);
                }
            }
        }));

    // The content has to be large-ish to exercise the bug
    client.POST(httpBinEndpoint + "/post")
            .content(new BytesContentProvider(new byte[65536]))
            .header(HttpHeader.CONTENT_LENGTH, String.valueOf(65536))
            .send();
    assertThat(gotContentLength.get()).isTrue();
}
 
Example #4
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 #5
Source File: Log4JAccessLogTest.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    // Create mock objects
    mockLog4jContextFactory = mock(Log4jContextFactory.class);
    whenNew(Log4jContextFactory.class).withNoArguments().thenReturn(mockLog4jContextFactory);
    mockLoggerContext = mock(LoggerContext.class);
    mockLogger = mock(Logger.class);
    when(mockLog4jContextFactory.getContext(anyString(), any(ClassLoader.class), any(), anyBoolean(), any(URI.class), anyString())).thenReturn(mockLoggerContext);
    when(mockLoggerContext.getRootLogger()).thenReturn(mockLogger);
    mockRequest = mock(Request.class);
    mockResponse = mock(Response.class);
    mockAccessLog = mock(AccessLog.class);
    whenNew(AccessLog.class).withArguments(mockRequest, mockResponse).thenReturn(mockAccessLog);

    // Create actual objects
    enabledSupplier = () -> true;
    disabledSupplier = () -> false;
    failedAccessLog = new TestLog4JAccessLog(NON_EXISTING_FILE_PATH, enabledSupplier);
    String filePath = getClass().getClassLoader().getResource(ACCESS_CONFIG_FILE_PATH).getPath();
    enabledAccessLog = new TestLog4JAccessLog(filePath, enabledSupplier);
    disabledAccessLog = new TestLog4JAccessLog(filePath, disabledSupplier);
}
 
Example #6
Source File: AndroidJettyServletContainer.java    From BeyondUPnP with Apache License 2.0 6 votes vote down vote up
public static boolean isConnectionOpen(HttpServletRequest request, byte[] heartbeat) {
    Request jettyRequest = (Request) request;
    AbstractHttpConnection connection = jettyRequest.getConnection();
    Socket socket = (Socket) connection.getEndPoint().getTransport();
    if (log.isLoggable(Level.FINE))
        log.fine("Checking if client connection is still open: " + socket.getRemoteSocketAddress());
    try {
        socket.getOutputStream().write(heartbeat);
        socket.getOutputStream().flush();
        return true;
    } catch (IOException ex) {
        if (log.isLoggable(Level.FINE))
            log.fine("Client connection has been closed: " + socket.getRemoteSocketAddress());
        return false;
    }
}
 
Example #7
Source File: HttpResponseStatisticsCollector.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String path, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    inFlight.incrementAndGet();

    /* The control flow logic here is mostly a copy from org.eclipse.jetty.server.handler.StatisticsHandler.handle(..) */
    try {
        Handler handler = getHandler();
        if (handler != null && shutdown.get() == null && isStarted()) {
            handler.handle(path, baseRequest, request, response);
        } else if (!baseRequest.isHandled()) {
            baseRequest.setHandled(true);
            response.sendError(HttpStatus.SERVICE_UNAVAILABLE_503);
        }
    } finally {
        HttpChannelState state = baseRequest.getHttpChannelState();

        if (state.isSuspended()) {
            if (state.isInitial()) {
                state.addListener(completionWatcher);
            }
        } else if (state.isInitial()) {
            observeEndOfRequest(baseRequest, response);
        }
    }
}
 
Example #8
Source File: MainServer.java    From JrebelBrainsLicenseServerforJava with Apache License 2.0 6 votes vote down vote up
private void pingHandler ( String target , Request baseRequest , HttpServletRequest request , HttpServletResponse response ) throws IOException
{
    response.setContentType("text/html; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    String salt = request.getParameter("salt");
    baseRequest.setHandled(true);
    if(salt==null){
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }else{
        String xmlContent = "<PingResponse><message></message><responseCode>OK</responseCode><salt>" + salt + "</salt></PingResponse>";
        String xmlSignature = rsasign.Sign(xmlContent);
        String body = "<!-- " + xmlSignature + " -->\n" + xmlContent;
        response.getWriter().print(body);
    }

}
 
Example #9
Source File: SpringTimeHandler.java    From springtime 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 {
	if (!target.startsWith(RPC_PREFIX)) {
		return;
	}
	String path = target.toLowerCase();
	Serializer serializerForRequest = serializer;

	dispatcher.dispatch(path, serializerForRequest, baseRequest.getInputStream(), response.getOutputStream());

	response.setContentType(Serializer.JSON_TYPE);
	response.setStatus(HttpServletResponse.SC_OK);
	response.getOutputStream().flush();
	baseRequest.setHandled(true);
}
 
Example #10
Source File: FaultToEndpointServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handle(String target, Request baseRequest, HttpServletRequest request,
                   HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("text/html;charset=utf-8");

    //System.out.println("In handler: " + request.getContentLength());

    byte[] bytes = new byte[1024];
    InputStream in = request.getInputStream();
    while (in.read(bytes) > -1) {
        //nothing
    }

    faultRequestPath = request.getPathInfo();
    if ("/faultTo".equals(faultRequestPath)) {
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
    PrintWriter writer = response.getWriter();
    writer.println("Received");
    writer.close();
    baseRequest.setHandled(true);
}
 
Example #11
Source File: TestRequestDispatcher.java    From joynr with Apache License 2.0 6 votes vote down vote up
private void forwardToUrl(final String targetContextPath,
                          Request baseRequest,
                          HttpServletResponse response) throws ServletException, IOException {

    logger.info("Forward request {} to context {}", baseRequest.toString(), targetContextPath);

    synchronized (contextForwardCounts) {
        int currentContextForwardCount = 0;
        if (contextForwardCounts.containsKey(targetContextPath)) {
            currentContextForwardCount = contextForwardCounts.get(targetContextPath);
        }
        contextForwardCounts.put(targetContextPath, currentContextForwardCount + 1);
    }

    ServletContext currentContext = baseRequest.getServletContext();
    String currentContextPath = currentContext.getContextPath();

    String forwardContextPath = currentContextPath.replace(ClusteredBounceProxyWithDispatcher.CONTEXT_DISPATCHER,
                                                           targetContextPath);

    ServletContext forwardContext = currentContext.getContext(forwardContextPath);
    String forwardPath = baseRequest.getPathInfo();
    RequestDispatcher requestDispatcher = forwardContext.getRequestDispatcher(forwardPath);

    requestDispatcher.forward(baseRequest, response);
}
 
Example #12
Source File: SolrRequestParsers.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public SolrParams parseParamsAndFillStreams(
    final HttpServletRequest req, ArrayList<ContentStream> streams) throws Exception {
  if (!isMultipart(req)) {
    throw new SolrException( ErrorCode.BAD_REQUEST, "Not multipart content! "+req.getContentType() );
  }
  // Magic way to tell Jetty dynamically we want multi-part processing.  "Request" here is a Jetty class
  req.setAttribute(Request.MULTIPART_CONFIG_ELEMENT, multipartConfigElement);

  MultiMapSolrParams params = parseQueryString( req.getQueryString() );

  // IMPORTANT: the Parts will all have the delete() method called by cleanupMultipartFiles()

  for (Part part : req.getParts()) {
    if (part.getSubmittedFileName() == null) { // thus a form field and not file upload
      // If it's a form field, put it in our parameter map
      String partAsString = org.apache.commons.io.IOUtils.toString(new PartContentStream(part).getReader());
      MultiMapSolrParams.addParam(
          part.getName().trim(),
          partAsString, params.getMap() );
    } else { // file upload
      streams.add(new PartContentStream(part));
    }
  }
  return params;
}
 
Example #13
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Before
public void initializeCollector() throws Exception {
    Server server = new Server();
    connector = new AbstractConnector(server, null, null, null, 0) {
        @Override
        protected void accept(int acceptorID) throws IOException, InterruptedException {
        }

        @Override
        public Object getTransport() {
            return null;
        }
    };
    collector.setHandler(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            baseRequest.setHandled(true);
            baseRequest.getResponse().setStatus(httpResponseCode);
        }
    });
    server.setHandler(collector);
    server.start();
}
 
Example #14
Source File: SpnegoTestUtil.java    From calcite-avatica 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 {
  Authentication auth = baseRequest.getAuthentication();
  if (Authentication.UNAUTHENTICATED == auth) {
    throw new AssertionError("Unauthenticated users should not reach here!");
  }

  baseRequest.setHandled(true);
  UserAuthentication userAuth = (UserAuthentication) auth;
  UserIdentity userIdentity = userAuth.getUserIdentity();
  Principal userPrincipal = userIdentity.getUserPrincipal();

  response.getWriter().print("OK " + userPrincipal.getName());
  response.setStatus(200);
}
 
Example #15
Source File: Zippy.java    From XRTB 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.addHeader("Access-Control-Allow-Origin", "*");
	response.setHeader("Cache-Control","max-age=86400");
	response.setHeader("Cache-Control","must-revalidate");
	response.setContentType("text/html;charset=utf-8");

	String url = request.getQueryString();
	StringBuilder output = new StringBuilder(target);
	InputStream body = request.getInputStream();
	output.append(url);
	output.append("\n");
	if (body != null) {
		final int bufferSize = 1024;
       	final char[] buffer = new char[bufferSize];
       	final StringBuilder out = new StringBuilder();
       	Reader in = new InputStreamReader(body, "UTF-8");
       	for (; ; ) {
       	    int rsz = in.read(buffer, 0, buffer.length);
       	    if (rsz < 0)
       	        break;
       	    out.append(buffer, 0, rsz);
       	}
       	String data = out.toString();
       	String [] x = data.split("\n");
       	count += x.length;
       	
       	output.append(data);
	}
	System.out.println(output.toString());
	System.out.println("------------- " + count + " ----------------");
	baseRequest.setHandled(true);
	response.setStatus(200);
	
}
 
Example #16
Source File: HttpTestServer.java    From rockscript with Apache License 2.0 5 votes vote down vote up
private PathMatch findPathMatch(String path, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
  for (RequestHandler requestHandler: requestHandlers) {
    Map<String,Object> pathParameters = requestHandler.matches(path, request, httpServletRequest, httpServletResponse);
    if (pathParameters!=null) {
      return new PathMatch(requestHandler.handler, pathParameters);
    }
  }
  throw new RuntimeException("No handler found for "+request.getMethod()+" "+path);
}
 
Example #17
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Request testRequest(String scheme, int responseCode, String httpMethod, String path) throws Exception {
    HttpChannel channel = new HttpChannel(connector, new HttpConfiguration(), null, new DummyTransport());
    MetaData.Request metaData = new MetaData.Request(httpMethod, new HttpURI(scheme + "://" + path), HttpVersion.HTTP_1_1, new HttpFields());
    Request req = channel.getRequest();
    req.setMetaData(metaData);

    this.httpResponseCode = responseCode;
    channel.handle();
    return req;
}
 
Example #18
Source File: CustomOpenIdProviderHandler.java    From OpenID-Attacker with GNU General Public License v2.0 5 votes vote down vote up
private void handleRequest(ParameterList requestParameter, String target, HttpServletResponse response, Request baseRequest) throws IOException, OpenIdAttackerServerException, TransformerException {
       // get the openIdProcessor.mode
       final String method = baseRequest.getMethod();
       final HttpURI uri = baseRequest.getUri();
       final String protocol = baseRequest.getProtocol();
       final String info = String.format("%s %s %s", method, uri, protocol);
       final String mode = requestParameter.hasParameter("openid.mode")
         ? requestParameter.getParameterValue("openid.mode") : null;

if (uri.getCompletePath().equals("/favicon.ico")) {
           handleFaviconRequest(info, response);
       } else if (target.contains("xxe")) {
           // Case: XXE
           handleXxeRequest(info, response, requestParameter);
       } /*else if (target.contains("dtd")) {
           // Case: DTD
           handleDtdRequest(info, response, requestParameter);
       }*/ else if (mode == null) {
           if (target.contains("xrds") || requestParameter.toString().contains("xrds")) {
               // Case: Request XRDS Document
               handleXrdsRequest(info, response);                
           } else {
               // Case: Request HTML Document
               handleHtmlDiscovery(info, response);
           }
       } else if ("associate".equals(mode)) {
           // Case: Process Association
           handleAssociationRequest(info, response, requestParameter);
       } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
           // Case: Generate Token
           handleTokenRequest(info, response, requestParameter);
       } else if ("check_authentication".equals(mode)) {
           handleCheckAuthentication(info, response, requestParameter);
       } else {
           throw new IllegalStateException("Unknown Request");
       }
       baseRequest.setHandled(true);
   }
 
Example #19
Source File: TestInvokeHttpCommon.java    From 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);

    authString = request.getHeader("Authorization");

    if (authString == null) {
        response.setStatus(401);
        response.setHeader("WWW-Authenticate", "Basic realm=\"Jetty\"");
        response.setHeader("response.phrase", "Unauthorized");
        response.setContentType("text/plain");
        response.getWriter().println("Get off my lawn!");
        return;
    }

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

    if (status == 200) {
        response.setStatus(status);
        response.setContentType("text/plain");
        response.getWriter().println(authString);
    } else {
        response.setStatus(status);
        response.setContentType("text/plain");
        response.getWriter().println("Get off my lawn!");
    }
}
 
Example #20
Source File: JwtAuthenticatorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testFailedLoginWithUserNotFound() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER_2, SecurityUtils.NO_CREDENTIAL, new String[] {USER_ROLE});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  Authenticator.AuthConfiguration configuration = mock(Authenticator.AuthConfiguration.class);
  expect(configuration.getLoginService()).andReturn(loginService);
  expect(configuration.getIdentityService()).andReturn(new DefaultIdentityService());
  expect(configuration.isSessionRenewedOnAuthentication()).andReturn(true);

  Request request = niceMock(Request.class);
  expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
  expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
  request.setAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE, tokenAndKeys.token());
  expectLastCall().andVoid();
  expect(request.getCookies()).andReturn(new Cookie[] {new Cookie(JWT_TOKEN, tokenAndKeys.token())});
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  HttpServletResponse response = mock(HttpServletResponse.class);
  response.setStatus(HttpStatus.UNAUTHORIZED_401);
  expectLastCall().andVoid();

  replay(configuration, request, response);
  JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);
  authenticator.setConfiguration(configuration);
  Authentication authentication = authenticator.validateRequest(request, response, true);
  verify(configuration, request, response);

  assertNotNull(authentication);
  assertEquals(Authentication.SEND_FAILURE, authentication);
}
 
Example #21
Source File: TestInvokeHTTP.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) {
    baseRequest.setHandled(true);
    response.setStatus(200);
    response.setContentLength(0);
    response.setContentType("text/plain");
    response.setHeader("Content-Encoding", "gzip");
}
 
Example #22
Source File: TestInvokeAWSGatewayApiCommon.java    From 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);

    if ("DELETE".equalsIgnoreCase(request.getMethod())) {
        final int status = Integer.valueOf(target.substring("/status".length() + 1));
        response.setStatus(status);
        response.setContentLength(0);
    } else {
        response.setStatus(404);
        response.setContentType("text/plain");
        response.setContentLength(0);
    }
}
 
Example #23
Source File: V3MockParsingRequestHandler.java    From vespa with Apache License 2.0 5 votes vote down vote up
private void dontAcceptVersion(Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
    String sessionId = getSessionId(request);
    setHeaders(response, sessionId);
    response.setStatus(Headers.HTTP_NOT_ACCEPTABLE);
    baseRequest.setHandled(true);
    PrintWriter responseWriter = response.getWriter();
    responseWriter.write("Go away, no such version.");
    responseWriter.flush();
    closeChannel(responseWriter);
}
 
Example #24
Source File: PatternConverterTest.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    // Create mock objects
    mockRequest = mock(Request.class);
    mockResponse = mock(Response.class);
    when(mockRequest.getMethod()).thenReturn(METHOD);
    when(mockRequest.getRequestURI()).thenReturn(URI);
    when(mockRequest.getQueryString()).thenReturn(QUERY);
    when(mockRequest.getProtocol()).thenReturn(PROTOCOL);
    when(mockRequest.getRemoteHost()).thenReturn(REMOTE_HOST);
    when(mockResponse.getStatus()).thenReturn(STATUS);
    when(mockResponse.getContentCount()).thenReturn(CONTENT_LENGTH);
    when(mockRequest.getTimeStamp()).thenReturn(REQUEST_TIME);
    when(mockRequest.getHeaderNames()).thenReturn(Collections.enumeration((HEADERS.keySet())));
    when(mockRequest.getHeader(anyString())).thenAnswer(invocation -> HEADERS.get(invocation.getArguments()[0]));

    // Static mocks
    mockStatic(System.class);
    when(System.currentTimeMillis()).thenReturn(RESPONSE_TIME);

    // Create actual objects
    contentLengthConverter = ContentLengthPatternConverter.newInstance(null);
    elapsedTimeConverter = ElapsedTimePatternConverter.newInstance(null);
    remoteHostConverter = RemoteHostPatternConverter.newInstance(null);
    requestHeaderConverter = RequestHeaderPatternConverter.newInstance(null);
    requestHeaderCaseConverter = RequestHeaderPatternConverter.newInstance(new String[] {HEADER_KEY1.toUpperCase() });
    requestHeaderNAConverter = RequestHeaderPatternConverter.newInstance(new String[] { NON_EXISTING_HEADER });
    requestLineConverter = RequestLinePatternConverter.newInstance(null);
    statusCodePatternConverter = StatusCodePatternConverter.newInstance(null);
    logEvent = new Log4jLogEvent.Builder().setMessage(new AccessLog(mockRequest, mockResponse)).build();
    noLogEvent = new Log4jLogEvent.Builder().setMessage(new SimpleMessage()).build();
}
 
Example #25
Source File: TestInvokeHttpCommon.java    From 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);

    if ("DELETE".equalsIgnoreCase(request.getMethod())) {
        final int status = Integer.valueOf(target.substring("/status".length() + 1));
        response.setStatus(status);
        response.setContentLength(0);
    } else {
        response.setStatus(404);
        response.setContentType("text/plain");
        response.setContentLength(0);
    }
}
 
Example #26
Source File: SlaManagerTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private AbstractHandler mockCoordinatorResponses(String mockResponse) {
  return new AbstractHandler() {
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
      createResponse(baseRequest, response, mockResponse);
    }
  };
}
 
Example #27
Source File: HttpServer.java    From smslib-v3 with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
	if (request.getPathInfo().toString().equals("/")) new Status(getSMSServer(), target, request, response).process();
	else if (request.getPathInfo().toString().equals("/status")) new Status(getSMSServer(), target, request, response).process();
	else if (request.getPathInfo().toString().equals("/send")) new Send(getSMSServer(), target, request, response).process();
	else if (request.getPathInfo().toString().equals("/read")) new Read(getSMSServer(), target, request, response).process();
}
 
Example #28
Source File: AbstractSamlAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Authentication register(Request request, SamlSession samlSession) {
    Authentication authentication = request.getAuthentication();
    if (!(authentication instanceof KeycloakAuthentication)) {
        UserIdentity userIdentity = createIdentity(samlSession);
        authentication = createAuthentication(userIdentity, request);
        request.setAuthentication(authentication);
    }
    return authentication;
}
 
Example #29
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 #30
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();
        }
    }

}