List of usage examples for java.net HttpURLConnection HTTP_UNAVAILABLE
int HTTP_UNAVAILABLE
To view the source code for java.net HttpURLConnection HTTP_UNAVAILABLE.
Click Source Link
From source file:net.myrrix.client.ClientRecommender.java
/** * @param userID user for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorerParams optional parameters to send to the server's {@code RescorerProvider} * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if the user is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null *///from w ww.j a v a 2 s.c o m public List<RecommendedItem> recommend(long userID, int howMany, boolean considerKnownItems, String[] rescorerParams) throws TasteException { StringBuilder urlPath = new StringBuilder(); urlPath.append("/recommend/"); urlPath.append(userID); appendCommonQueryParams(howMany, considerKnownItems, rescorerParams, urlPath); TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(userID)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(userID); 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
/** * @param userIDs users for which recommendations are to be computed * @param howMany desired number of recommendations * @param considerKnownItems if true, items that the user is already associated to are candidates * for recommendation. Normally this is {@code false}. * @param rescorerParams optional parameters to send to the server's {@code RescorerProvider} * @return {@link List} of recommended {@link RecommendedItem}s, ordered from most strongly recommend to least * @throws NoSuchUserException if <em>none</em> of {@code userIDs} are known in the model. Otherwise unknown * user IDs are ignored.//from w w w .j a v a2 s .c o m * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs * @throws UnsupportedOperationException if rescorer is not null */ public List<RecommendedItem> recommendToMany(long[] userIDs, int howMany, boolean considerKnownItems, String[] rescorerParams) throws TasteException { StringBuilder urlPath = new StringBuilder(32); urlPath.append("/recommendToMany"); for (long userID : userIDs) { urlPath.append('/').append(userID); } appendCommonQueryParams(howMany, considerKnownItems, rescorerParams, urlPath); // Note that this assumes that all user IDs are on the same partition. It will fail at request // time if not since the partition of the first user doesn't contain the others. TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(userIDs[0])) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchUserException(Arrays.toString(userIDs)); 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:org.eclipse.hono.client.impl.HonoClientImpl.java
/** * Gets an existing or creates a new request-response client for a particular service. * /* www. j ava2 s. c o m*/ * @param key The key to look-up the client by. * @param clientSupplier A consumer for an attempt to create a new client. * @param resultHandler The handler to inform about the outcome of the operation. */ void getOrCreateRequestResponseClient(final String key, final Supplier<Future<RequestResponseClient>> clientSupplier, final Handler<AsyncResult<RequestResponseClient>> resultHandler) { context.runOnContext(get -> { final RequestResponseClient client = activeRequestResponseClients.get(key); if (client != null && client.isOpen()) { LOG.debug("reusing existing client [target: {}]", key); resultHandler.handle(Future.succeededFuture(client)); } else if (!creationLocks.computeIfAbsent(key, k -> Boolean.FALSE)) { // register a handler to be notified if the underlying connection to the server fails // so that we can fail the result handler passed in final Handler<Void> connectionFailureHandler = connectionLost -> { // remove lock so that next attempt to open a sender doesn't fail creationLocks.remove(key); resultHandler .handle(Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "no connection to service"))); }; creationRequests.add(connectionFailureHandler); creationLocks.put(key, Boolean.TRUE); LOG.debug("creating new client for {}", key); clientSupplier.get().setHandler(creationAttempt -> { if (creationAttempt.succeeded()) { LOG.debug("successfully created new client for {}", key); activeRequestResponseClients.put(key, creationAttempt.result()); } else { LOG.debug("failed to create new client for {}", key, creationAttempt.cause()); activeRequestResponseClients.remove(key); } creationLocks.remove(key); creationRequests.remove(connectionFailureHandler); resultHandler.handle(creationAttempt); }); } else { LOG.debug("already trying to create a client for {}", key); resultHandler.handle(Future.failedFuture( new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "no connection to service"))); } }); }
From source file:net.myrrix.client.ClientRecommender.java
@Override public List<RecommendedItem> mostPopularItems(int howMany) throws TasteException { StringBuilder urlPath = new StringBuilder(32); urlPath.append("/mostPopularItems"); appendCommonQueryParams(howMany, false, null, urlPath); // Always send to partition 0 for consistency TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(0L)) { HttpURLConnection connection = null; try {/*from w w w .j a v a 2 s .c o m*/ connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); 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 List<RecommendedItem> anonymousOrSimilar(long[] itemIDs, float[] values, int howMany, String path, String[] rescorerParams, Long contextUserID) throws TasteException { Preconditions.checkArgument(values == null || values.length == itemIDs.length, "Number of values doesn't match number of items"); StringBuilder urlPath = new StringBuilder(); urlPath.append(path);// w ww. j a va2 s. c o m for (int i = 0; i < itemIDs.length; i++) { urlPath.append('/').append(itemIDs[i]); if (values != null) { urlPath.append('=').append(values[i]); } } appendCommonQueryParams(howMany, false, rescorerParams, urlPath); // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on (first0 item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? itemIDs[0] : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(Arrays.toString(itemIDs)); 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
/** * Like {@link #similarityToItem(long, long[])}, but allows caller to specify the user for which the request * is being made. This information does not directly affect the computation, but affects <em>routing</em> * of the request in a distributed context. This is always recommended when there is a user in whose context * the request is being made, as it will ensure that the request can take into account all the latest information * from the user, including very new items that may be in {@code itemIDs}. *///from w w w.j a v a 2 s .c o m public float[] similarityToItem(long toItemID, long[] itemIDs, Long contextUserID) throws TasteException { StringBuilder urlPath = new StringBuilder(32); urlPath.append("/similarityToItem/"); urlPath.append(toItemID); for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } // Requests are typically partitioned by user, but this request does not directly depend on a user. // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other // requests related to that user. Otherwise just partition on (first0 item ID, which is at least // deterministic. long idToPartitionOn = contextUserID == null ? itemIDs[0] : contextUserID; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: BufferedReader reader = IOUtils.bufferStream(connection.getInputStream()); try { float[] result = new float[itemIDs.length]; for (int i = 0; i < itemIDs.length; i++) { result[i] = LangUtils.parseFloat(reader.readLine()); } return result; } finally { reader.close(); } case HttpURLConnection.HTTP_NOT_FOUND: throw new NoSuchItemException(connection.getResponseMessage()); 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:org.openrdf.http.client.SparqlSession.java
protected HttpResponse execute(HttpUriRequest method) throws IOException, OpenRDFException { boolean consume = true; method.setParams(params);//w w w . ja v a 2 s.c o m HttpResponse response = httpClient.execute(method, httpContext); try { int httpCode = response.getStatusLine().getStatusCode(); if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) { consume = false; return response; // everything OK, control flow can continue } else { switch (httpCode) { case HttpURLConnection.HTTP_UNAUTHORIZED: // 401 throw new UnauthorizedException(); case HttpURLConnection.HTTP_UNAVAILABLE: // 503 throw new QueryInterruptedException(); default: ErrorInfo errInfo = getErrorInfo(response); // Throw appropriate exception if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) { throw new RDFParseException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) { throw new UnsupportedRDFormatException(errInfo.getErrorMessage()); } else 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()); } } } } finally { if (consume) { EntityUtils.consumeQuietly(response.getEntity()); } } }
From source file:org.openrdf.http.client.HTTPClient.java
protected void getTupleQueryResult(HttpMethod method, TupleQueryResultHandler handler) throws IOException, TupleQueryResultHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<TupleQueryResultFormat> tqrFormats = TupleQueryResultParserRegistry.getInstance().getKeys(); if (tqrFormats.isEmpty()) { throw new RepositoryException("No tuple query result parsers have been registered"); }/* w w w . j a v a2 s.co m*/ for (TupleQueryResultFormat format : tqrFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredTQRFormat != null && !preferredTQRFormat.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 { TupleQueryResultFormat format = TupleQueryResultFormat.matchMIMEType(mimeType, tqrFormats); TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory()); parser.setTupleQueryResultHandler(handler); 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(errInfo.toString()); } } }
From source file:net.myrrix.client.ClientRecommender.java
/** * <p>Lists the items that were most influential in recommending a given item to a given user. Exactly how this * is determined is left to the implementation, but, generally this will return items that the user prefers * and that are similar to the given item.</p> * * <p>These values by which the results are ordered are opaque values and have no interpretation * other than that larger means stronger.</p> * * @param userID ID of user who was recommended the item * @param itemID ID of item that was recommended * @param howMany maximum number of items to return * @return {@link List} of {@link RecommendedItem}, ordered from most influential in recommended the given * item to least/* w w w . j ava2 s .c o m*/ * @throws NoSuchUserException if the user is not known in the model * @throws NoSuchItemException if the item is not known in the model * @throws NotReadyException if the recommender has no model available yet * @throws TasteException if another error occurs */ @Override public List<RecommendedItem> recommendedBecause(long userID, long itemID, int howMany) throws TasteException { String urlPath = "/because/" + userID + '/' + itemID + "?howMany=" + howMany; TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(userID)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath, "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: return consumeItems(connection); case HttpURLConnection.HTTP_NOT_FOUND: String connectionMessage = connection.getResponseMessage(); if (connectionMessage != null && connectionMessage.contains(NoSuchUserException.class.getSimpleName())) { throw new NoSuchUserException(userID); } else { throw new NoSuchItemException(itemID); } 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:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
protected HttpResponse execute(HttpUriRequest method) throws IOException, RDF4JException { boolean consume = true; if (params != null) { method.setParams(params);// w w w. j av a2s . c o m } HttpResponse response = httpClient.execute(method, httpContext); try { int httpCode = response.getStatusLine().getStatusCode(); if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) { consume = false; return response; // everything OK, control flow can continue } else { switch (httpCode) { case HttpURLConnection.HTTP_UNAUTHORIZED: // 401 throw new UnauthorizedException(); case HttpURLConnection.HTTP_UNAVAILABLE: // 503 throw new QueryInterruptedException(); default: ErrorInfo errInfo = getErrorInfo(response); // Throw appropriate exception if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) { throw new RDFParseException(errInfo.getErrorMessage()); } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) { throw new UnsupportedRDFormatException(errInfo.getErrorMessage()); } else 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 if (errInfo.toString().length() > 0) { throw new RepositoryException(errInfo.toString()); } else { throw new RepositoryException(response.getStatusLine().getReasonPhrase()); } } } } finally { if (consume) { EntityUtils.consumeQuietly(response.getEntity()); } } }