Search in sources :

Example 76 with ProtocolException

use of java.net.ProtocolException in project opennms by OpenNMS.

the class BasicHttpMethods method postData.

/**
 * Reads data from the data reader and posts it to a server via POST request.
 * data - The data you want to send
 * endpoint - The server's address
 * output - writes the server's response to output
 * @throws Exception
 */
public void postData(Reader data, URL endpoint, Writer output, String username, String password) throws Exception {
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();
        try {
            conn.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        // set username and password
        // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html
        String userPassword = username + ":" + password;
        // Encode String
        // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder()
        byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes());
        String authStringEnc = new String(encoding);
        log.debug("Base64 encoded auth string: '" + authStringEnc + "'");
        conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "application/xml; charset=" + "UTF-8");
        OutputStream out = conn.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            pipe(data, writer);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null)
                out.close();
        }
        InputStream in = conn.getInputStream();
        try {
            Reader reader = new InputStreamReader(in);
            pipe(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null)
                in.close();
        }
    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}
Also used : ProtocolException(java.net.ProtocolException) HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 77 with ProtocolException

use of java.net.ProtocolException in project opennms by OpenNMS.

the class BasicHttpMethods method putData.

/**
 * sends data to a server via PUT request.
 * data - The data you want to send
 * endpoint - The server's address
 * output - writes the server's response to output
 * @throws Exception
 */
public void putData(Reader data, URL endpoint, Writer output, String username, String password) throws Exception {
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();
        try {
            conn.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support PUT??", e);
        }
        // set username and password
        // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html
        String userPassword = username + ":" + password;
        // Encode String
        // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder()
        byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes());
        String authStringEnc = new String(encoding);
        log.debug("Base64 encoded auth string: '" + authStringEnc + "'");
        conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=" + "UTF-8");
        OutputStream out = conn.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            pipe(data, writer);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while putting data", e);
        } finally {
            if (out != null)
                out.close();
        }
        InputStream in = conn.getInputStream();
        try {
            Reader reader = new InputStreamReader(in);
            pipe(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null)
                in.close();
        }
    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}
Also used : ProtocolException(java.net.ProtocolException) HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 78 with ProtocolException

use of java.net.ProtocolException in project opennms by OpenNMS.

the class BasicHttpMethods method deleteData.

/**
 * Sends an HTTP DELETE request to a url
 * endpoint - The server's address
 * output - writes the server's response to output
 * @throws Exception
 */
public void deleteData(URL endpoint, Writer output, String username, String password) throws Exception {
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();
        try {
            conn.setRequestMethod("DELETE");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support DELETE??", e);
        }
        // set username and password
        // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html
        String userPassword = username + ":" + password;
        // Encode String
        // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder()
        byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes());
        String authStringEnc = new String(encoding);
        log.debug("Base64 encoded auth string: '" + authStringEnc + "'");
        conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "application/xml; charset=" + "UTF-8");
        InputStream in = conn.getInputStream();
        try {
            Reader reader = new InputStreamReader(in);
            pipe(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null)
                in.close();
        }
    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}
Also used : ProtocolException(java.net.ProtocolException) HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) IOException(java.io.IOException) ProtocolException(java.net.ProtocolException)

Example 79 with ProtocolException

use of java.net.ProtocolException in project cxf by apache.

the class JsXMLHttpRequest method doSend.

