Java Code Examples for org.eclipse.jetty.server.Request

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /http-server/src/test/java/io/airlift/http/server/.

Source file: TestDelimitedRequestLog.java

  26 
vote

@Test public void testNoXForwardedProto() throws Exception {
  final Request request=mock(Request.class);
  final Response response=mock(Response.class);
  final String protocol="protocol";
  when(request.getScheme()).thenReturn("protocol");
  InMemoryEventClient eventClient=new InMemoryEventClient();
  DelimitedRequestLog logger=new DelimitedRequestLog(file.getAbsolutePath(),1,null,eventClient);
  logger.log(request,response);
  logger.stop();
  List<Object> events=eventClient.getEvents();
  Assert.assertEquals(events.size(),1);
  HttpRequestEvent event=(HttpRequestEvent)events.get(0);
  Assert.assertEquals(event.getProtocol(),protocol);
}
 

Example 2

From project platform_3, under directory /http-server/src/test/java/com/proofpoint/http/server/.

Source file: TestDelimitedRequestLog.java

  26 
vote

@Test public void testNoXForwardedProto() throws Exception {
  final Request request=mock(Request.class);
  final Response response=mock(Response.class);
  final String protocol="protocol";
  when(request.getScheme()).thenReturn("protocol");
  InMemoryEventClient eventClient=new InMemoryEventClient();
  DelimitedRequestLog logger=new DelimitedRequestLog(file.getAbsolutePath(),1,null,eventClient);
  logger.log(request,response);
  logger.stop();
  List<Object> events=eventClient.getEvents();
  Assert.assertEquals(events.size(),1);
  HttpRequestEvent event=(HttpRequestEvent)events.get(0);
  Assert.assertEquals(event.getProtocol(),protocol);
}
 

Example 3

From project components-ness-httpserver_1, under directory /src/test/java/com/nesscomputing/httpserver/log/file/.

Source file: FileRequestLogTest.java

  25 
vote

@Test public void testRequestLogging(){
  final Config config=Config.getFixedConfig("ness.httpserver.request-log.file.enabled","true","ness.httpserver.request-log.file.fields","remoteAddr,cookie:trumpet-json-api-authorization,cookie:not-here,method,requestUri,query,responseCode,responseHeader:Content-Length,elapsedTime");
  final Injector inj=Guice.createInjector(Stage.PRODUCTION,disableStuff(),new LogFieldsModule(),new FileRequestLogModule(config));
  inj.injectMembers(this);
  Assert.assertNotNull(fileRequestLog);
  StringWriter buffer=new StringWriter();
  fileRequestLog.setWriter(new PrintWriter(buffer));
  Request req=createMock(Request.class);
  Response resp=createMock(Response.class);
  expect(req.getRemoteAddr()).andReturn("1.2.3.4").anyTimes();
  Cookie[] cookies={new Cookie("trumpet-JSON-api-AUTHORIZATION","omgwtfbbq")};
  expect(req.getCookies()).andReturn(cookies).anyTimes();
  expect(req.getMethod()).andReturn("GET").anyTimes();
  expect(req.getRequestURI()).andReturn("foo").anyTimes();
  expect(req.getRequestURL()).andReturn(new StringBuffer("foo")).anyTimes();
  expect(req.getQueryString()).andReturn("?bar").anyTimes();
  expect(req.getTimeStamp()).andReturn(10000L).anyTimes();
  expect(resp.getStatus()).andReturn(201).anyTimes();
  expect(resp.getHeader("Content-Length")).andReturn("42").anyTimes();
  replayAll();
  DateTimeUtils.setCurrentMillisFixed(11500);
  fileRequestLog.log(req,resp);
  assertEquals("1.2.3.4\tomgwtfbbq\t\tGET\tfoo\t?bar\t201\t42\t1500\n",buffer.getBuffer().toString());
  verifyAll();
}
 

Example 4

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-intents/easysoa-proxy-intents-fuseIntent/src/main/java/org/easysoa/sca/intents/.

Source file: AutoRearmFuseIntent.java

  25 
vote

/** 
 * Implementation of the IntentHandler interface
 * @see org.ow2.frascati.tinfi.control.intent.IntentHandler#invoke(IntentJoinPoint)
 */
public Object invoke(IntentJoinPoint ijp) throws Throwable {
  Object ret;
  Request request=null;
  if (ijp.getArguments().length >= 2) {
    if (ijp.getArguments()[1] instanceof org.eclipse.jetty.server.Request) {
      request=(org.eclipse.jetty.server.Request)(ijp.getArguments()[1]);
    }
  }
  try {
    checkFuseConditions();
  }
 catch (  ServiceUnavailableException ex) {
    if (request != null && !request.getResponse().isCommitted()) {
      request.getResponse().sendError(500,ex.getMessage());
    }
  }
  ret=ijp.proceed();
  return ret;
}
 

