Example usage for java.net ProtocolException ProtocolException

List of usage examples for java.net ProtocolException ProtocolException

Introduction

In this page you can find the example usage for java.net ProtocolException ProtocolException.

Prototype

public ProtocolException(String message) 

Source Link

Document

Constructs a new ProtocolException with the specified detail message.

Usage

From source file:com.aptana.core.epl.downloader.RepositoryStatusHelper.java

/**
 * Check if the given exception represents a permission failure (401 for HTTP), and throw a ProtocolException if a
 * permission failure was encountered.// w w  w .  ja  va  2s  .  com
 */
public static void checkPermissionDenied(Throwable t) throws ProtocolException {
    // From Use of File Transfer
    if (t instanceof IncomingFileTransferException) {
        if (((IncomingFileTransferException) t).getErrorCode() == 401)
            throw new ProtocolException("Authentication Failed"); //$NON-NLS-1$
        IStatus status = ((IncomingFileTransferException) t).getStatus();
        t = status == null ? t : status.getException();
        // From Use of Browse
    } else if (t instanceof BrowseFileTransferException) {
        if (((BrowseFileTransferException) t).getErrorCode() == 401)
            throw new ProtocolException("Authentication Failed"); //$NON-NLS-1$
        IStatus status = ((BrowseFileTransferException) t).getStatus();
        t = status == null ? t : status.getException();
    }

    if (t == null || !(t instanceof IOException))
        return;

    // TODO: is this needed (for 401) now that ECF throws exceptions with codes?
    // try to figure out if we have a 401 by parsing the exception message
    // There is unfortunately no specific (general) exception for "redirected too many times" - which is commonly
    // caused by a failed login. The message and exception are different in different implementations
    // of http client.
    String m = t.getMessage();
    if (m != null && (m.indexOf(" 401 ") != -1 || m.indexOf(SERVER_REDIRECT) != -1)) //$NON-NLS-1$
        throw new ProtocolException("Authentication Failed"); //$NON-NLS-1$
    if ("org.apache.commons.httpclient.RedirectException".equals(t.getClass().getName())) //$NON-NLS-1$
        throw new ProtocolException("Authentication Failed"); //$NON-NLS-1$
}

From source file:com.example.android.vault.EncryptedDocument.java

private static void assertMagic(RandomAccessFile f) throws IOException {
    final int magic = f.readInt();
    if (magic != MAGIC_NUMBER) {
        throw new ProtocolException("Bad magic number: " + Integer.toHexString(magic));
    }//from w  w  w  . ja va 2 s . c  om
}

From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java

public void connect() throws IOException {
    if (!connected) {
        final String userInfo = url.getUserInfo();
        final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals("");

        // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight)
        final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
        final HttpContext httpContext = new BasicHttpContext();

        // Set cookie store, creating a new one if none was provided to us
        if (cookieStore == null)
            cookieStore = new BasicCookieStore();
        httpClient.setCookieStore(cookieStore);

        // Set proxy and host authentication
        if (proxyAuthState != null)
            httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);
        if (userInfo != null || isAuthenticationRequestedWithUsername) {

            // Make authentication preemptive; interceptor is added first, as the Authentication header is added
            // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor
            // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find
            // the appropriate AuthState/AuthScheme/Credentials in the HttpContext

            // Don't add the interceptor if we don't want preemptive authentication!
            if (!"false".equals(preemptiveAuthentication)) {
                httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0);
            }//from  ww  w.  j  a  v  a2 s  . com

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
            final AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            final Credentials credentials;
            if (userInfo != null) {
                // Set username and optional password specified on URL
                final int separatorPosition = userInfo.indexOf(":");
                String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition);
                String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1);
                // If the username/password contain special character, those character will be encoded, since we
                // are getting this from a URL. Now do the decoding.
                username = URLDecoder.decode(username, "utf-8");
                password = URLDecoder.decode(password, "utf-8");
                credentials = new UsernamePasswordCredentials(username, password);
            } else {
                // Set username and password specified externally
                credentials = domain == null
                        ? new UsernamePasswordCredentials(username, password == null ? "" : password)
                        : new NTCredentials(username, password, url.getHost(), domain);
            }
            credentialsProvider.setCredentials(authScope, credentials);
        }

        // If method has not been set, use GET
        // This can happen e.g. when this connection handler is used from URLFactory
        if (method == null)
            setRequestMethod("GET");

        // Set all headers,
        final boolean skipAuthorizationHeader = userInfo != null || username != null;
        for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) {
            final String currentHeaderName = currentEntry.getKey();
            final String[] currentHeaderValues = currentEntry.getValue();
            for (final String currentHeaderValue : currentHeaderValues) {
                // Skip over Authorization header if user authentication specified
                if (skipAuthorizationHeader && currentHeaderName.toLowerCase()
                        .equals(Connection.AUTHORIZATION_HEADER.toLowerCase()))
                    continue;
                method.addHeader(currentHeaderName, currentHeaderValue);
            }
        }

        // Create request entity with body
        if (method instanceof HttpEntityEnclosingRequest) {

            // Use the body that was set directly, or the result of writing to the OutputStream
            final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null;

            if (body != null) {
                final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison
                if (contentTypeHeader == null)
                    throw new ProtocolException("Can't set request entity: Content-Type header is missing");
                final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body);
                byteArrayEntity.setContentType(contentTypeHeader);
                ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity);
            }
        }

        // Make request
        httpResponse = httpClient.execute(method, httpContext);
        connected = true;
    }
}

