Search in sources :

Example 11 with HttpURLConnection

use of java.net.HttpURLConnection in project jetty.project by eclipse.

the class RequestLogHandlerTest method testLogHandlerCollection_OKErrorHandler.

/**
     * Test a RequestLogHandler at the end of a HandlerCollection and also with the ErrorHandler in place.
     * @throws Exception if test failure
     */
@Test(timeout = 4000)
public void testLogHandlerCollection_OKErrorHandler() throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.setConnectors(new Connector[] { connector });
    OKErrorHandler errorDispatcher = new OKErrorHandler();
    server.addBean(errorDispatcher);
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    ContextHandler errorContext = new ContextHandler("/errorpage");
    errorContext.setHandler(new AltErrorHandler());
    ContextHandler testContext = new ContextHandler("/test");
    testContext.setHandler(testHandler);
    contexts.addHandler(errorContext);
    contexts.addHandler(testContext);
    RequestLogHandler requestLog = new RequestLogHandler();
    CaptureLog captureLog = new CaptureLog();
    requestLog.setRequestLog(captureLog);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { contexts, requestLog });
    server.setHandler(handlers);
    try {
        server.start();
        String host = connector.getHost();
        if (host == null) {
            host = "localhost";
        }
        int port = connector.getLocalPort();
        URI serverUri = new URI("http", null, host, port, requestPath, null, null);
        // Make call to test handler
        HttpURLConnection connection = (HttpURLConnection) serverUri.toURL().openConnection();
        try {
            connection.setAllowUserInteraction(false);
            // log response status code
            int statusCode = connection.getResponseCode();
            LOG.debug("Response Status Code: {}", statusCode);
            if (statusCode == 200) {
                // collect response message and log it
                String content = getResponseContent(connection);
                LOG.debug("Response Content: {}", content);
            }
        } finally {
            connection.disconnect();
        }
        assertRequestLog(captureLog);
    } finally {
        server.stop();
    }
}
Also used : Server(org.eclipse.jetty.server.Server) URI(java.net.URI) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpURLConnection(java.net.HttpURLConnection) Test(org.junit.Test)

Example 12 with HttpURLConnection

use of java.net.HttpURLConnection in project jetty.project by eclipse.

the class RequestLogHandlerTest method testLogHandlerWrapped.

@Test(timeout = 4000)
public void testLogHandlerWrapped() throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.setConnectors(new Connector[] { connector });
    CaptureLog captureLog = new CaptureLog();
    RequestLogHandler requestLog = new RequestLogHandler();
    requestLog.setRequestLog(captureLog);
    requestLog.setHandler(testHandler);
    server.setHandler(requestLog);
    try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class, HttpChannelState.class)) {
        server.start();
        String host = connector.getHost();
        if (host == null) {
            host = "localhost";
        }
        int port = connector.getLocalPort();
        URI serverUri = new URI("http", null, host, port, requestPath, null, null);
        // Make call to test handler
        HttpURLConnection connection = (HttpURLConnection) serverUri.toURL().openConnection();
        try {
            connection.setAllowUserInteraction(false);
            // log response status code
            int statusCode = connection.getResponseCode();
            LOG.info("Response Status Code: {}", statusCode);
            if (statusCode == 200) {
                // collect response message and log it
                String content = getResponseContent(connection);
                LOG.info("Response Content: {}", content);
            }
        } finally {
            connection.disconnect();
        }
        assertRequestLog(captureLog);
    } finally {
        server.stop();
    }
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpURLConnection(java.net.HttpURLConnection) Server(org.eclipse.jetty.server.Server) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) URI(java.net.URI) Test(org.junit.Test)

Example 13 with HttpURLConnection

use of java.net.HttpURLConnection in project jetty.project by eclipse.

the class RequestLogHandlerTest method testLogHandlerCollection_ErrorHandler_ServerBean.

/**
     * Test a RequestLogHandler at the end of a HandlerCollection and also with the default ErrorHandler as server bean in place.
     * @throws Exception if test failure
     */