Example 5

From project eventtracker, under directory /http/src/test/java/com/ning/metrics/eventtracker/.

Source file: TestHttpSender.java

  25 
vote

@BeforeClass(alwaysRun=true) public void setUpGlobal() throws Exception {
  final int port=findFreePort();
  server=new Server(port);
  errorServer=new Server(port){
    @Override public void handle(    final AbstractHttpConnection connection) throws IOException, ServletException {
      final String target=connection.getRequest().getPathInfo();
      final Request request=connection.getRequest();
      final Response response=connection.getResponse();
      response.setStatus(404);
      handle(target,request,request,response);
    }
  }
;
  System.setProperty("eventtracker.collector.port",Integer.toString(port));
  final EventTrackerConfig config=new ConfigurationObjectFactory(System.getProperties()).build(EventTrackerConfig.class);
  sender=new HttpSender(config.getCollectorHost(),config.getCollectorPort(),config.getEventType(),config.getHttpMaxWaitTimeInMillis(),config.getHttpMaxKeepAlive().getMillis(),10);
  failureCallbackHandler=new CallbackHandler(){
    @Override public void onError(    final Throwable t,    final File event){
      logger.debug("Got error (good): " + t.getMessage());
    }
    @Override public void onSuccess(    final File event){
      Assert.fail("Got success when we were expecting failure. Uh oh.");
    }
  }
;
  successCallbackHandler=new CallbackHandler(){
    @Override public void onError(    final Throwable t,    final File event){
      Assert.fail("Got error (bad!): ",t);
    }
    @Override public void onSuccess(    final File event){
      logger.debug("Got success. Yay.");
    }
  }
;
  Assert.assertTrue(eventsFile.createNewFile());
  final FileWriter writer=new FileWriter(eventsFile);
  writer.write("{ \"eventName\":\"Hello\", \"payload\": { \"dontcare\": \"World\" } }");
  writer.close();
}
 

Example 6

From project rest-driver, under directory /rest-client-driver/src/test/java/com/github/restdriver/clientdriver/unit/.

Source file: ClientDriverHandlerTest.java

  25 
vote

/** 
 * with no expectations set, and a request made, the handler throws an error upon verification
 */
@Test public void testUnexpectedRequest() throws IOException, ServletException {
  Request mockRequest=mock(Request.class);
  HttpServletRequest mockHttpRequest=mock(HttpServletRequest.class);
  HttpServletResponse mockHttpResponse=mock(HttpServletResponse.class);
  when(mockHttpRequest.getMethod()).thenReturn("POST");
  when(mockHttpRequest.getPathInfo()).thenReturn("yarr");
  when(mockHttpRequest.getQueryString()).thenReturn("gooo=gredge");
  when(mockHttpRequest.getInputStream()).thenReturn(new DummyServletInputStream(IOUtils.toInputStream("")));
  try {
    sut.handle("",mockRequest,mockHttpRequest,mockHttpResponse);
    Assert.fail();
  }
 catch (  ClientDriverInternalException e) {
    assertThat(e.getMessage(),equalTo("Unexpected request: POST yarr?gooo=gredge"));
  }
  try {
    sut.checkForUnexpectedRequests();
    Assert.fail();
  }
 catch (  ClientDriverFailedExpectationException e) {
    assertThat(e.getMessage(),equalTo("Unexpected request: POST yarr?gooo=gredge"));
  }
}
 

Example 7

From project aether-core, under directory /aether-connector-asynchttpclient/src/test/java/org/eclipse/aether/connector/async/.

Source file: ResumeGetTest.java

  23 
vote

public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException {
  Integer attempts=madeRequests.get(target);
  attempts=(attempts == null) ? Integer.valueOf(1) : Integer.valueOf(attempts.intValue() + 1);
  madeRequests.put(target,attempts);
  if (attempts.intValue() > requiredRequests) {
    response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
    response.flushBuffer();
    return;
  }
  int lb=0, ub=totalSize - 1;
  String range=request.getHeader("Range");
  if (range != null && range.matches(RANGE.pattern())) {
    Matcher m=RANGE.matcher(range);
    m.matches();
    lb=Integer.parseInt(m.group(1));
  }
  response.setStatus((lb > 0) ? HttpURLConnection.HTTP_PARTIAL : HttpURLConnection.HTTP_OK);
  response.setContentLength(totalSize - lb);
  response.setContentType("Content-type: text/plain; charset=UTF-8");
  if (lb > 0) {
    response.setHeader("Content-Range","bytes " + lb + "-"+ ub+ "/"+ totalSize);
  }
  response.flushBuffer();
  OutputStream out=response.getOutputStream();
  for (int i=lb, j=0; i <= ub; i++, j++) {
    if (j >= chunkSize) {
      out.flush();
      throw new IOException("oups, we're dead");
    }
    out.write(CONTENT_PATTERN[i % CONTENT_PATTERN.length]);
  }
  out.close();
}
 

