Example usage for org.apache.http.protocol ResponseContent ResponseContent

List of usage examples for org.apache.http.protocol ResponseContent ResponseContent

Introduction

In this page you can find the example usage for org.apache.http.protocol ResponseContent ResponseContent.

Prototype

public ResponseContent() 

Source Link

Usage

From source file:com.ultrahook.test.utils.TestServer.java

public void start() throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/*from   ww w .  ja  va 2s. c  o m*/
    UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
    reqistry.register("*", new HttpHandler());
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry);
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000)
            .setConnectTimeout(3000).build();
    ioReactor = new DefaultListeningIOReactor(config);
    ioReactor.listen(new InetSocketAddress(port));
    new Thread() {
        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException e) {
                e.printStackTrace();
            } catch (IOReactorException e) {
                e.printStackTrace();
            }
        };

    }.start();
}

From source file:NioHttpServer.java

public NioHttpServer(int port, // TCP port for the server.
        HttpRequestHandler request_responder, // Scheme level responder for HTTP requests from clients.
        EventListener connection_listener) throws Exception {

    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    BufferingHttpServiceHandler service_handler = new BufferingHttpServiceHandler(httpproc,
            new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params);

    // Set up request handlers
    HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
    reqistry.register("*", request_responder);

    service_handler.setHandlerResolver(reqistry);

    service_handler.setEventListener(connection_listener); // Provide a connection listener.

    // Use two worker threads for the IO reactor.
    io_reactor = new DefaultListeningIOReactor(2, params);
    io_event_dispatch = new DefaultServerIOEventDispatch(handler, params);
    this.port = port; // Set the listening TCP port.
}

From source file:com.bluetooth.activities.WiFiControl.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wifi_control);

    SERVERIP = getLocalIpAddress();//from w w  w  . j a  v a2  s .  com

    httpContext = new BasicHttpContext();

    httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory());

    registry = new HttpRequestHandlerRegistry();
    registry.register(ALL_PATTERN, new RequestHandler());

    httpService.setHandlerResolver(registry);

    tvData = (LogView) findViewById(R.id.tvData);
    tvIP = (TextView) findViewById(R.id.tvIP);
    bToggle = (Button) findViewById(R.id.bToggle);
    log = "";
}

From source file:org.cytoscape.app.internal.net.server.CyHttpdFactoryImpl.java

public CyHttpdImpl(final ServerSocketFactory serverSocketFactory) {
    if (serverSocketFactory == null)
        throw new IllegalArgumentException("serverSocketFactory == null");
    this.serverSocketFactory = serverSocketFactory;

    // Setup params

    params = (new SyncBasicHttpParams()).setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    // Setup service

    final HttpProcessor proc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(),
            new ResponseServer(), new ResponseContent(), new ResponseConnControl() });

    final HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("*", new RequestHandlerDispatcher());

    service = new HttpService(proc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(),
            registry, params);/*from w w  w. ja va 2  s . c o m*/
}

From source file:it.danja.newsmonitor.utils.HttpServer.java

public void init() {

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();//from w  w  w.j  a va  2  s. c  o  m

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpFileHandler(docRoot));

    // Set up the HTTP service
    httpService = new HttpService(httpproc, reqistry);

    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            log.info("HttpServer : Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = null;
        try {
            keystore = KeyStore.getInstance("jks");
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        }
        try {
            keystore.load(url.openStream(), "secret".toCharArray());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        } catch (CertificateException e) {

            log.error(e.getMessage());
        } catch (IOException e) {

            log.error(e.getMessage());
        }
        KeyManagerFactory kmfactory = null;
        try {
            kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            kmfactory.init(keystore, "secret".toCharArray());
        } catch (UnrecoverableKeyException e) {

            log.error(e.getMessage());
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            sslcontext.init(keymanagers, null, null);
        } catch (KeyManagementException e) {

            log.error(e.getMessage());
        }
        this.sf = sslcontext.getServerSocketFactory();
    }
}

From source file:org.devtcg.rojocam.rtsp.AbstractRtspServer.java

public void run() {
    checkIsBound();/* ww  w. j a va2 s  .c om*/
    if (mReqHandler == null) {
        throw new IllegalStateException("Request handler not set.");
    }

    while (!mShutdown) {
        try {
            Log.i(TAG, "run nao");
            Socket sock = mSocket.accept();
            RtspServerConnection conn = new RtspServerConnection();

            conn.bind(sock, mParams);

            BasicHttpProcessor processor = new BasicHttpProcessor();
            processor.addInterceptor(new ResponseContent());
            processor.addInterceptor(new ResponseHeaderEcho(RtspHeaders.CSEQ));
            processor.addInterceptor(new ResponseDate());
            processor.addInterceptor(new ResponseHeaderEcho(RtspHeaders.SESSION));

            HttpRequestHandlerRegistry reg = new HttpRequestHandlerRegistry();
            reg.register("*", mReqHandler);

            RtspService svc = new RtspService(processor, new RtspConnectionReuseStrategy(),
                    new DefaultHttpResponseFactory());

            svc.setParams(mParams);
            svc.setHandlerResolver(reg);

            WorkerThread worker = new WorkerThread(svc, conn);

            synchronized (mWorkers) {
                mWorkers.add(worker);
            }

            worker.setDaemon(true);
            worker.start();
        } catch (IOException e) {
            if (!mShutdown) {
                Log.e(TAG, "I/O error initializing connection thread", e);
            }
            break;
        }
    }
}

From source file:org.apache.axis2.transport.http.server.DefaultHttpConnectionManager.java

