Example usage for java.net HttpURLConnection HTTP_UNAVAILABLE

List of usage examples for java.net HttpURLConnection HTTP_UNAVAILABLE

Introduction

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

Prototype

int HTTP_UNAVAILABLE

To view the source code for java.net HttpURLConnection HTTP_UNAVAILABLE.

Click Source Link

Document

HTTP Status-Code 503: Service Unavailable.

Usage

From source file:org.openrdf.http.client.HTTPClient.java

protected void getRDF(HttpMethod method, RDFHandler handler, boolean requireContext)
        throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
    if (rdfFormats.isEmpty()) {
        throw new RepositoryException("No tuple RDF parsers have been registered");
    }//from  w ww .j  av  a2  s.  com

    List<String> acceptParams = RDFFormat.getAcceptParams(rdfFormats, requireContext, preferredRDFFormat);
    for (String acceptParam : acceptParams) {
        method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam);
    }

    int httpCode = httpClient.executeMethod(method);

    if (httpCode == HttpURLConnection.HTTP_OK) {
        String mimeType = getResponseMIMEType(method);
        try {
            RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats);
            RDFParser parser = Rio.createParser(format, getValueFactory());
            parser.setParserConfig(getParserConfig());
            parser.setParseErrorListener(new ParseErrorLogger());
            parser.setRDFHandler(handler);
            parser.parse(method.getResponseBodyAsStream(), method.getURI().getURI());
        } catch (UnsupportedRDFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (RDFParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new UnauthorizedException();
    } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        throw new QueryInterruptedException();
    } else {
        ErrorInfo errInfo = getErrorInfo(method);

        // Throw appropriate exception
        if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
            throw new MalformedQueryException(errInfo.getErrorMessage());
        } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
            throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
        } else {
            throw new RepositoryException(errInfo.toString());
        }
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

protected boolean getBoolean(HttpMethod method) throws IOException, RepositoryException,
        MalformedQueryException, UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<BooleanQueryResultFormat> booleanFormats = BooleanQueryResultParserRegistry.getInstance().getKeys();
    if (booleanFormats.isEmpty()) {
        throw new RepositoryException("No boolean query result parsers have been registered");
    }/*from   ww  w . ja v a  2 s .  co m*/

    for (BooleanQueryResultFormat format : booleanFormats) {
        // Determine a q-value that reflects the user specified preference
        int qValue = 10;

        if (preferredBQRFormat != null && !preferredBQRFormat.equals(format)) {
            // Prefer specified format over other formats
            qValue -= 2;
        }

        for (String mimeType : format.getMIMETypes()) {
            String acceptParam = mimeType;

            if (qValue < 10) {
                acceptParam += ";q=0." + qValue;
            }

            method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam);
        }
    }

    int httpCode = httpClient.executeMethod(method);

    if (httpCode == HttpURLConnection.HTTP_OK) {
        String mimeType = getResponseMIMEType(method);
        try {
            BooleanQueryResultFormat format = BooleanQueryResultFormat.matchMIMEType(mimeType, booleanFormats);
            BooleanQueryResultParser parser = QueryResultIO.createParser(format);
            return parser.parse(method.getResponseBodyAsStream());
        } catch (UnsupportedQueryResultFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (QueryResultParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new UnauthorizedException();
    } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        throw new QueryInterruptedException();
    } else {
        ErrorInfo errInfo = getErrorInfo(method);

        // Throw appropriate exception
        if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
            throw new MalformedQueryException(errInfo.getErrorMessage());
        } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
            throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
        } else {
            throw new RepositoryException(method.getStatusText());
        }
    }
}

From source file:net.myrrix.client.ClientRecommender.java