private void doSend(byte[] dataToSend, boolean xml) {
    // avoid warnings on stuff we arent using yet.
    if (storedUser != null || storedPassword != null) {
    // 
    }
    // 1 check state
    if (readyState != jsGet_OPENED()) {
        LOG.severe("send state != OPENED.");
        throwError("INVALID_STATE_ERR");
    }
    // 2 check flag
    if (sendFlag) {
        LOG.severe("send sendFlag set.");
        throwError("INVALID_STATE_ERR");
    }
    // 3
    sendFlag = storedAsync;
    // UTF-8 bytes.
    if (xml && !requestHeaders.containsKey("Content-Type")) {
        requestHeaders.put("Content-Type", "application/xml;charset=utf-8");
    }
    // 5 talk to the server.
    try {
        connection = url.openConnection();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "send connection failed.", e);
        throwError("CONNECTION_FAILED");
    }
    connection.setDoInput(true);
    // Enable tunneling.
    connection.setUseCaches(false);
    boolean post = false;
    httpConnection = null;
    if (connection instanceof HttpURLConnection) {
        httpConnection = (HttpURLConnection) connection;
        try {
            httpConnection.setRequestMethod(storedMethod);
            if ("POST".equalsIgnoreCase(storedMethod)) {
                httpConnection.setDoOutput(true);
                post = true;
            }
            for (Map.Entry<String, String> headerEntry : requestHeaders.entrySet()) {
                httpConnection.setRequestProperty(headerEntry.getKey(), headerEntry.getValue());
            }
        } catch (ProtocolException e) {
            LOG.log(Level.SEVERE, "send http protocol exception.", e);
            throwError("HTTP_PROTOCOL_ERROR");
        }
    }
    if (post) {
        OutputStream outputStream = null;
        try {
            // implicitly connects?
            outputStream = connection.getOutputStream();
            if (dataToSend != null) {
                outputStream.write(dataToSend);
                outputStream.flush();
            }
            outputStream.close();
        } catch (IOException e) {
            errorFlag = true;
            LOG.log(Level.SEVERE, "send output error.", e);
            throwError("NETWORK_ERR");
            try {
                outputStream.close();
            } catch (IOException e1) {
            // 
            }
        }
    }
    // 6
    notifyReadyStateChangeListener();
    if (storedAsync) {
        new Thread() {

            public void run() {
                try {
                    Context cx = ContextFactory.getGlobal().enterContext();
                    communicate(cx);
                } finally {
                    Context.exit();
                }
            }
        }.start();
    } else {
        communicate(Context.getCurrentContext());
    }
}
Also used : Context(org.mozilla.javascript.Context) ProtocolException(java.net.ProtocolException) HttpURLConnection(java.net.HttpURLConnection) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 80 with ProtocolException

use of java.net.ProtocolException in project grakn by graknlabs.

the class Client method serverIsRunning.

/**
 * Check if Grakn Engine has been started
 *
 * @return true if Grakn Engine running, false otherwise
 */
public static boolean serverIsRunning(SimpleURI uri) {
    URL url;
    try {
        url = UriBuilder.fromUri(uri.toURI()).path(REST.WebPath.KB).build().toURL();
    } catch (MalformedURLException e) {
        throw CommonUtil.unreachableStatement("This will never throw because we're appending a known path to a valid URI", e);
    }
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) mapQuadZeroRouteToLocalhost(url).openConnection();
    } catch (IOException e) {
        // If this fails, then the server is not reachable
        return false;
    }
    try {
        connection.setRequestMethod("GET");
    } catch (ProtocolException e) {
        throw CommonUtil.unreachableStatement("This will never throw because 'GET' is correct and the connection is not open yet", e);
    }
    int available;
    try {
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        available = inputStream.available();
    } catch (IOException e) {
        // If this fails, then the server is not reachable
        return false;
    }
    return available != 0;
}
Also used : ProtocolException(java.net.ProtocolException) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

ProtocolException (java.net.ProtocolException)153 IOException (java.io.IOException)41 HttpURLConnection (java.net.HttpURLConnection)32 URL (java.net.URL)28 FileInputStream (java.io.FileInputStream)19 NetworkStats (android.net.NetworkStats)18 NetworkStatsHistory (android.net.NetworkStatsHistory)18 StrictMode (android.os.StrictMode)18 ProcFileReader (com.android.internal.util.ProcFileReader)18 BufferedInputStream (java.io.BufferedInputStream)17 FileNotFoundException (java.io.FileNotFoundException)17 MalformedURLException (java.net.MalformedURLException)15 InputStream (java.io.InputStream)13 OutputStream (java.io.OutputStream)13 AtomicFile (android.util.AtomicFile)12 DataInputStream (java.io.DataInputStream)12 Map (java.util.Map)12 Test (org.junit.Test)12 BufferedReader (java.io.BufferedReader)11 InputStreamReader (java.io.InputStreamReader)11