Example 8

From project BeeQueue, under directory /src/org/beequeue/buzz/.

Source file: BuzzContext.java

  23 
vote

public BuzzContext(String target,Request r,HttpServletRequest req,HttpServletResponse res,BuzzHandler handler){
  this.target=target;
  this.r=r;
  this.req=req;
  this.res=res;
  this.handler=handler;
  this.resoursePath=BuzzPath.valueOf(target.substring(1));
  this.ancestor=this.resoursePath.findAncestor(handler.rcConfigs.keySet());
  System.out.println(target);
}
 

Example 9

From project cometd, under directory /cometd-java/cometd-java-examples/src/main/java/org/cometd/benchmark/.

Source file: BayeuxLoadServer.java

  23 
vote

@Override public void handle(String target,Request request,final HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws IOException, ServletException {
  final long requestId=requestIds.incrementAndGet();
  final AtomicBoolean longRequest=new AtomicBoolean(false);
  final Thread thread=Thread.currentThread();
  ScheduledFuture<?> task=scheduler.scheduleWithFixedDelay(new Runnable(){
    public void run(){
      longRequest.set(true);
      onLongRequestDetected(requestId,httpRequest,thread);
    }
  }
,maxRequestTime,maxRequestTime,TimeUnit.MILLISECONDS);
  long start=System.nanoTime();
  try {
    super.handle(target,request,httpRequest,httpResponse);
  }
  finally {
    long end=System.nanoTime();
    task.cancel(false);
    if (longRequest.get()) {
      onLongRequestEnded(requestId,end - start);
    }
  }
}
 

Example 10

From project components-ness-httpclient, under directory /client/src/test/java/com/nesscomputing/httpclient/.

Source file: TestObserverExtension.java

  23 
vote

@Override public void handle(String target,Request request,HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws IOException, ServletException {
  httpResponse.setContentType("text/plain");
  httpResponse.setStatus(HttpServletResponse.SC_OK);
  final String header=httpRequest.getHeader("X-Observed");
  Assert.assertNotNull(header);
  httpResponse.addHeader("X-Observed",header);
  request.setHandled(true);
  final PrintWriter writer=httpResponse.getWriter();
  writer.print("blah");
  writer.flush();
}
 

Example 11

From project components-ness-tracking, under directory /src/test/java/com/nesscomputing/tracking/adapters/.

Source file: GenericTrackingTestHandler.java

  23 
vote

@SuppressWarnings("unchecked") @Override public void handle(final String target,final Request request,final HttpServletRequest httpRequest,final HttpServletResponse httpResponse) throws IOException, ServletException {
  final ServletApiAdapter adapter=new ServletApiAdapter(httpRequest);
  token=trackingManager.get(adapter);
  log.info("Received Tracking Token: '%s'",token);
  method=request.getMethod();
  httpResponse.setContentType(contentType);
  httpResponse.setStatus(HttpServletResponse.SC_OK);
  for (  final HttpClientHeader header : headers) {
    httpResponse.addHeader(header.getName(),header.getValue());
  }
  for (Enumeration<String> e=request.getHeaderNames(); e.hasMoreElements(); ) {
    String headerName=e.nextElement();
    List<HttpClientHeader> headers=reqHeaders.get(headerName);
    if (headers == null) {
      headers=new ArrayList<HttpClientHeader>();
      reqHeaders.put(headerName,headers);
    }
    for (Enumeration<String> v=request.getHeaders(headerName); v.hasMoreElements(); ) {
      String headerValue=v.nextElement();
      HttpClientHeader header=new HttpClientHeader(headerName,headerValue);
      headers.add(header);
    }
  }
  cookies=request.getCookies();
  request.setHandled(true);
  final PrintWriter writer=httpResponse.getWriter();
  writer.print(content);
  writer.flush();
}
 

Example 12

From project Eclipse, under directory /com.mobilesorcery.sdk.html5/src/com/mobilesorcery/sdk/html5/live/.

Source file: JSODDServer.java

  23 
vote

@Override public void handle(String target,Request baseRequest,HttpServletRequest req,HttpServletResponse res) throws IOException {
  try {
    if (CoreMoSyncPlugin.getDefault().isDebugging()) {
      CoreMoSyncPlugin.trace("{3}: STARTED {0} REQUEST {1} ON THREAD {2}",req.getMethod(),target,Thread.currentThread().getName(),new Date().toString());
    }
    boolean preflight="OPTIONS".equals(req.getMethod());
    ReloadVirtualMachine vm=getVM(req.getRemoteAddr());
    if (vm != null && vm.getCurrentSessionId() != NO_SESSION) {
      queues.heartbeat(vm.getCurrentSessionId());
    }
    configureForPreflight(req,res);
    JSONObject command=preflight || !targetMatches(target,"/mobile/") || targetMatches(target,"/mobile/incoming") ? null : parseCommand(req);
    Object result=handleFetch(target,req,res);
    if (result == null) {
      result=handleCommand(target,command,req,res,preflight);
    }
    if (result == null) {
      result=waitForClient(target,command,req,res,preflight);
    }
    if (result != null) {
      if (CoreMoSyncPlugin.getDefault().isDebugging()) {
        CoreMoSyncPlugin.trace("SEND ({0}): {1}",target,result);
      }
      writeResponse(result,res);
    }
    if (CoreMoSyncPlugin.getDefault().isDebugging()) {
      CoreMoSyncPlugin.trace("{3}: FINISHED {0} REQUEST {1} ON THREAD {2}",req.getMethod(),target,Thread.currentThread().getName(),new Date().toString());
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
    throw new IOException(e);
  }
}
 

Example 13

From project elasticsearch-jetty, under directory /src/main/java/com/sonian/elasticsearch/http/jetty/error/.

Source file: JettyHttpServerErrorHandler.java

  23 
vote

@Override public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException {
  AbstractHttpConnection connection=AbstractHttpConnection.getCurrentConnection();
  connection.getRequest().setHandled(true);
  String method=request.getMethod();
  response.setContentType(MimeTypes.TEXT_PLAIN_8859_1);
  ByteArrayISO8859Writer writer=new ByteArrayISO8859Writer(4096);
  writer.write(request.getAttribute(Dispatcher.ERROR_STATUS_CODE) + " " + request.getAttribute(Dispatcher.ERROR_MESSAGE)+ " "+ request.getAttribute(Dispatcher.ERROR_REQUEST_URI));
  writer.flush();
  response.setContentLength(writer.size());
  writer.writeTo(response.getOutputStream());
  writer.destroy();
}
 

Example 14

From project http-testing-harness, under directory /server-provider/src/main/java/org/sonatype/tests/http/server/jetty/impl/.

Source file: FixedDigestAuthenticator.java

  23 
vote

public String newNonce(Request request){
  long ts=request.getTimeStamp();
  long sk=_nonceSecret;
  byte[] nounce=new byte[24];
  for (int i=0; i < 8; i++) {
    nounce[i]=(byte)(ts & 0xff);
    ts=ts >> 8;
    nounce[8 + i]=(byte)(sk & 0xff);
    sk=sk >> 8;
  }
  byte[] hash=null;
  try {
    MessageDigest md=MessageDigest.getInstance("MD5");
    md.reset();
    md.update(nounce,0,16);
    hash=md.digest();
  }
 catch (  Exception e) {
    Log.warn(e);
  }
  for (int i=0; i < hash.length; i++) {
    nounce[8 + i]=hash[i];
    if (i == 23) {
      break;
    }
  }
  return new String(B64Code.encode(nounce));
}
 

Example 15

From project https-utils, under directory /src/main/java/org/italiangrid/utils/examples/.

Source file: PrintAuthenticationInformationHandler.java

  23 
vote

public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  response.setContentType("text/html;charset=utf-8");
  response.setStatus(HttpServletResponse.SC_OK);
  baseRequest.setHandled(true);
  VOMSSecurityContext sc=VOMSSecurityContext.getCurrentContext();
  response.getWriter().println("<h1>Hello!</h1>");
  BigInteger sn=sc.getClientCert().getSerialNumber();
  String serialNumber=(sn == null) ? "NULL" : sn.toString();
  String[] fqans=sc.getFQANs();
  String vomsFQANString="No VOMS attributes found.";
  if (fqans.length > 0)   vomsFQANString=String.format("VOMS attributes: %s .",StringUtils.join(fqans,","));
  String connectionMessage=String.format("<p>You connected from '%s', as '%s' (issued by '%s') serial: %s.</p><p>%s</p>",request.getRemoteAddr(),sc.getClientDN().getRFCDNv2(),sc.getIssuerDN().getRFCDNv2(),serialNumber,vomsFQANString);
  response.getWriter().println(connectionMessage);
}
 

Example 16

From project iJetty, under directory /i-jetty/i-jetty-ui/src/org/mortbay/ijetty/handler/.

Source file: DefaultHandler.java

  23 
vote

public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  if (response.isCommitted() || baseRequest.isHandled()) {
    return;
  }
  baseRequest.setHandled(true);
  String method=request.getMethod();
  if (!method.equals(HttpMethods.GET) || !request.getRequestURI().equals("/")) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
  }
  response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  response.setContentType(MimeTypes.TEXT_HTML);
  String uri=request.getRequestURI();
  uri=StringUtil.replace(uri,"<","&lt;");
  uri=StringUtil.replace(uri,">","&gt;");
  ByteArrayISO8859Writer writer=new ByteArrayISO8859Writer(1500);
  createHtml(request,writer);
  response.setContentLength(writer.size());
  OutputStream out=response.getOutputStream();
  writer.writeTo(out);
  out.close();
}
 