private boolean isPartitionReady(int partition) throws TasteException {
    String urlPath = "/ready";

    TasteException savedException = null;
    for (HostAndPort replica : partitions.get(partition)) {
        HttpURLConnection connection = null;
        try {/*from  w w w  .j  ava 2 s  . c  om*/
            connection = buildConnectionToReplica(replica, urlPath, "HEAD");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                return true;
            case HttpURLConnection.HTTP_UNAVAILABLE:
                return false;
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:net.myrrix.client.ClientRecommender.java

private void getAllIDsFromPartition(int partition, boolean user, FastIDSet result) throws TasteException {
    String urlPath = '/' + (user ? "user" : "item") + "/allIDs";

    TasteException savedException = null;
    for (HostAndPort replica : partitions.get(partition)) {
        HttpURLConnection connection = null;
        try {//ww w .j  av  a2s. c  o  m
            connection = buildConnectionToReplica(replica, urlPath, "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                consumeIDs(connection, result);
                return;
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:net.myrrix.client.ClientRecommender.java

private int getNumClusters(boolean user) throws TasteException {
    String urlPath = '/' + (user ? "user" : "item") + "/clusters/count";

    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(0L)) {
        HttpURLConnection connection = null;
        try {//w w w  .  j a v  a2 s. com
            connection = buildConnectionToReplica(replica, urlPath, "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                BufferedReader reader = IOUtils.bufferStream(connection.getInputStream());
                try {
                    return Integer.parseInt(reader.readLine());
                } finally {
                    reader.close();
                }
            case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
                throw new UnsupportedOperationException();
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:net.myrrix.client.ClientRecommender.java

private FastIDSet getCluster(int n, boolean user) throws TasteException {
    String urlPath = '/' + (user ? "user" : "item") + "/clusters/" + n;

    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(0L)) {
        HttpURLConnection connection = null;
        try {/*  w  w  w.ja  va 2  s. c om*/
            connection = buildConnectionToReplica(replica, urlPath, "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                FastIDSet members = new FastIDSet();
                consumeIDs(connection, members);
                return members;
            case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
                throw new UnsupportedOperationException();
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:com.box.androidlib.BoxSynchronous.java

/**
 * Executes an Http request and triggers response parsing by the specified parser.
 * /*ww w. j  ava 2s.c o  m*/
 * @param parser
 *            A BoxResponseParser configured to consume the response and capture data that is of interest
 * @param uri
 *            The Uri of the request
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 */
protected static void saxRequest(final DefaultResponseParser parser, final Uri uri) throws IOException {
    Uri theUri = uri;
    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        Uri.Builder builder = theUri.buildUpon();
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
        theUri = builder.build();
    }

    try {
        final XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xmlReader.setContentHandler(parser);
        HttpURLConnection conn = (HttpURLConnection) (new URL(theUri.toString())).openConnection();
        conn.setRequestProperty("User-Agent", BoxConfig.getInstance().getUserAgent());
        conn.setRequestProperty("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
        conn.setConnectTimeout(BoxConfig.getInstance().getConnectionTimeOut());
        if (mLoggingEnabled) {
            DevUtils.logcat("URL: " + theUri.toString());
            //                Iterator<String> keys = conn.getRequestProperties().keySet().iterator();
            //                while (keys.hasNext()) {
            //                    String key = keys.next();
            //                    DevUtils.logcat("Request Header: " + key + " => " + conn.getRequestProperties().get(key));
            //                }
        }

        int responseCode = -1;
        try {
            conn.connect();
            responseCode = conn.getResponseCode();
            if (mLoggingEnabled)
                DevUtils.logcat("Response Code: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                xmlReader.parse(new InputSource(inputStream));
                inputStream.close();
            } else if (responseCode == -1) {
                parser.setStatus(ResponseListener.STATUS_UNKNOWN_HTTP_RESPONSE_CODE);
            }
        } catch (IOException e) {
            try {
                responseCode = conn.getResponseCode();
            } catch (NullPointerException ee) {
                // Honeycomb devices seem to throw a null pointer exception sometimes which traces to HttpURLConnectionImpl.
            }
            // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
            if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
                parser.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
            } else {
                throw e;
            }
        } finally {
            conn.disconnect();
        }
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    } catch (final SAXException e) {
        e.printStackTrace();
    } catch (final FactoryConfigurationError e) {
        e.printStackTrace();
    }
}