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:org.xframium.integrations.alm.ALMRESTConnection.java
/** * Checks if is authenticated.//www . j a v a 2s . co m * * @return null if authenticated.<br> * a url to authenticate against if not authenticated. * @throws Exception the exception */ public String isAuthenticated() throws Exception { String isAuthenticateUrl = buildUrl("rest/is-authenticated"); String ret; ALMResponse response = httpGet(isAuthenticateUrl, null, null); int responseCode = response.getStatusCode(); // if already authenticated if (responseCode == HttpURLConnection.HTTP_OK) { ret = null; } // if not authenticated - get the address where to authenticate // via WWW-Authenticate else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { Iterable<String> authenticationHeader = response.getResponseHeaders().get("WWW-Authenticate"); String newUrl = authenticationHeader.iterator().next().split("=")[1]; newUrl = newUrl.replace("\"", ""); newUrl += "/authenticate"; ret = newUrl; } // Not ok, not unauthorized. An error, such as 404, or 500 else { throw response.getFailure(); } return ret; }
From source file:co.cask.cdap.client.rest.RestStreamClientTest.java
@Test public void testNotAuthorizedEmptyTokenCreate() throws IOException { AuthenticationClient authClient = Mockito.mock(AuthenticationClient.class); AccessToken accessToken = Mockito.mock(AccessToken.class); Mockito.when(authClient.getAccessToken()).thenReturn(accessToken); Mockito.when(accessToken.getValue()).thenReturn(StringUtils.EMPTY); Mockito.when(accessToken.getTokenType()).thenReturn("Bearer"); streamClient = RestStreamClient.builder(testServerHost, testServerPort).authClient(authClient).build(); try {//from ww w . jav a 2 s . c o m streamClient.create(TestUtils.AUTH_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode()); } }
From source file:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java
/** * Get a quest data with specific ID from database * @param appId applicationId// w ww .jav a 2 s.co m * @param questId quest id * @return HttpResponse returned as JSON object */ @GET @Path("/{appId}/{questId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a quest"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) @ApiOperation(value = "getQuestWithId", notes = "Returns quest detail with specific ID", response = QuestModel.class) public HttpResponse getQuestWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId, @ApiParam(value = "Quest ID") @PathParam("questId") String questId) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/quests/" + appId + "/" + questId); long randomLong = new Random().nextLong(); //To be able to match QuestModel quest = null; Connection conn = null; JSONObject objResponse = new JSONObject(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong); try { if (!questAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot get quest. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot get quest. Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } if (!questAccess.isQuestIdExist(conn, appId, questId)) { objResponse.put("message", "Cannot get quest. Quest not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } quest = questAccess.getQuestWithId(conn, appId, questId); if (quest == null) { objResponse.put("message", "Cannot get quest. Quest Null, Cannot find quest with " + questId); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); String questString = objectMapper.writeValueAsString(quest); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId); return new HttpResponse(questString, HttpURLConnection.HTTP_OK); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get quest. DB Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IOException e) { e.printStackTrace(); objResponse.put("message", "Cannot get quest. Problem in the quest model. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java
private JobIdData submit(String sessionId, InputStream job, MediaType mediaType, Map<String, String> variables) throws Exception { String uriTmpl = restEndpointURL + addSlashIfMissing(restEndpointURL) + "scheduler/submit"; ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory) .build();//from w w w .java2s . c o m ResteasyWebTarget target = client.target(uriTmpl); if (variables != null) { for (String key : variables.keySet()) { target = target.matrixParam(key, variables.get(key)); } } MultipartFormDataOutput formData = new MultipartFormDataOutput(); formData.addFormData("file", job, mediaType); GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(formData) { }; Response response = target.request().header("sessionid", sessionId) .post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Job submission failed status code: %d", response.getStatus()), response); } } return response.readEntity(JobIdData.class); }
From source file:co.cask.cdap.client.rest.RestStreamClientTest.java
@Test public void testNotAuthorizedUnknownTokenCreate() throws IOException { AuthenticationClient authClient = Mockito.mock(AuthenticationClient.class); AccessToken accessToken = Mockito.mock(AccessToken.class); Mockito.when(authClient.getAccessToken()).thenReturn(accessToken); Mockito.when(accessToken.getValue()).thenReturn("test"); Mockito.when(accessToken.getTokenType()).thenReturn("Bearer"); streamClient = RestStreamClient.builder(testServerHost, testServerPort).authClient(authClient).build(); try {//w ww.java 2 s .c o m streamClient.create(TestUtils.AUTH_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode()); } }
From source file:org.betaconceptframework.astroboa.resourceapi.resource.TaxonomyResource.java
private Response saveTaxonomySource(String taxonomySource, String httpMethod, boolean entityIsNew) { logger.debug("Want to save a new taxonomy {}", taxonomySource); try {//www. ja v a2s. c om ImportConfiguration configuration = ImportConfiguration.taxonomy() .persist(PersistMode.PERSIST_ENTITY_TREE).build(); Taxonomy taxonomy = astroboaClient.getImportService().importTaxonomy(taxonomySource, configuration); return ContentApiUtils.createResponseForPutOrPostOfACmsEntity(taxonomy, httpMethod, taxonomySource, 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.projectbuendia.client.ui.OdkActivityLauncher.java
private static void handleSubmitError(VolleyError error) { SubmitXformFailedEvent.Reason reason = SubmitXformFailedEvent.Reason.UNKNOWN; if (error instanceof TimeoutError) { reason = SubmitXformFailedEvent.Reason.SERVER_TIMEOUT; } else if (error.networkResponse != null) { switch (error.networkResponse.statusCode) { case HttpURLConnection.HTTP_UNAUTHORIZED: case HttpURLConnection.HTTP_FORBIDDEN: reason = SubmitXformFailedEvent.Reason.SERVER_AUTH; break; case HttpURLConnection.HTTP_NOT_FOUND: reason = SubmitXformFailedEvent.Reason.SERVER_BAD_ENDPOINT; break; case HttpURLConnection.HTTP_INTERNAL_ERROR: if (error.networkResponse.data == null) { LOG.e("Server error, but no internal error stack trace available."); } else { LOG.e(new String(error.networkResponse.data, Charsets.UTF_8)); LOG.e("Server error. Internal error stack trace:\n"); }/* w w w .j av a 2s . com*/ reason = SubmitXformFailedEvent.Reason.SERVER_ERROR; break; default: reason = SubmitXformFailedEvent.Reason.SERVER_ERROR; break; } } EventBus.getDefault().post(new SubmitXformFailedEvent(reason, error)); }
From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java
/** * Update a level//from w w w. j ava2 s . com * @param appId applicationId * @param levelNum levelNum * @param formData form data * @param contentType content type * @return HttpResponse with the returnString */ @PUT @Path("/{appId}/{levelNum}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Level Updated"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error occured"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad request"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) @ApiOperation(value = "updateLevel", notes = "A method to update an level with details (Level number, level name, level point value, level point id)") public HttpResponse updateLevel( @ApiParam(value = "Application ID to store a new level", required = true) @PathParam("appId") String appId, @PathParam("levelNum") int levelNum, @ApiParam(value = "Content type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Level detail in multiple/form-data type", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "PUT " + "gamification/levels/" + appId + "/" + levelNum); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); String levelname = null; int levelpointvalue = 0; //boolean levelnotifcheck = false; String levelnotifmessage = null; Connection conn = null; UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); try { L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_18, "" + randomLong); try { if (!levelAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot update level. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot update level. Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } if (!levelAccess.isLevelNumExist(conn, appId, levelNum)) { objResponse.put("message", "Cannot update level. Level not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType); if (levelNum == 0) { objResponse.put("message", "Cannot update level. Level ID cannot be null"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } LevelModel model = levelAccess.getLevelWithNumber(conn, appId, levelNum); if (model != null) { FormDataPart partName = parts.get("levelname"); if (partName != null) { levelname = partName.getContent(); if (levelname != null) { model.setName(levelname); } } FormDataPart partPV = parts.get("levelpointvalue"); if (partPV != null) { // optional description text input form element levelpointvalue = Integer.parseInt(partPV.getContent()); if (levelpointvalue != 0) { model.setPointValue(levelpointvalue); } } FormDataPart partNotificationCheck = parts.get("levelnotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked model.useNotification(true); } else { model.useNotification(false); } FormDataPart partNotificationMsg = parts.get("levelnotificationmessage"); if (partNotificationMsg != null) { levelnotifmessage = partNotificationMsg.getContent(); if (levelnotifmessage != null) { model.setNotificationMessage(levelnotifmessage); } } try { levelAccess.updateLevel(conn, appId, model); objResponse.put("message", "Level updated"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_19, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_28, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_29, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot update level. Cannot connect to database. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { // model is null objResponse.put("message", "Cannot update level. Level not found in database"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot update level. DB Error " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (MalformedStreamException e) { // the stream failed to follow required syntax objResponse.put("message", "Cannot update level. Failed to upload " + levelNum + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } catch (IOException e) { // a read or write error occurred objResponse.put("message", "Cannot update level. Failed to upload " + levelNum + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot update level. DB Error " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:com.popdeem.sdk.core.PopdeemSDK.java
/** * @param moment Moment to log//from w ww . java 2 s . c o m * @param callback */ public static void logMoment(@NonNull String moment, @NonNull PDAPICallback<PDBasicResponse> callback) { if (PDSocialUtils.isLoggedInToFacebook() && PDUtils.getUserToken() != null) { PDAPIClient.instance().logMoment(moment, callback); } else { callback.failure(HttpURLConnection.HTTP_UNAUTHORIZED, new IllegalStateException("Not logged in.")); } }