Example 17

From project jena-fuseki, under directory /src/main/java/org/apache/jena/fuseki/server/.

Source file: FusekiErrorHandler.java

  23 
vote

@Override public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException {
  HttpConnection connection=HttpConnection.getCurrentConnection();
  connection.getRequest().setHandled(true);
  String method=request.getMethod();
  if (!method.equals(HttpMethods.GET) && !method.equals(HttpMethods.POST) && !method.equals(HttpMethods.HEAD))   return;
  response.setContentType(MimeTypes.TEXT_PLAIN_UTF_8);
  response.setHeader(HttpHeaders.CACHE_CONTROL,"must-revalidate,no-cache,no-store");
  ByteArrayOutputStream bytes=new ByteArrayOutputStream(1024);
  Writer writer=new OutputStreamWriter(bytes,"UTF-8");
  handleErrorPage(request,writer,connection.getResponse().getStatus(),connection.getResponse().getReason());
  if (!Fuseki.VERSION.equalsIgnoreCase("development")) {
    writer.write("\n");
    writer.write("\n");
    writer.write(format("Fuseki - version %s (Build date: %s)\n",Fuseki.VERSION,Fuseki.BUILD_DATE));
  }
  writer.flush();
  response.setContentLength(bytes.size());
  response.getOutputStream().write(bytes.toByteArray());
  writer.close();
}
 

