Search in sources :

Example 1 with IStatus

use of fi.iki.elonen.NanoHTTPD.Response.IStatus in project bnd by bndtools.

the class DebugProxy method serve.

@Override
public synchronized Response serve(IHTTPSession session) {
    try {
        System.out.println(session);
        URL uri = new URL(forward + session.getUri());
        final HttpURLConnection c = (HttpURLConnection) uri.openConnection();
        c.setRequestMethod(session.getMethod().toString());
        System.out.println("-> " + session.getMethod() + " " + session.getUri());
        for (Entry<String, String> e : session.getHeaders().entrySet()) {
            if (e.getKey().equalsIgnoreCase("host")) {
                String host = forward.getHost();
                if (forward.getPort() != forward.getDefaultPort())
                    host += ":" + forward.getPort();
                c.setRequestProperty("host", host);
            } else if (!e.getKey().equals("accept-encoding"))
                c.setRequestProperty(e.getKey(), e.getValue());
            System.out.println("-> " + e.getKey() + "=" + e.getValue());
        }
        byte[] data = null;
        Map<String, String> headers = session.getHeaders();
        if (headers.containsKey("content-length")) {
            int length = Integer.parseInt(headers.get("content-length"));
            data = new byte[length];
            DataInputStream din = new DataInputStream(session.getInputStream());
            din.readFully(data);
            c.setDoOutput(true);
            c.getOutputStream().write(data);
            c.getOutputStream().flush();
        }
        c.connect();
        IStatus status = new IStatus() {

            @Override
            public String getDescription() {
                try {
                    return c.getResponseMessage();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }

            @Override
            public int getRequestStatus() {
                try {
                    return c.getResponseCode();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        };
        System.out.println("== " + c.getResponseCode() + " : " + c.getResponseMessage());
        InputStream in = null;
        if (c.getContentLength() > 0) {
            data = new byte[c.getContentLength()];
            DataInputStream din = new DataInputStream(c.getInputStream());
            din.readFully(data);
            String s = new String(data);
            // System.out.println("--------------------\n");
            // System.out.println(s);
            // System.out.println("--------------------\n");
            in = new ByteArrayInputStream(data);
        }
        Response r = new Response(status, c.getContentType(), in, c.getContentLengthLong()) {

            {
                for (Map.Entry<String, List<String>> l : c.getHeaderFields().entrySet()) {
                    for (String value : l.getValue()) {
                        if (l.getKey() != null)
                            addHeader(l.getKey(), value);
                        System.out.println("<- " + l.getKey() + "=" + value);
                    }
                }
            }
        };
        return r;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
Also used : IStatus(fi.iki.elonen.NanoHTTPD.Response.IStatus) DataInputStream(java.io.DataInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) Map(java.util.Map)

Example 2 with IStatus

use of fi.iki.elonen.NanoHTTPD.Response.IStatus in project wikidata-query-rdf by wikimedia.

the class Proxy method main.

/**
 * Run from the CLI.
 *
 * @throws IOException if one is thrown trying to get the port
 * @throws URISyntaxException
 */
public static void main(String[] args) throws IOException, URISyntaxException {
    ProxyOptions options = OptionsUtils.handleOptions(ProxyOptions.class, args);
    WikibaseRepository.Uris wikibase = WikibaseRepository.Uris.withWikidataDefaults(new URI(options.wikibaseUrl()));
    // Create status objects for errors
    IStatus[] statuses = options.error().stream().map(Proxy::buildErrorStatus).toArray(IStatus[]::new);
    Proxy p = new Proxy(options.port(), wikibase, statuses, options.errorMod());
    p.start();
    if (options.embedded()) {
        return;
    }
    while (true) {
        try {
            Thread.sleep(TimeUnit.MINUTES.toSeconds(1));
        } catch (InterruptedException e) {
            break;
        }
    }
    p.stop();
}
Also used : IStatus(fi.iki.elonen.NanoHTTPD.Response.IStatus) WikibaseRepository(org.wikidata.query.rdf.tool.wikibase.WikibaseRepository) URI(java.net.URI)

Example 3 with IStatus

use of fi.iki.elonen.NanoHTTPD.Response.IStatus in project bnd by bndtools.

the class Server method serve.

@Override
public Response serve(IHTTPSession session) {
    try {
        final aQute.http.testservers.HttpTestServer.Response response = new HttpTestServer.Response();
        final aQute.http.testservers.HttpTestServer.Request request = new HttpTestServer.Request();
        Map<String, String> headers = session.getHeaders();
        if (headers.containsKey("content-length")) {
            int length = Integer.parseInt(headers.get("content-length"));
            request.content = new byte[length];
            DataInputStream din = new DataInputStream(session.getInputStream());
            din.readFully(request.content);
        }
        HttpContext context = findHandler(session.getUri());
        if (context == null) {
            return newFixedLengthResponse(NanoHTTPD.Response.Status.BAD_REQUEST, "text/plain", "Method not found for " + session.getUri());
        }
        request.uri = new URI(session.getUri());
        request.headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
        request.headers.putAll(session.getHeaders());
        request.args = session.getParms();
        request.ip = session.getHeaders().get("remote-addr");
        request.method = session.getMethod().name();
        String path = request.uri.getPath().substring(context.path.length());
        if (path.startsWith("/"))
            path = path.substring(1);
        context.handler.handle(path, request, response);
        if (response.content == null)
            response.content = new byte[0];
        if (response.length < 0)
            response.length = response.content.length;
        IStatus status = NanoHTTPD.Response.Status.OK;
        for (IStatus v : fi.iki.elonen.NanoHTTPD.Response.Status.values()) {
            if (v.getRequestStatus() == response.code) {
                status = v;
                break;
            }
        }
        Response r;
        if (response.stream != null)
            r = newFixedLengthResponse(status, response.mimeType, response.stream, response.length);
        else
            r = newFixedLengthResponse(status, response.mimeType, new ByteArrayInputStream(response.content), response.length);
        for (Map.Entry<String, String> entry : response.headers.entrySet()) {
            r.addHeader(entry.getKey(), entry.getValue());
        }
        if (response.mimeType != null)
            r.setMimeType(response.mimeType);
        return r;
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.close();
        Response r = newFixedLengthResponse(NanoHTTPD.Response.Status.INTERNAL_ERROR, "text/plain", sw.toString());
        return r;
    }
}
Also used : IStatus(fi.iki.elonen.NanoHTTPD.Response.IStatus) DataInputStream(java.io.DataInputStream) URI(java.net.URI) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) PrintWriter(java.io.PrintWriter)

Example 4 with IStatus

use of fi.iki.elonen.NanoHTTPD.Response.IStatus in project wikidata-query-rdf by wikimedia.

the class Proxy method serve.

@Override
public Response serve(IHTTPSession session) {
    log.debug("Serving {} {}", session.getMethod(), session.getUri());
    long currentRequest = requestCount.incrementAndGet();
    if (currentRequest % errorMod == 1) {
        final IStatus randomStatus = errorStatus[random.nextInt(errorStatus.length)];
        log.debug("Returning an {}:{}", randomStatus.getRequestStatus(), randomStatus.getDescription());
        return new Response(randomStatus, NanoHTTPD.MIME_PLAINTEXT, "dummy error");
    }
    try {
        URI uri = buildUri(session.getUri(), session.getParms());
        log.debug("Proxying to {}", uri);
        HttpRequestBase request = buildRequest(session.getMethod(), uri);
        // TODO we totally ignore headers
        ignoreCookies(request);
        CloseableHttpResponse response = client.execute(request);
        /*
             * Note that I'm intentionally not closing the response because the
             * caller will close the wrapped input stream which is probably good
             * enough.
             */
        IStatus status = new SimpleStatus(response.getStatusLine());
        String mimeType = response.getEntity().getContentType().getValue();
        Response result = new Response(status, mimeType, response.getEntity().getContent());
        result.setChunkedTransfer(true);
        return result;
    } catch (URISyntaxException e) {
        return new Response(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "Invalid URI:  " + e.getMessage());
    } catch (IOException e) {
        return new Response(NanoHTTPD.Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "Errroc communicating with other side of proxy:  " + e.getMessage());
    }
}
Also used : CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IStatus(fi.iki.elonen.NanoHTTPD.Response.IStatus) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI)

Example 5 with IStatus

use of fi.iki.elonen.NanoHTTPD.Response.IStatus in project wikidata-query-rdf by wikimedia.

the class Proxy method buildErrorStatus.

/**
 * Build a NanoHTTPD compatible IStatus for an error code.
 */
private static IStatus buildErrorStatus(int errorCode) {
    /*
         * Some codes aren't supported by NanoHTTPD "natively" so we add them
         * ourselves.
         */
    switch(errorCode) {
        case 503:
            return new SimpleStatus(503, "Internal server error");
        case 429:
            return new SimpleStatus(429, "Too many requests");
        default:
    }
    // If it is supported by NanoHTTPD use its status
    for (Status status : Status.values()) {
        if (status.getRequestStatus() == errorCode) {
            return status;
        }
    }
    // Otherwise throw the user an error
    CliUtils.ForbiddenOk.systemDotErr().printf(Locale.ROOT, "Unknown error code:  %s\n", errorCode);
    System.exit(1);
    return null;
}
Also used : Status(fi.iki.elonen.NanoHTTPD.Response.Status) IStatus(fi.iki.elonen.NanoHTTPD.Response.IStatus)

Aggregations

IStatus (fi.iki.elonen.NanoHTTPD.Response.IStatus)5 IOException (java.io.IOException)3 URI (java.net.URI)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 DataInputStream (java.io.DataInputStream)2 Map (java.util.Map)2 Status (fi.iki.elonen.NanoHTTPD.Response.Status)1 InputStream (java.io.InputStream)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 HttpURLConnection (java.net.HttpURLConnection)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 KeyManagementException (java.security.KeyManagementException)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 UnrecoverableKeyException (java.security.UnrecoverableKeyException)1 CertificateException (java.security.cert.CertificateException)1 HashMap (java.util.HashMap)1 List (java.util.List)1