From source file:com.almende.eve.transport.xmpp.XmppService.java

@Override
public void sendAsync(final URI senderUrl, final URI receiverUrl, final String message, final String tag)
        throws IOException {

    AgentConnection connection = null;//  w ww  . j  a va2  s.  c o m

    if (senderUrl != null) {
        connection = connectionsByUrl.get(senderUrl);
    }
    if (connection != null) {
        // remove the protocol from the receiver url
        String receiver = receiverUrl.toString();
        final String protocol = "xmpp:";
        if (!receiver.startsWith(protocol)) {
            throw new ProtocolException(
                    "Receiver url must start with '" + protocol + "' (receiver='" + receiver + "')");
        }
        // username@domain
        final String fullUsername = receiver.substring(protocol.length());
        connection.send(fullUsername, message);
    } else {
        // TODO: use an anonymous xmpp connection when the sender agent has
        // no xmpp connection.
        throw new IOException("Cannot send an xmpp request, " + "agent has no xmpp connection.");
    }
}

From source file:org.apache.hawq.pxf.plugins.ignite.IgniteAccessor.java

/**
 * Send a REST request to the Ignite server
 *
 * @param query A prepared and properly encoded HTTP GET request
 *
 * @return "response" field from the received JSON object
 * (See Ignite REST API documentation for details)
 *
 * @throws ProtocolException if Ignite reports error in it's JSON response
 * @throws MalformedURLException if URL is malformed
 * @throws IOException in case of connection failure
 *//*w  w w. j  a va2 s .  com*/
private JsonElement sendRestRequest(String query) throws ProtocolException, MalformedURLException, IOException {
    // Create URL object. This operation may throw 'MalformedURLException'
    URL url = new URL(query);

    // Connect to the Ignite server, send query and get raw response
    BufferedReader reader = null;
    String responseRaw = null;
    try {
        StringBuilder sb = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String responseLine;
        while ((responseLine = reader.readLine()) != null) {
            sb.append(responseLine);
        }
        responseRaw = sb.toString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("sendRestRequest(): URL: '" + query + "'; Result: '" + responseRaw + "'");
        }
    } catch (Exception e) {
        LOG.error("sendRestRequest(): Failed (connection failure). URL is '" + query + "'");
        throw e;
    } finally {
        if (reader != null) {
            reader.close();
        }
        // if 'reader' is null, an exception must have been thrown
    }

    // Parse raw Ignite server response
    JsonElement response = null;
    String error = null;
    int successStatus;
    try {
        response = new JsonParser().parse(responseRaw);

        if (!response.getAsJsonObject().get("error").isJsonNull()) {
            error = response.getAsJsonObject().get("error").getAsString();
        }
        successStatus = response.getAsJsonObject().get("successStatus").getAsInt();
    } catch (Exception e) {
        LOG.error("sendRestRequest(): Failed (JSON parsing failure). URL is '" + query + "'");
        throw e;
    }

    // Check errors reported by Ignite
    if ((error != null) || (successStatus != 0)) {
        LOG.error(
                "sendRestRequest(): Failed (failure on Ignite side: '" + error + "'). URL is '" + query + "'");
        throw new ProtocolException("Ignite failure: status " + successStatus + ", '" + error + "'");
    }

    // Return response without metadata
    try {
        return response.getAsJsonObject().get("response");
    } catch (Exception e) {
        LOG.error("sendRestRequest(): Failed (JSON parsing failure). URL is '" + query + "'");
        throw e;
    }
}

From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java

/**
 * Logs on to the MyProxy server by issuing the MyProxy GET command.
 *//*  w w w  . j  a v  a2s .  c o m*/