Example 18

From project jetty-project, under directory /jetty-integration-tests/src/test/java/org/mortbay/jetty/integration/ssl/.

Source file: SSLContextTest.java

  23 
vote

public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  PrintWriter out=response.getWriter();
  try {
    out.print(HELLO_WORLD);
  }
  finally {
    out.close();
  }
}
 

Example 19

From project jspwiki, under directory /tests/org/apache/wiki/web/.

Source file: TestContainer.java

  23 
vote

public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  if (request.getRequestURI().indexOf(SHUTDOWN_CMD) != -1) {
    log.error("stop cmd received, shutting down server");
    System.exit(0);
  }
 else {
    log.error("ignoring request " + request.getRequestURI());
  }
}
 

Example 20

From project JukeBukkit, under directory /src/main/java/cc/thedudeguy/jukebukkit/server/.

Source file: MusicHandler.java

  23 
vote

@Override public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  Debug.debug("Attempting to handle a music uri");
  if (target.startsWith("/music/")) {
    Debug.debug("URI is a music URI");
    super.handle(target,baseRequest,request,response);
  }
 else {
    baseRequest.setHandled(false);
    return;
  }
}
 

Example 21

From project logback, under directory /logback-access/src/main/java/ch/qos/logback/access/jetty/.

Source file: RequestLogImpl.java

  23 
vote

public void log(Request jettyRequest,Response jettyResponse){
  JettyServerAdapter adapter=new JettyServerAdapter(jettyRequest,jettyResponse);
  IAccessEvent accessEvent=new AccessEvent(jettyRequest,jettyResponse,adapter);
  if (getFilterChainDecision(accessEvent) == FilterReply.DENY) {
    return;
  }
  aai.appendLoopOnAppenders(accessEvent);
}
 

Example 22

From project Metamorphosis, under directory /metamorphosis-server-wrapper/src/main/java/com/taobao/metamorphosis/http/processor/.

Source file: MetamorphosisOnJettyProcessor.java

  23 
vote