@Test(timeout = 4000)
public void testLogHandlerCollection_ErrorHandler_ServerBean() throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.setConnectors(new Connector[] { connector });
    ErrorHandler errorHandler = new ErrorHandler();
    server.addBean(errorHandler);
    CaptureLog captureLog = new CaptureLog();
    RequestLogHandler requestLog = new RequestLogHandler();
    requestLog.setRequestLog(captureLog);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { testHandler, requestLog });
    server.setHandler(handlers);
    try {
        server.start();
        String host = connector.getHost();
        if (host == null) {
            host = "localhost";
        }
        int port = connector.getLocalPort();
        URI serverUri = new URI("http", null, host, port, requestPath, null, null);
        // Make call to test handler
        HttpURLConnection connection = (HttpURLConnection) serverUri.toURL().openConnection();
        try {
            connection.setAllowUserInteraction(false);
            // log response status code
            int statusCode = connection.getResponseCode();
            LOG.debug("Response Status Code: {}", statusCode);
            if (statusCode == 200) {
                // collect response message and log it
                String content = getResponseContent(connection);
                LOG.debug("Response Content: {}", content);
            }
        } finally {
            connection.disconnect();
        }
        assertRequestLog(captureLog);
    } finally {
        server.stop();
    }
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpURLConnection(java.net.HttpURLConnection) Server(org.eclipse.jetty.server.Server) URI(java.net.URI) Test(org.junit.Test)

Example 14 with HttpURLConnection

use of java.net.HttpURLConnection in project UltimateAndroid by cymcsg.

the class BitmapDecoderHttp method decode.

@Override
public Bitmap decode(String fileName, Context context) {
    try {
        URL url = new URL(fileName);
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream input = connection.getInputStream();
            if (input != null) {
                try {
                    return BitmapFactory.decodeStream(input, null, OPTIONS);
                } catch (OutOfMemoryError oom) {
                // oom - you can try sleeping (this method won't be called in the UI thread) or try again (or give up)
                } catch (Exception e) {
                // unknown error decoding bitmap
                }
            }
        } catch (IOException e) {
        // io error
        }
    } catch (MalformedURLException e1) {
    // bad url
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) IOException(java.io.IOException) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 15 with HttpURLConnection

use of java.net.HttpURLConnection in project deeplearning4j by deeplearning4j.

the class RemoteUIStatsStorageRouter method tryPost.

private boolean tryPost(ToPost toPost) throws IOException {
    HttpURLConnection connection = getConnection();
    String className;
    byte[] asBytes;
    StorageType type;
    if (toPost.getMeta() != null) {
        StorageMetaData smd = toPost.getMeta();
        className = smd.getClass().getName();
        asBytes = smd.encode();
        type = StorageType.MetaData;
    } else if (toPost.getStaticInfo() != null) {
        Persistable p = toPost.getStaticInfo();
        className = p.getClass().getName();
        asBytes = p.encode();
        type = StorageType.StaticInfo;
    } else {
        Persistable p = toPost.getUpdate();
        className = p.getClass().getName();
        asBytes = p.encode();
        type = StorageType.Update;
    }
    String base64 = DatatypeConverter.printBase64Binary(asBytes);
    Map<String, String> jsonObj = new LinkedHashMap<>();
    jsonObj.put("type", type.name());
    jsonObj.put("class", className);
    jsonObj.put("data", base64);
    String str;
    try {
        str = objectMapper.writeValueAsString(jsonObj);
    } catch (Exception e) {
        //Should never get an exception from simple Map<String,String>
        throw new RuntimeException(e);
    }
    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    dos.writeBytes(str);
    dos.flush();
    dos.close();
    try {
        int responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            log.warn("Error posting to remote UI - received response code {}\tContent: {}", response, response.toString());
            return false;
        }
    } catch (IOException e) {
        String msg = e.getMessage();
        if (msg.contains("403 for URL")) {
            log.warn("Error posting to remote UI at {} (Response code: 403)." + " Remote listener support is not enabled? use UIServer.getInstance().enableRemoteListener()", url, e);
        } else {
            log.warn("Error posting to remote UI at {}", url, e);
        }
        return false;
    }
    return true;
}
Also used : StorageType(org.deeplearning4j.api.storage.StorageType) Persistable(org.deeplearning4j.api.storage.Persistable) InputStreamReader(java.io.InputStreamReader) DataOutputStream(java.io.DataOutputStream) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) StorageMetaData(org.deeplearning4j.api.storage.StorageMetaData) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader)

Aggregations

HttpURLConnection (java.net.HttpURLConnection)3831 URL (java.net.URL)2447 IOException (java.io.IOException)1634 InputStream (java.io.InputStream)1082 InputStreamReader (java.io.InputStreamReader)692 Test (org.junit.Test)650 BufferedReader (java.io.BufferedReader)573 OutputStream (java.io.OutputStream)466 MalformedURLException (java.net.MalformedURLException)372 URLConnection (java.net.URLConnection)248 HashMap (java.util.HashMap)216 OutputStreamWriter (java.io.OutputStreamWriter)208 Map (java.util.Map)199 Gson (com.google.gson.Gson)190 ByteArrayOutputStream (java.io.ByteArrayOutputStream)186 ArrayList (java.util.ArrayList)168 ExecutionException (java.util.concurrent.ExecutionException)161 File (java.io.File)159 AsyncTask (android.os.AsyncTask)158 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)157