List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED
int HTTP_UNAUTHORIZED
To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.
Click Source Link
From source file:net.sf.eclipsecs.core.config.configtypes.RemoteConfigurationType.java
@Override protected byte[] getBytesFromURLConnection(URLConnection connection) throws IOException { byte[] configurationFileData = null; InputStream in = null;/*from w ww . jav a 2s. c om*/ try { // set timeouts - bug 2941010 connection.setConnectTimeout(10000); connection.setReadTimeout(10000); if (connection instanceof HttpURLConnection) { if (!sFailedWith401URLs.contains(connection.getURL().toString())) { HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setInstanceFollowRedirects(true); httpConn.connect(); if (httpConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { try { RemoteConfigAuthenticator.removeCachedAuthInfo(connection.getURL()); } catch (CheckstylePluginException e) { CheckstyleLog.log(e); } // add to 401ed URLs sFailedWith401URLs.add(connection.getURL().toString()); throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized); } } else { // don't retry since we just get another 401 throw new IOException(Messages.RemoteConfigurationType_msgUnAuthorized); } } in = connection.getInputStream(); configurationFileData = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } return configurationFileData; }
From source file:org.betaconceptframework.astroboa.resourceapi.resource.TopicResource.java
private Response saveTopicSource(String topicSource, String httpMethod, boolean entityIsNew) { logger.debug("Want to save a new topic {}", topicSource); try {/* ww w . ja va2 s. c o m*/ ImportConfiguration configuration = ImportConfiguration.topic().persist(PersistMode.PERSIST_ENTITY_TREE) .build(); Topic topic = astroboaClient.getImportService().importTopic(topicSource, configuration); return ContentApiUtils.createResponseForPutOrPostOfACmsEntity(topic, httpMethod, topicSource, entityIsNew); } catch (CmsUnauthorizedAccessException e) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } catch (Exception e) { logger.error("", e); throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND); } }
From source file:org.openrdf.http.client.HTTPClient.java
public String getServerProtocol() throws IOException, RepositoryException, UnauthorizedException { checkServerURL();//from ww w . ja v a2s . c om GetMethod method = new GetMethod(Protocol.getProtocolLocation(serverURL)); setDoAuthentication(method); try { int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { return method.getResponseBodyAsString(); } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (httpCode == HttpURLConnection.HTTP_NOT_FOUND) { // trying to contact a non-Sesame server? throw new RepositoryException("Failed to get server protocol; no such resource on this server"); } else { ErrorInfo errInfo = getErrorInfo(method); throw new RepositoryException("Failed to get server protocol: " + errInfo); } } finally { releaseConnection(method); } }
From source file:com.github.pascalgn.jiracli.web.HttpClient.java
private <T> T doExecute(HttpUriRequest request, boolean retry, Function<HttpEntity, T> function) { LOGGER.debug("Calling URL: {} [{}]", request.getURI(), request.getMethod()); // disable XSRF check: if (!request.containsHeader("X-Atlassian-Token")) { request.addHeader("X-Atlassian-Token", "nocheck"); }/* w w w . j av a 2 s. c o m*/ HttpResponse response; try { response = httpClient.execute(request, httpClientContext); } catch (IOException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw new IllegalStateException("Could not call URL: " + request.getURI(), e); } } LOGGER.debug("Response received ({})", response.getStatusLine().toString().trim()); HttpEntity entity = response.getEntity(); try { if (Thread.interrupted()) { throw new InterruptedError(); } int statusCode = response.getStatusLine().getStatusCode(); if (isSuccess(statusCode)) { T result; try { result = function.apply(entity, Hint.none()); } catch (NotAuthenticatedException e) { if (retry) { resetAuthentication(); setCredentials(); return doExecute(request, false, function); } else { throw e.getCause(); } } catch (RuntimeException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw e; } } if (Thread.interrupted()) { throw new InterruptedError(); } return result; } else { if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { resetAuthentication(); if (retry) { setCredentials(); return doExecute(request, false, function); } else { String error = readErrorResponse(request.getURI(), entity); LOGGER.debug("Unauthorized [401]: {}", error); throw new AccessControlException("Unauthorized [401]: " + request.getURI()); } } else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) { resetAuthentication(); checkAccountLocked(response); if (retry) { setCredentials(); return doExecute(request, false, function); } else { throw new AccessControlException("Forbidden [403]: " + request.getURI()); } } else { String status = response.getStatusLine().toString().trim(); String message; if (entity == null) { message = status; } else { String error = readErrorResponse(request.getURI(), entity); message = status + (error.isEmpty() ? "" : ": " + error); } if (Thread.interrupted()) { throw new InterruptedError(); } if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) { throw new NoSuchElementException(message); } else { throw new IllegalStateException(message); } } } } finally { EntityUtils.consumeQuietly(entity); } }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Get a default message for an HTTP code. * * @param context the context to use. * @param responseCode the http code. * @param defaultOkMessage an optional message for the ok code. * @return the message.// ww w . ja v a2s. co m */ public static String getMessageForCode(Context context, int responseCode, String defaultOkMessage) { Resources resources = context.getResources(); switch (responseCode) { case HttpURLConnection.HTTP_OK: if (defaultOkMessage != null) { return defaultOkMessage; } else { return resources.getString(R.string.http_ok_msg); } case HttpURLConnection.HTTP_FORBIDDEN: return resources.getString(R.string.http_forbidden_msg); case HttpURLConnection.HTTP_UNAUTHORIZED: return resources.getString(R.string.http_forbidden_msg); case HttpURLConnection.HTTP_NOT_FOUND: return resources.getString(R.string.http_not_found_msg); default: return resources.getString(R.string.http_not_implemented_code_msg) + " " + responseCode; } }
From source file:com.scvngr.levelup.core.net.LevelUpResponse.java
/** * Maps an {@link LevelUpStatus} to an HTTP status code from the response. * * @param statusCode the HTTP status code from the response. * @param serverHeader the value of the Server HTTP header; this is used to validate whether the * response is coming from the LevelUp Platform server or a backup/reverse-proxy. * @return {@link LevelUpStatus} describing the status code. *///from w ww. ja v a 2 s .co m @NonNull @VisibleForTesting(visibility = Visibility.PRIVATE) /* package */static LevelUpStatus mapStatus(final int statusCode, @Nullable final String serverHeader) { final boolean fromLevelUpPlatform = HTTP_HEADER_VALUE_SERVER.equals(serverHeader); final LevelUpStatus status; if (statusCode >= AbstractResponse.STATUS_CODE_SUCCESS_MIN_INCLUSIVE && statusCode < AbstractResponse.STATUS_CODE_SUCCESS_MAX_EXCLUSIVE) { // A 2xx status code is OK. status = LevelUpStatus.OK; } else if (HttpURLConnection.HTTP_NOT_IMPLEMENTED == statusCode && fromLevelUpPlatform) { /* * The API treats a 501 response as a requirement for the client to be upgraded. * However, in failover etc. this response should be ignored since it may have a * different meaning coming from other servers. */ status = LevelUpStatus.UPGRADE; } else if (HttpURLConnection.HTTP_UNAUTHORIZED == statusCode && fromLevelUpPlatform) { /* * The API treats a 401 response as a notice that the user needs a new access token, and * should be logged out. However, if a reverse-proxy or backup server is sending the * response, this should be ignored since it may have a different meaning coming from * other servers. */ status = LevelUpStatus.LOGIN_REQUIRED; } else if (HttpURLConnection.HTTP_NOT_FOUND == statusCode && fromLevelUpPlatform) { /* * Some endpoints (like PaymentToken) have special meanings for 404s, but in failover * they may just indicate a partially-functioning service and should be treated as * generic network errors. */ status = LevelUpStatus.ERROR_NOT_FOUND; } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) { // LevelUp is down for maintenance (applicable even if the Server header differs). status = LevelUpStatus.ERROR_MAINTENANCE; } else { // All other response codes are server errors. status = LevelUpStatus.ERROR_SERVER; } return status; }
From source file:mobi.jenkinsci.alm.assembla.client.AssemblaClient.java
private String getData(final String dataSuffix, final boolean autoLogin) throws IOException { loginWhenNecessary(autoLogin);/* w ww . j a va 2s.c om*/ final HttpGet get = new HttpGet(getTargetUrl(dataSuffix)); setRequestHeaders(get, autoLogin); try { final HttpResponse response = httpClient.execute(get, httpContext); switch (response.getStatusLine().getStatusCode()) { case HttpURLConnection.HTTP_OK: final ByteArrayOutputStream bout = new ByteArrayOutputStream(); final InputStream in = response.getEntity().getContent(); IOUtils.copy(in, bout); return new String(bout.toByteArray()); case HttpURLConnection.HTTP_NO_CONTENT: return null; case HttpURLConnection.HTTP_NOT_FOUND: LOG.warn("Resource at " + dataSuffix + " was not found: returning NULL"); return null; case HttpURLConnection.HTTP_UNAUTHORIZED: if (autoLogin) { loginRefresh(); return getData(dataSuffix, false); } default: throw new IOException("Cannot GET " + dataSuffix + " from Assembla: " + response.getStatusLine()); } } finally { get.releaseConnection(); } }
From source file:org.betaconceptframework.astroboa.resourceapi.resource.TopicResource.java
private Response saveTopic(Topic topic, String httpMethod, String requestContent, boolean entityIsNew) { try {//ww w . java 2 s. co m topic = astroboaClient.getTopicService().save(topic); return ContentApiUtils.createResponseForPutOrPostOfACmsEntity(topic, httpMethod, requestContent, entityIsNew); } catch (CmsUnauthorizedAccessException e) { throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } catch (Exception e) { logger.error("", e); throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND); } }
From source file:codesample.AuthenticationSample.java
/***************************************************************************************************************** * * Perform a call to _bws.echo().// www . j a v a 2 s .c o m * * @return Returns true if echo is successful, and false otherwise. * ***************************************************************************************************************** */ public static boolean echo() throws WebServiceException { final String METHOD_NAME = "echo()"; final String BWS_API_NAME = "_bws.echo()"; logMessage("Entering %s", METHOD_NAME); boolean returnValue = true; EchoRequest request = new EchoRequest(); EchoResponse response = null; request.setMetadata(REQUEST_METADATA); request.setText("Hello World!"); try { logRequest(BWS_API_NAME); response = _bws.echo(request); logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata()); } catch (WebServiceException e) { if (e.getCause() instanceof HTTPException) { HTTPException httpException = (HTTPException) e.getCause(); // Handle authentication failure. if (httpException != null && httpException.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { returnValue = false; logMessage("Failed to authenticate with the BWS web service"); logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue); return returnValue; } } // Log and re-throw exception. logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage()); throw e; } logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue); return returnValue; }
From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java
public static DataInputStream getOdkStream(HttpClient client, String url) throws Exception { // get prefs/*from w w w. j ava2 s .c om*/ HttpPost request = new HttpPost(url); request.setEntity(new OdkAuthEntity()); HttpResponse response = client.execute(request); response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent())); int status = zdis.readInt(); if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { zdis.close(); throw new IOException("Access denied. Check your username and password."); } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) { zdis.close(); throw new IOException(App.getApp().getString(R.string.error_connection)); } else { assert (status == HttpURLConnection.HTTP_OK); // success return zdis; } }