public void process(final AxisHttpConnection conn) {
    if (conn == null) {
        throw new IllegalArgumentException("HTTP connection may not be null");
    }/*from   w w w . java  2 s.  c  o m*/
    // Evict destroyed processors
    cleanup();

    // Assemble new Axis HTTP service
    HttpProcessor httpProcessor;
    ConnectionReuseStrategy connStrategy;
    HttpResponseFactory responseFactory;

    if (httpFactory != null) {
        httpProcessor = httpFactory.newHttpProcessor();
        connStrategy = httpFactory.newConnStrategy();
        responseFactory = httpFactory.newResponseFactory();
    } else {
        BasicHttpProcessor p = new BasicHttpProcessor();
        p.addInterceptor(new RequestSessionCookie());
        p.addInterceptor(new ResponseDate());
        p.addInterceptor(new ResponseServer());
        p.addInterceptor(new ResponseContent());
        p.addInterceptor(new ResponseConnControl());
        p.addInterceptor(new ResponseSessionCookie());
        httpProcessor = p;
        connStrategy = new DefaultConnectionReuseStrategy();
        responseFactory = new DefaultHttpResponseFactory();
    }

    AxisHttpService httpService = new AxisHttpService(httpProcessor, connStrategy, responseFactory,
            this.configurationContext, this.workerfactory.newWorker());
    httpService.setParams(this.params);

    // Create I/O processor to execute HTTP service
    IOProcessorCallback callback = new IOProcessorCallback() {

        public void completed(final IOProcessor processor) {
            removeProcessor(processor);
            if (LOG.isDebugEnabled()) {
                LOG.debug(processor + " terminated");
            }
        }

    };
    IOProcessor processor = new HttpServiceProcessor(httpService, conn, callback);

    addProcessor(processor);
    this.executor.execute(processor);
}

From source file:org.muckebox.android.net.DownloadServer.java

private void initHttpServer() {
    mHttpProcessor = new BasicHttpProcessor();
    mHttpContext = new BasicHttpContext();
    mHttpService = new HttpService(mHttpProcessor, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory());

    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    mRegistry = new HttpRequestHandlerRegistry();

    mRegistry.register("*", new FileHandler());

    mHttpService.setHandlerResolver(mRegistry);
}

From source file:com.facebook.stetho.server.LocalSocketHttpServer.java

private HttpService createService(HttpParams params) {
    HttpRequestHandlerRegistry registry = mRegistryInitializer.getRegistry();

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    HttpService service = new HttpService(httpproc, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory());
    service.setParams(params);/*  ww  w . j a v  a2s  . co m*/
    service.setHandlerResolver(registry);

    return service;
}

From source file:org.jenkinsci.test.acceptance.update_center.MockUpdateCenter.java

public void ensureRunning() {
    if (original != null) {
        return;//from   w w  w  . j a  va2  s  . c o m
    }
    // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController
    Jenkins jenkins = injector.getInstance(Jenkins.class);
    List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url");
    if (sites.size() != 1) {
        // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies
        LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites);
        return;
    }
    UpdateCenterMetadata ucm;
    try {
        ucm = ucmd.get(jenkins);
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot load data for mock update center", x);
        return;
    }
    JSONObject all;
    try {
        all = new JSONObject(ucm.originalJSON);
        all.remove("signature");
        JSONObject plugins = all.getJSONObject("plugins");
        LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size()
                + " possible overrides");
        for (PluginMetadata meta : ucm.plugins.values()) {
            String name = meta.getName();
            String version = meta.getVersion();
            JSONObject plugin = plugins.optJSONObject(name);
            if (plugin == null) {
                LOGGER.log(Level.INFO, "adding plugin {0}", name);
                plugin = new JSONObject().accumulate("name", name);
                plugins.put(name, plugin);
            }
            plugin.put("url", name + ".hpi");
            updating(plugin, "version", version);
            updating(plugin, "gav", meta.gav);
            updating(plugin, "requiredCore", meta.requiredCore().toString());
            updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> {
                try {
                    return new JSONObject().accumulate("name", d.name).accumulate("version", d.version)
                            .accumulate("optional", d.optional);
                } catch (JSONException x) {
                    throw new AssertionError(x);
                }
            }).collect(Collectors.toList())));
            plugin.remove("sha1");
        }
    } catch (JSONException x) {
        LOGGER.log(Level.WARNING, "cannot prepare mock update center", x);
        return;
    }
    HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter"))
            .add(new ResponseContent()).add(new RequestConnControl()).build();
    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    String json = "updateCenter.post(\n" + all + "\n);";
    handlerMapper.register("/update-center.json",
            (HttpRequest request, HttpResponse response, HttpContext context) -> {
                response.setStatusCode(HttpStatus.SC_OK);
                response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            });
    handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1");
        PluginMetadata meta = ucm.plugins.get(plugin);
        if (meta == null) {
            LOGGER.log(Level.WARNING, "no such plugin {0}", plugin);
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            return;
        }
        File local = meta.resolve(injector, meta.getVersion());
        LOGGER.log(Level.INFO, "serving {0}", local);
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new FileEntity(local));
    });
    handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String location = original.replace("/update-center.json", request.getRequestLine().getUri());
        LOGGER.log(Level.INFO, "redirect to {0}", location);
        /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true):
        response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", location);
         */
        HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection();
        uc.setInstanceFollowRedirects(true);
        // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json
        byte[] data = IOUtils.toByteArray(uc);
        String contentType = uc.getContentType();
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType)));

    });
    server = ServerBootstrap.bootstrap().
    // could setLocalAddress if using a JenkinsController that requires it
            setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler())
            .create();

    try {
        server.start();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot start mock update center", x);
        return;

    }
    original = sites.get(0);
    // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host
    String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort()
            + "/update-center.json";
    LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override });
    jenkins.runScript(
            "DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])",
            override);
}