public void logon() throws IOException, GeneralSecurityException {
    String line;
    char response;

    if (this.state != State.CONNECTED) {
        this.connect();
    }
    try {
        this.socketOut.write('0');
        this.socketOut.flush();
        this.socketOut.write(VERSION.getBytes());
        this.socketOut.write('\n');
        this.socketOut.write(GETCOMMAND.getBytes());
        this.socketOut.write('\n');
        this.socketOut.write(USERNAME.getBytes());
        this.socketOut.write(this.username.getBytes());
        this.socketOut.write('\n');
        this.socketOut.write(PASSPHRASE.getBytes());
        this.socketOut.write(this.passphrase.getBytes());
        this.socketOut.write('\n');
        this.socketOut.write(LIFETIME.getBytes());
        this.socketOut.write(Integer.toString(this.lifetime).getBytes());
        this.socketOut.write('\n');
        if (this.credname != null) {
            this.socketOut.write(CREDNAME.getBytes());
            this.socketOut.write(this.credname.getBytes());
            this.socketOut.write('\n');
        }
        if (this.requestTrustRoots) {
            this.socketOut.write(TRUSTROOTS.getBytes());
            this.socketOut.write("1\n".getBytes());
        }
        this.socketOut.flush();

        line = readLine(this.socketIn);
        if (line == null) {
            throw new EOFException();
        }
        if (!line.equals(VERSION)) {
            throw new ProtocolException("bad MyProxy protocol VERSION string: " + line);
        }
        line = readLine(this.socketIn);
        if (line == null) {
            throw new EOFException();
        }
        if (!line.startsWith(RESPONSE) || line.length() != RESPONSE.length() + 1) {
            throw new ProtocolException("bad MyProxy protocol RESPONSE string: " + line);
        }
        response = line.charAt(RESPONSE.length());
        if (response == '1') {
            StringBuffer errString;

            errString = new StringBuffer("MyProxy logon failed");
            while ((line = readLine(this.socketIn)) != null) {
                if (line.startsWith(ERROR)) {
                    errString.append('\n');
                    errString.append(line.substring(ERROR.length()));
                }
            }
            throw new FailedLoginException(errString.toString());
        } else if (response == '2') {
            throw new ProtocolException("MyProxy authorization RESPONSE not implemented");
        } else if (response != '0') {
            throw new ProtocolException("unknown MyProxy protocol RESPONSE string: " + line);
        }
        while ((line = readLine(this.socketIn)) != null) {
            if (line.startsWith(TRUSTROOTS)) {
                String filenameList = line.substring(TRUSTROOTS.length());
                this.trustrootFilenames = filenameList.split(",");
                this.trustrootData = new String[this.trustrootFilenames.length];
                for (int i = 0; i < this.trustrootFilenames.length; i++) {
                    String lineStart = "FILEDATA_" + this.trustrootFilenames[i] + "=";
                    line = readLine(this.socketIn);
                    if (line == null) {
                        throw new EOFException();
                    }
                    if (!line.startsWith(lineStart)) {
                        throw new ProtocolException("bad MyProxy protocol RESPONSE: expecting " + lineStart
                                + " but received " + line);
                    }
                    this.trustrootData[i] = new String(Base64.decodeBase64(line.substring(lineStart.length())));
                }
            }
        }
        this.state = State.LOGGEDON;
    } catch (Throwable t) {
        handleException(t, getClass().getSimpleName() + " logon failed.");
    }
}

From source file:org.lockss.protocol.LcapDatagramComm.java

private void runHandlers(LockssReceivedDatagram ld) throws ProtocolException {
    try {//  ww w.  ja  va  2s . com
        int proto = ld.getProtocol();
        MessageHandler handler;
        if (proto >= 0 && proto < messageHandlers.size()
                && (handler = (MessageHandler) messageHandlers.get(proto)) != null) {
            runHandler(handler, ld);
        } else {
            log.warning("Received message with unregistered protocol: " + proto + " from " + ld.getSender());
        }
    } catch (RuntimeException e) {
        log.warning("Unexpected error in runHandlers", e);
        throw new ProtocolException(e.toString());
    }
}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * Rename file/*from w  w w  .j  a  va 2  s  . c om*/
 * @param sSourceURI Source URI (ej. "file:///tmp/files/oldfile.txt")
 * @param sTargetURI Target URI (ej. "file:///tmp/files/newfile.txt")
 * @since 2.1
 * @throws Exception
 * @throws IOException
 * @throws ProtocolException If source and target file does not use the same protocol, either file:// or ftp://
 */
public boolean rename(String sSourceURI, String sTargetURI) throws Exception, IOException, ProtocolException {
    boolean bRetVal;

    if (sSourceURI.startsWith("file://") && sTargetURI.startsWith("file://")) {
        File oOldFile = new File(sSourceURI.substring(7));
        File oNewFile = new File(sTargetURI.substring(7));
        bRetVal = oOldFile.renameTo(oNewFile);
    } else if (sSourceURI.startsWith("ftp://") && sTargetURI.startsWith("ftp://")) {
        bRetVal = moveFTPToFTP(sSourceURI, sTargetURI);
    } else {
        throw new ProtocolException("");
    }
    return bRetVal;
}

From source file:org.lockss.protocol.BlockingStreamComm.java

private void runHandlers(PeerMessage msg) throws ProtocolException {
    try {//from   ww  w .j  ava 2s. c o m
        int proto = msg.getProtocol();
        MessageHandler handler;
        if (proto >= 0 && proto < messageHandlers.size()
                && (handler = (MessageHandler) messageHandlers.get(proto)) != null) {
            runHandler(handler, msg);
        } else {
            log.warning("Received message with unregistered protocol: " + proto);
        }
    } catch (RuntimeException e) {
        log.warning("Unexpected error in runHandlers", e);
        throw new ProtocolException(e.toString());
    }
}