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:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;//w w w .j av a 2s . co m BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:codesample.AuthenticationSample.java
/***************************************************************************************************************** * * Call bwsService.getSystemInfo() and set the _serverType member. * ***************************************************************************************************************** *//*from w w w . jav a2s .co m*/ public static void getSystemInfo() { final String METHOD_NAME = "getSystemInfo()"; final String BWS_API_NAME = "_bws.getSystemInfo()"; logMessage("Entering %s", METHOD_NAME); GetSystemInfoRequest request = new GetSystemInfoRequest(); request.setLoadAuthenticatedUserProperties(false); request.setMetadata(REQUEST_METADATA); GetSystemInfoResponse response = null; /* * The try catch block here is used to illustrate how to handle a specific type of exception. * For example, in this case we check to see if the error was caused by invalid credentials. */ try { logRequest(BWS_API_NAME); response = _bws.getSystemInfo(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) { logMessage("Failed to authenticate with the BWS web service"); } } // Log and re-throw exception. logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage()); throw e; } if (response.getReturnStatus().getCode().equals("SUCCESS")) { if (response.getProperties() != null && !response.getProperties().isEmpty()) { for (Property property : response.getProperties()) { if (property.getName().equalsIgnoreCase("BAS Version")) { if (property.getValue().split("\\.")[0].equals("12")) // 10 is BDS { _serverType = ServerType.BES12; logMessage("ServerType found: BES12/UEM"); } else { _serverType = ServerType.BDS; logMessage("ServerType found: BDS"); } break; } if (property.getName().equalsIgnoreCase("BUDS Version")) { _serverType = ServerType.UDS; logMessage("ServerType found: UDS"); break; } } } else { logMessage("No properties in response"); } } else { System.err.format("Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(), response.getReturnStatus().getMessage()); } logMessage("Exiting %s", METHOD_NAME); }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java
public boolean upload(String sessionId, StreamingOutput output, String encoding, String dataspace, String path) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)).append("data/").append(dataspace); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory) .build();/*w ww.ja v a 2s. com*/ ResteasyWebTarget target = client.target(uriTmpl.toString()).path(path); Response response = null; try { response = target.request().header("sessionid", sessionId).put(Entity.entity(output, new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (Locale) null, encoding))); if (response.getStatus() != HttpURLConnection.HTTP_CREATED) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("File upload failed. Status code: %d" + response.getStatus()), response); } } return true; } finally { if (response != null) { response.close(); } } }
From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java
/** * Function to return http unauthorized message * @return HTTP response unauthorized/*from w w w. ja v a 2 s. c om*/ */ private HttpResponse unauthorizedMessage() { JSONObject objResponse = new JSONObject(); objResponse.put("message", "You are not authorized"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, "Not Authorized"); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_UNAUTHORIZED); }
From source file:com.bigstep.datalake.KerberosIdentityAuthenticator.java
private byte[] readToken() throws IOException, AuthenticationException { int status = conn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_UNAUTHORIZED) { String authHeader = conn.getHeaderField(WWW_AUTHENTICATE); if (authHeader == null || !authHeader.trim().startsWith(NEGOTIATE)) { throw new AuthenticationException( "Invalid SPNEGO sequence, '" + WWW_AUTHENTICATE + "' header incorrect: " + authHeader); }/*from w w w.j ava2s . com*/ String negotiation = authHeader.trim().substring((NEGOTIATE + " ").length()).trim(); return base64.decode(negotiation); } throw new AuthenticationException("Invalid SPNEGO sequence, status code: " + status); }
From source file:i5.las2peer.services.servicePackage.TemplateService.java
/** * Example method that shows how to change a user email address in a database. * //from ww w . j ava2 s . c om * WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! * IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE. * */ @POST @Path("/userEmail/{username}/{email}") @Produces(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Update Confirmation"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Server Error") }) @ApiOperation(value = "setUserEmail", notes = "Example method that changes a user email address in a database." + " WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! " + "IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.") public HttpResponse setUserEmail(@PathParam("username") String username, @PathParam("email") String email) { String result = ""; Connection conn = null; PreparedStatement stmnt = null; ResultSet rs = null; try { conn = dbm.getConnection(); stmnt = conn.prepareStatement("UPDATE users SET email = ? WHERE username = ?;"); stmnt.setString(1, email); stmnt.setString(2, username); int rows = stmnt.executeUpdate(); // same works for insert result = "Database updated. " + rows + " rows affected"; // return return new HttpResponse(result, HttpURLConnection.HTTP_OK); } catch (Exception e) { // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { // free resources if exception or not if (rs != null) { try { rs.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } if (stmnt != null) { try { stmnt.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } if (conn != null) { try { conn.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } } }
From source file:org.sofun.core.security.oauth.OAuthSofunProvider.java
public OAuthRequestToken getRequestToken(String requestToken) throws OAuthException { OAuthRequestToken token = requestTokens.get(requestToken); if (token == null) { throw new OAuthException(HttpURLConnection.HTTP_UNAUTHORIZED, "No such request token " + requestToken); }//from w w w . ja va2 s . c om return token; }
From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java
/** * * @param urlString JIRA URL to connect to * @return VALID if we get a HTTP 200,/* w w w .jav a 2s. co m*/ * UNAUTHORIZED if we get an HTTP 401, * OTHER if we get another HTTP response code, * INVALID if a MalformedURLException or IOException is thrown, * INVALID_CERTIFICATE if a SSLHandshakeException is thrown. */ public ConnectionStatus checkConnectionStatus(String urlString) { LOG.info("Checking to see if we get an HTTP 401 error for the URL '" + urlString + "'"); ConnectionStatus retVal; HttpClient httpClient; try { if (proxyService == null) { httpClient = new HttpClient(); } else { httpClient = proxyService.getClientWithProxyConfig(classToProxy); } GetMethod get = new GetMethod(urlString); int responseCode = httpClient.executeMethod(get); LOG.info("Got HTTP response code of: " + responseCode); if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { retVal = ConnectionStatus.UNAUTHORIZED; } else if (responseCode == HttpURLConnection.HTTP_OK) { retVal = ConnectionStatus.VALID; } else { retVal = ConnectionStatus.OTHER; } } catch (MalformedURLException e) { LOG.warn("URL string of '" + urlString + "' is not a valid URL.", e); retVal = ConnectionStatus.INVALID; } catch (SSLHandshakeException e) { LOG.warn("Certificate Error encountered while trying to find the response code.", e); retVal = ConnectionStatus.INVALID_CERTIFICATE; } catch (IOException e) { LOG.warn("IOException encountered while trying to find the response code: " + e.getMessage(), e); retVal = ConnectionStatus.INVALID; } catch (IllegalArgumentException e) { LOG.warn("IllegalArgumentException encountered while trying to find the response code: " + e.getMessage(), e); retVal = ConnectionStatus.INVALID; } LOG.info("Return value will be " + retVal); return retVal; }
From source file:org.sakaiproject.mediasite.tool.MediasiteContentLaunch.java
private Document Connect() throws AuthenticationException, ParserConfigurationException, SAXException, IOException { java.util.Date startDate = new java.util.Date(); String responseString = ""; String outputString = ""; int responseStatus = -1; try {/*ww w . ja va 2 s. co m*/ responseStatus = this.connection.getResponseCode(); CommonUtilities.WriteLog(String.format("WebApiUtilities.Connect: %s returned %d.", this.connection.getURL().toString(), responseStatus)); if (responseStatus == HttpURLConnection.HTTP_OK) { InputStreamReader isr = new InputStreamReader(this.connection.getInputStream()); BufferedReader in = new BufferedReader(isr); while ((responseString = in.readLine()) != null) { outputString += responseString; } } else if (responseStatus == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad credentials or insufficient privs CommonUtilities.WriteLog(String.format( "WebApiUtilities.Connect: \n\tURL: %s\n\tResponse Code: %s\n\tResponse Message: %s\n\tUser: %s", this.connection.getURL().toString(), responseStatus, this.connection.getResponseMessage(), ""), null, true); throw new AuthenticationException(); } else { String errorMessage = readStream(this.connection.getErrorStream()); CommonUtilities.WriteLog(String.format( "WebApiUtilities.Connect: \n\tURL: %s\n\tResponse Code: %s\n\tResponse Message: %s\n\t%s", this.connection.getURL().toString(), responseStatus, this.connection.getResponseMessage(), errorMessage), null, true); throw new AuthenticationException(); //WebApiHTTPException(responseStatus, null, errorMessage); } } catch (SSLHandshakeException e) { CommonUtilities.WriteLog(String.format( "WebApiUtilities.Connect: An SSL/Certificate error has occurred. Response Code: %s", responseStatus), e, true); } catch (IOException e) { CommonUtilities.WriteLog( String.format("WebApiUtilities.Connect: A general error has occurred. Response Code: %s", responseStatus), e, true); } CommonUtilities.WriteLog("WebApiUtilities.Connect executed in " + (System.currentTimeMillis() - startDate.getTime()) + " milliseconds."); return CommonUtilities.isNullOrEmpty(outputString) ? null : parseXmlFile(outputString); }
From source file:com.murrayc.galaxyzoo.app.provider.test.ZooniverseClientTest.java
public void testUploadWithFailure() throws IOException { final MockWebServer server = new MockWebServer(); final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED); response.setBody("test nonsense failure message"); server.enqueue(response);//from www .j a v a 2 s. c o m server.play(); final ZooniverseClient client = createZooniverseClient(server); final List<NameValuePair> values = new ArrayList<>(); values.add(new BasicNameValuePair("test nonsense", "12345")); try { final boolean result = client.uploadClassificationSync("testAuthName", "testAuthApiKey", values); assertFalse(result); } catch (final ZooniverseClient.UploadException e) { //This is (at least with okhttp.mockwebserver) a normal //event if the upload was refused via an error response code. assertTrue(e.getCause() instanceof IOException); } server.shutdown(); }