@Override public void handle(final String target,final Request jettyRequest,final HttpServletRequest request,final HttpServletResponse response) throws IOException, ServletException {
  if (target.length() < 2) {
    response.setStatus(HttpStatus.BadRequest);
    response.getWriter().write("Invalid request");
  }
 else {
    final char command=target.charAt(1);
switch (command) {
case 'g':
      this.getMessage(jettyRequest,response);
    break;
case 'p':
  this.putMessage(jettyRequest,response);
break;
case 'o':
this.getOffset(jettyRequest,response);
break;
default :
response.setStatus(HttpStatus.BadRequest);
response.getWriter().write("Invalid request");
break;
}
}
response.flushBuffer();
}
 

Example 23

From project meteo, under directory /core/src/main/java/com/ning/metrics/meteo/publishers/.

Source file: ResmonPublisher.java

  23 
vote

public ResmonPublisher() throws Exception {
  Handler handler=new AbstractHandler(){
    public void handle(    String target,    HttpServletRequest request,    HttpServletResponse response,    int dispatch) throws IOException, ServletException {
    }
    /** 
 * Handle a request.
 * @param target      The target of the request - either a URI or a name.
 * @param baseRequest The original unwrapped request object.
 * @param request     The request either as the {@link org.eclipse.jetty.server.Request}object or a wrapper of that request. The  {@link org.eclipse.jetty.server.HttpConnection#getCurrentConnection()}method can be used access the Request object if required.
 * @param response    The response as the {@link org.eclipse.jetty.server.Response}object or a wrapper of that request. The  {@link org.eclipse.jetty.server.HttpConnection#getCurrentConnection()}method can be used access the Response object if required.
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
    @Override public void handle(    String target,    Request baseRequest,    HttpServletRequest request,    HttpServletResponse response) throws IOException, ServletException {
      response.setContentType("text/xml; encoding=UTF-8");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println(writeResmon());
      ((Request)request).setHandled(true);
    }
  }
;
  Server server=new Server(8083);
  server.setHandler(handler);
  server.start();
}
 

Example 24

From project nexus-p2-repository-plugin, under directory /src/test/java/org/sonatype/nexus/plugins/p2/repository/its/nxcm2812/.

Source file: NXCM2812UseCachedMetadataWhenProxyIsUnavailableIT.java

  23 
vote

private void replaceProxy() throws Exception {
  final Handler handler=proxyServer.getServer().getHandler();
  proxyServer.stop();
  proxyServer.getServer().setHandler(new AbstractHandler(){
    @Override public void handle(    String target,    Request baseRequest,    HttpServletRequest request,    HttpServletResponse response) throws IOException, ServletException {
      for (      final String path : P2Constants.METADATA_FILE_PATHS) {
        if (target.endsWith(path)) {
          response.sendError(503);
          return;
        }
      }
      handler.handle(target,baseRequest,request,response);
    }
  }
);
  proxyServer.start();
}
 

Example 25

From project OpenConext-api, under directory /coin-api-war/src/test/java/nl/surfnet/coin/selenium/.

Source file: Oauth20AuthorizationGrantTestSelenium.java

  23 
vote

@Before public void startServer(){
  LOG.debug("Starting server for catching authorization code...");
  server=new MockHtppServer(8083){
    protected MockHandler createHandler(    Server server){
      return new MockHandler(server){
        @Override public void handle(        String target,        Request baseRequest,        HttpServletRequest request,        HttpServletResponse response) throws IOException, ServletException {
          if (request.getRequestURI().contains("favicon")) {
            LOG.debug("ignoring favicon-request.");
            return;
          }
          LOG.debug("Request to mock http server: {}",request);
          authorizationCode=new Verifier(request.getParameter("code"));
          response.setStatus(200);
        }
      }
;
    }
  }
;
  server.startServer();
}
 

Example 26

From project org.ops4j.pax.url, under directory /pax-url-aether/src/test/java/amazon/.

Source file: RepoHandler.java

  23 
vote

public void handle(final String target,final Request baseRequest,final HttpServletRequest request,final HttpServletResponse response) throws IOException, ServletException {
  log.info("request : " + baseRequest);
  Assert.assertEquals("this should work in https only",baseRequest.getScheme(),"https");
  Assert.assertEquals("username and password should be injected as a header",request.getHeader("User-Agent"),"magic-token");
  final String text="hello there";
  response.getWriter().println(text);
  response.setContentType("text/html");
  response.setStatus(HttpServletResponse.SC_OK);
  baseRequest.setHandled(true);
}
 

Example 27

From project org.ops4j.pax.web, under directory /pax-web-jetty/src/main/java/org/ops4j/pax/web/service/jetty/internal/.

Source file: HttpServiceRequestWrapper.java

  23 
vote

/** 
 * Constructs a request object wrapping the given request .
 * @param request original request to be wrapped
 * @throws IllegalArgumentException if the request is null
 */
HttpServiceRequestWrapper(final HttpServletRequest request){
  super(request);
  m_originalRequest=request;
  if (request instanceof Request) {
    m_request=(Request)request;
  }
 else {
    final Object requestAttrValue=request.getAttribute(JETTY_REQUEST_ATTR_NAME);
    if (requestAttrValue != null && requestAttrValue instanceof Request) {
      m_request=(Request)requestAttrValue;
    }
 else {
      m_request=null;
      LOG.debug("HttpService specific authentication is disabled because the ServletRequest object cannot be used, " + "and " + JETTY_REQUEST_ATTR_NAME + " attribute is not set."+ " Expected to be an instance of "+ Request.class.getName()+ " but got "+ m_originalRequest.getClass().getName()+ ".");
    }
  }
}
 

Example 28

From project reef-example-apps, under directory /apps/web-embedded/src/main/java/org/totalgrid/reef/examples/web/embedded/.

Source file: WebEmbedded.java

  23 
vote

public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  response.setContentType("text/html;charset=utf-8");
  response.setStatus(HttpServletResponse.SC_OK);
  baseRequest.setHandled(true);
  response.getWriter().println("<h1>Current Measurements:</h1>");
  try {
    PointService pointService=client.getService(PointService.class);
    List<Model.Point> pointList=pointService.getPoints();
    MeasurementService measurementService=client.getService(MeasurementService.class);
    List<Measurements.Measurement> measurementList=measurementService.getMeasurementsByPoints(pointList);
    response.getWriter().println("<table><tr><th>Measurement</th><th>Value</th><th>Time</th></tr>");
    for (    Measurements.Measurement measurement : measurementList) {
      response.getWriter().println("<tr><td>" + measurement.getName() + "</td><td>"+ buildValueString(measurement)+ "</td><td>"+ new Date(measurement.getTime())+ "</td></tr>");
    }
    response.getWriter().println("</table>");
  }
 catch (  ReefServiceException ex) {
    throw new ServletException(ex);
  }
}
 

Example 29

From project signedrequest4j, under directory /src/test/java/server/.

Source file: BasicHandler.java

  23 
vote

public void _handle(Boolean isAllowed,HttpMethod method,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws Exception {
  boolean isValid=false;
  if (method.equals(HttpMethod.POST)) {
    isValid=SignedRequestVerifier.verifyPOST("http://localhost:8888/",request.getQueryString(),request.getHeader("Authorization"),HttpServerSpec.SINGLETON_CONSUMER,SignatureMethod.HMAC_SHA1,request.getParameterMap());
  }
 else {
    isValid=SignedRequestVerifier.verify("http://localhost:8888/",request.getQueryString(),request.getHeader("Authorization"),HttpServerSpec.SINGLETON_CONSUMER,method,SignatureMethod.HMAC_SHA1);
  }
  if (isAllowed && isValid) {
    response.setStatus(HttpServletResponse.SC_OK);
  }
 else {
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
  }
  response.getWriter().print("");
  baseRequest.setHandled(true);
}
 

Example 30

From project sonatype-aether, under directory /aether-connector-asynchttpclient/src/test/java/org/sonatype/aether/connector/async/.

Source file: ResumeGetTest.java

  23 
vote

public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException {
  Integer attempts=madeRequests.get(target);
  attempts=(attempts == null) ? Integer.valueOf(1) : Integer.valueOf(attempts.intValue() + 1);
  madeRequests.put(target,attempts);
  if (attempts.intValue() > requiredRequests) {
    response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
    response.flushBuffer();
    return;
  }
  int lb=0, ub=totalSize - 1;
  String range=request.getHeader("Range");
  if (range != null && range.matches(RANGE.pattern())) {
    Matcher m=RANGE.matcher(range);
    m.matches();
    lb=Integer.parseInt(m.group(1));
  }
  response.setStatus((lb > 0) ? HttpURLConnection.HTTP_PARTIAL : HttpURLConnection.HTTP_OK);
  response.setContentLength(totalSize - lb);
  response.setContentType("Content-type: text/plain; charset=UTF-8");
  if (lb > 0) {
    response.setHeader("Content-Range","bytes " + lb + "-"+ ub+ "/"+ totalSize);
  }
  response.flushBuffer();
  OutputStream out=response.getOutputStream();
  for (int i=lb, j=0; i <= ub; i++, j++) {
    if (j >= chunkSize) {
      out.flush();
      throw new IOException("oups, we're dead");
    }
    out.write(CONTENT_PATTERN[i % CONTENT_PATTERN.length]);
  }
  out.close();
}
 

Example 31

From project stubby4j, under directory /src/main/java/org/stubby/handlers/.

Source file: AdminHandler.java

  23 
vote

@Override public void handle(final String target,final Request baseRequest,final HttpServletRequest request,final HttpServletResponse response) throws IOException, ServletException {
  baseRequest.setHandled(true);
  response.setContentType(MimeTypes.TEXT_HTML_UTF_8);
  response.setStatus(HttpStatus.OK_200);
  response.setHeader(HttpHeaders.SERVER,HandlerUtils.constructHeaderServerName());
  final AdminRequestHandlingStrategy adminRequestHandlingStrategy=AdminRequestHandlingStrategyFactory.identifyHandlingStrategyFor(request.getPathInfo(),jettyOrchestrator);
  try {
    adminRequestHandlingStrategy.handle(request,response);
  }
 catch (  final Exception ex) {
    HandlerUtils.configureErrorResponse(response,HttpStatus.INTERNAL_SERVER_ERROR_500,ex.toString());
  }
}
 

Example 32

From project testlink-java-api, under directory /src/test/java/br/eti/kinoshita/testlinkjavaapi/.

Source file: HttpTestServer.java

  23 
vote

public Handler getMockHandler(){
  Handler mockHandler=new AbstractHandler(){
    public void handle(    String target,    Request request,    HttpServletRequest httpRequest,    HttpServletResponse httpResponse) throws IOException, ServletException {
      Request baseRequest=HttpConnection.getCurrentConnection().getRequest();
      setResponseBody(getMockResponseBody());
      setRequestBody(IOUtils.toString(baseRequest.getInputStream()));
      httpResponse.setStatus(HttpServletResponse.SC_OK);
      httpResponse.setContentType("text/xml;charset=utf-8");
      httpResponse.getWriter().write(getResponseBody());
      baseRequest.setHandled(true);
    }
  }
;
  return mockHandler;
}
 

Example 33

From project traccar, under directory /src/org/traccar/http/.

Source file: WebServer.java

  23 
vote

public void handleIndex(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  response.setContentType("text/html");
  InputStream in=this.getClass().getClassLoader().getResourceAsStream("web/index.html");
  OutputStream out=response.getOutputStream();
  byte[] buffer=new byte[BUFFER_SIZE];
  int count;
  while ((count=in.read(buffer)) != -1) {
    out.write(buffer,0,count);
  }
  out.flush();
}
 

Example 34

From project turmeric-monitoring, under directory /mgmt-console/src/main/java/org/ebayopensource/turmeric/monitoring/.

Source file: Main.java

  23 
vote

/** 
 * Handle.
 * @param target the target
 * @param baseRequest the base request
 * @param request the request
 * @param response the response
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ServletException the servlet exception
 * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,org.eclipse.jetty.server.Request,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
 */
public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
  response.setContentType("text/html;charset=utf-8");
  response.setStatus(HttpServletResponse.SC_OK);
  baseRequest.setHandled(true);
  String tmp=request.getParameter("X-TURMERIC-SERVICE-NAME");
  if ("SOAMetricsQueryService".equals(tmp)) {
    tmp=request.getParameter("X-TURMERIC-OPERATION-NAME");
    if ("getMetricsData".equals(tmp)) {
      response.getOutputStream().write(GET_METRICS_DATA_JSON.getBytes());
    }
  }
}
 

Example 35

From project tycho, under directory /tycho-bundles/org.eclipse.tycho.test.utils/src/main/java/org/eclipse/tycho/test/util/.

Source file: AbstractMonitorServlet.java

  23 
vote

@Override public final void service(ServletRequest request,ServletResponse response) throws ServletException, IOException {
  HttpServletRequest req=(HttpServletRequest)request;
  HttpServletResponse res=(HttpServletResponse)response;
  String uri=((Request)req).getUri().toString();
  if (!uri.endsWith(".sha1") && !uri.endsWith(".md5")) {
    accessedUrls.add(uri);
  }
  service(req,res);
}
 

Example 36

From project zen-project, under directory /zen-webservice/src/main/java/com/nominanuda/web/http/.

Source file: BaseHttpTest.java

  23 
vote

protected Server startServer(int port,final Handler h) throws Exception {
  Server srv=new Server(port);
  srv.setHandler(new AbstractHandler(){
    public void handle(    String target,    Request baseRequest,    HttpServletRequest request,    HttpServletResponse response) throws IOException, ServletException {
      h.handle(target,baseRequest,request,response);
      baseRequest.setHandled(true);
    }
  }
);
  srv.start();
  return srv;
}