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.kohsuke.github.Requester.java
/** * Handle API error by either throwing it or by returning normally to retry. *///w w w . jav a2 s . co m /*package*/ void handleApiError(IOException e) throws IOException { int responseCode; try { responseCode = uc.getResponseCode(); } catch (IOException e2) { // likely to be a network exception (e.g. SSLHandshakeException), // uc.getResponseCode() and any other getter on the response will cause an exception if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, "Silently ignore exception retrieving response code for '" + uc.getURL() + "'" + " handling exception " + e, e); throw e; } InputStream es = wrapStream(uc.getErrorStream()); if (es != null) { try { String error = IOUtils.toString(es, "UTF-8"); if (e instanceof FileNotFoundException) { // pass through 404 Not Found to allow the caller to handle it intelligently e = (IOException) new FileNotFoundException(error).initCause(e); } else if (e instanceof HttpException) { HttpException http = (HttpException) e; e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), http.getUrl(), e); } else { e = (IOException) new IOException(error).initCause(e); } } finally { IOUtils.closeQuietly(es); } } if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) // 401 / Unauthorized == bad creds throw e; if ("0".equals(uc.getHeaderField("X-RateLimit-Remaining"))) { root.rateLimitHandler.onError(e, uc); return; } // Retry-After is not documented but apparently that field exists if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && uc.getHeaderField("Retry-After") != null) { this.root.abuseLimitHandler.onError(e, uc); return; } throw e; }
From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java
/** * Update a badge/*from w w w. j ava 2 s . com*/ * @param appId application id * @param badgeId badge id * @param formData form data * @param contentType content type * @return HttpResponse returned as JSON object */ @PUT @Path("/{appId}/{badgeId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Badge 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 = "Update a badge", notes = "A method to update a badge with details (badge ID, badge name, badge description, and badge image") public HttpResponse updateBadge( @ApiParam(value = "Application ID to store a new badge", required = true) @PathParam("appId") String appId, @PathParam("badgeId") String badgeId, @ApiParam(value = "Badge detail in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "PUT " + "gamification/badges/" + appId + "/" + badgeId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); String filename = null; byte[] filecontent = null; String mimeType = null; // Badge ID for the filesystem is appended with app id to make sure it is unique String badgename = null; String badgedescription = null; //boolean badgeusenotification = false; String badgenotificationmessage = null; Connection conn = null; 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_18, "" + randomLong); try { if (!badgeAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot update badge. 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 badge. 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); } Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType); if (badgeId == null) { objResponse.put("message", "Cannot update badge. Badge ID cannot be null"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } BadgeModel currentBadge = badgeAccess.getBadgeWithId(conn, appId, badgeId); if (currentBadge == null) { // currentBadge is null objResponse.put("message", "Cannot update badge. Badge not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } FormDataPart partBadgeName = parts.get("badgename"); if (partBadgeName != null) { badgename = partBadgeName.getContent(); if (badgename != null) { currentBadge.setName(badgename); } } FormDataPart partDescription = parts.get("badgedesc"); if (partDescription != null) { // optional description text input form element badgedescription = partDescription.getContent(); if (badgedescription != null) { currentBadge.setDescription(badgedescription); } } FormDataPart partFilecontent = parts.get("badgeimageinput"); if (partFilecontent != null) { // these data belong to the file input form element filename = partFilecontent.getHeader(HEADER_CONTENT_DISPOSITION).getParameter("filename"); byte[] filecontentbefore = partFilecontent.getContentRaw(); mimeType = partFilecontent.getContentType(); // validate input if (filecontentbefore != null) { try { // in unit test, resize image will turn the image into null BufferedImage // but, it works in web browser FormDataPart partDev = parts.get("dev"); if (partDev != null) { filecontent = filecontentbefore; } else { filecontent = resizeImage(filecontentbefore); } //filecontent = resizeImage(filecontentbefore); storeBadgeDataToSystem(appId, badgeId, filename, filecontent, mimeType, badgedescription); logger.info("upload request (" + filename + ") of mime type '" + mimeType + "' with content length " + filecontent.length); } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException | TimeoutException e) { e.printStackTrace(); objResponse.put("message", "Cannot update badge. Failed to upload " + badgeId + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IllegalArgumentException e) { objResponse.put("message", "Cannot update badge. Badge image is not updated. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } } FormDataPart partNotificationCheck = parts.get("badgenotificationcheck"); if (partNotificationCheck != null) { currentBadge.useNotification(true); } else { currentBadge.useNotification(false); } FormDataPart partNotificationMsg = parts.get("badgenotificationmessage"); if (partNotificationMsg != null) { badgenotificationmessage = partNotificationMsg.getContent(); if (badgenotificationmessage != null) { currentBadge.setNotificationMessage(badgenotificationmessage); } } try { badgeAccess.updateBadge(conn, appId, currentBadge); objResponse.put("message", "Badge 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 badge. Database Error. " + e.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 badge. Failed to upload " + badgeId + ". " + 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 badge. Failed to upload " + badgeId + "." + 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 badge. Database 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:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass, int authRetryCount) throws IOException { T ret = null;/*from w w w. ja va2s. c o m*/ try { if (jsonOutput != null) { writeJson(jsonOutput, conn.getOutputStream()); } } catch (IOException ex) { IOUtils.closeStream(conn.getInputStream()); throw ex; } if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // Ideally, this should happen only when there is an Authentication // failure. Unfortunately, the AuthenticationFilter returns 403 when it // cannot authenticate (Since a 401 requires Server to send // WWW-Authenticate header as well).. KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token(); if (authRetryCount > 0) { String contentType = conn.getRequestProperty(CONTENT_TYPE); String requestMethod = conn.getRequestMethod(); URL url = conn.getURL(); conn = createConnection(url, requestMethod); conn.setRequestProperty(CONTENT_TYPE, contentType); return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1); } } try { AuthenticatedURL.extractToken(conn, authToken); } catch (AuthenticationException e) { // Ignore the AuthExceptions.. since we are just using the method to // extract and set the authToken.. (Workaround till we actually fix // AuthenticatedURL properly to set authToken post initialization) } HttpExceptionUtils.validateResponse(conn, expectedResponse); if (conn.getContentType() != null && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) { ObjectMapper mapper = new ObjectMapper(); InputStream is = null; try { is = conn.getInputStream(); ret = mapper.readValue(is, klass); } finally { IOUtils.closeStream(is); } } return ret; }
From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java
/** * Delete an application data with specified ID * @param appId applicationId// w w w . j a va 2s . c o m * @return HttpResponse with the returnString */ @DELETE @Path("/data/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Delete Application", notes = "This method deletes an App") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Application Deleted"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Application not found"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Application not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error checking app ID exist"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database error"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error delete storage"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) public HttpResponse deleteApplication( @ApiParam(value = "Application ID", required = true) @PathParam("appId") String appId) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "DELETE " + "gamification/applications/data/" + appId); JSONObject objResponse = new JSONObject(); Connection conn = null; UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); if (!applicationAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot delete Application. App not found."); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } try { if (cleanStorage(appId)) { //if(applicationAccess.removeApplicationInfo(appId)){ L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_12, "" + name); if (applicationAccess.deleteApplicationDB(conn, appId)) { objResponse.put("message", "Application deleted"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_13, "" + name); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK); } //} objResponse.put("message", "Cannot delete Application. Database error. "); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException | TimeoutException e) { e.printStackTrace(); L2pLogger.logEvent(Event.RMI_FAILED, "Failed to clean storage"); objResponse.put("message", "RMI error. Failed to clean storage. "); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot delete Application. Error checking app ID exist. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } objResponse.put("message", "Cannot delete Application. Error delete storage."); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); }
From source file:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java
/** * Update a quest/*w w w . j a v a 2 s. c o m*/ * @param appId applicationId * @param questId questId * @param contentB data * @return HttpResponse with the returnString */ @PUT @Path("/{appId}/{questId}") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Quest 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 = "updateQuest", notes = "A method to update a quest with details") public HttpResponse updateQuest( @ApiParam(value = "Application ID to store a new quest", required = true) @PathParam("appId") String appId, @ApiParam(value = "Quest ID") @PathParam("questId") String questId, @ApiParam(value = "Quest detail in JSON", required = true) @ContentParam byte[] contentB) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "PUT " + "gamification/quests/" + appId + "/" + questId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); Connection conn = null; String content = new String(contentB); if (content.equals(null)) { objResponse.put("message", "Cannot update quest. Cannot parse json data into string"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } String questname; String questdescription; String queststatus; String questachievementid; boolean questquestflag = false; String questquestidcompleted = null; boolean questpointflag = false; int questpointvalue = 0; List<Pair<String, Integer>> questactionids = new ArrayList<Pair<String, Integer>>(); 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_18, "" + randomLong); try { if (!questAccess.isAppIdExist(conn, appId)) { logger.info("App not found >> "); objResponse.put("message", "Cannot update 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(); logger.info( "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage()); objResponse.put("message", "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 (questId == null) { logger.info("quest ID cannot be null >> "); objResponse.put("message", "Cannot update quest. quest ID cannot be null"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } QuestModel quest = questAccess.getQuestWithId(conn, appId, questId); if (!questAccess.isQuestIdExist(conn, appId, questId)) { objResponse.put("message", "Cannot update quest. Failed to update the quest. Quest ID is not exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } JSONObject obj = (JSONObject) JSONValue.parseWithException(content); try { questname = stringfromJSON(obj, "questname"); quest.setName(questname); } catch (IOException e) { e.printStackTrace(); logger.info("Cannot parse questname"); } try { queststatus = stringfromJSON(obj, "queststatus"); quest.setStatus(QuestStatus.valueOf(queststatus)); } catch (IOException e) { e.printStackTrace(); } try { questachievementid = stringfromJSON(obj, "questachievementid"); quest.setAchievementId(questachievementid); } catch (IOException e) { e.printStackTrace(); } questdescription = (String) obj.get("questdescription"); if (!questdescription.equals(null)) { quest.setDescription(questdescription); } questquestidcompleted = (String) obj.get("questidcompleted"); if (questquestflag) { if (questquestidcompleted.equals(null) || questquestidcompleted.equals("")) { objResponse.put("message", "Cannot update quest. Completed quest ID cannot be null if it is selected"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } questquestflag = boolfromJSON(obj, "questquestflag"); questpointflag = boolfromJSON(obj, "questpointflag"); questpointvalue = intfromJSON(obj, "questpointvalue"); quest.setQuestFlag(questquestflag); quest.setPointFlag(questpointflag); quest.setQuestIdCompleted(questquestidcompleted); quest.setPointValue(questpointvalue); try { questactionids = listPairfromJSON(obj, "questactionids", "action", "times"); quest.setActionIds(questactionids); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } questAccess.updateQuest(conn, appId, quest); logger.info("Quest Updated "); objResponse.put("message", "Quest updated " + questId); 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 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 (ParseException e) { e.printStackTrace(); objResponse.put("message", "Cannot update quest. ParseExceptionr. " + 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 update quest. Problem with the 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:com.bugclipse.fogbugz.api.client.FogBugzClient.java
private GetMethod connectInternal(String serverURL, IProgressMonitor monitor) throws MarshalException, ValidationException, HttpException, FogBugzClientException, IOException { WebClientUtil.setupHttpClient(httpClient, proxy, serverURL, null, null); for (int attempt = 0; attempt < 2; attempt++) { // force authentication if (!authenticated && hasAuthenticationCredentials()) { monitor.subTask("Authenticating request"); authenticate();//from w w w . java 2 s. c o m if (checkMonitor(monitor)) return null; } String requestUrl = WebClientUtil.getRequestPath(serverURL + "&token=" + token); GetMethod method = new GetMethod(requestUrl); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); int code; try { monitor.subTask("Sending request"); code = httpClient.executeMethod(method); if (checkMonitor(monitor)) return null; } catch (IOException e) { method.releaseConnection(); e.printStackTrace(); throw e; } if (code == HttpURLConnection.HTTP_OK) { return method; } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { // login or re-authenticate due to an expired session method.releaseConnection(); authenticated = false; authenticate(); } else { throw new FogBugzClientException("code = " + code); } } throw new FogBugzClientException("Session might have expired!"); }
From source file:org.wso2.carbon.registry.app.RemoteRegistry.java
public String put(String suggestedPath, Resource resource) throws RegistryException { int idx = suggestedPath.lastIndexOf('/'); String relativePath = suggestedPath.substring(idx + 1); if (Pattern.matches("\\p{Alnum}*[~!@#%^&*()\\+\\;<>\\[\\]{},/\\\\\"\',]+\\p{Alnum}*", relativePath)) { throw new RegistryException("Invalid characters have been used in the resource name. " + relativePath + ". Special characters are ~!@#%^*()+{}[]|\\<>;\"\',"); }/*from ww w. j ava2 s. co m*/ String parentPath = idx > 1 ? suggestedPath.substring(0, idx) : "/"; // Does the resource already exist? If so this is an update (PUT) not a create (POST) // boolean alreadyExists = resourceExists(suggestedPath); //TODO: Needs to implement the REST PUT/POST operations properly. boolean alreadyExists = false; // Until the above fix is made, this is to make sure POST is called all the time. AbderaClient abderaClient = new AbderaClient(abdera); final Factory factory = abdera.getFactory(); boolean isCollection = resource instanceof Collection; ExtensibleElement element; if (isCollection) { Feed feed = factory.newFeed(); feed.setId(baseURI + APPConstants.ATOM + encodeURL(suggestedPath)); // feed.setId(encodeURL(suggestedPath)); feed.setTitle(suggestedPath); feed.setSubtitle(resource.getDescription()); feed.addAuthor(username); feed.setUpdated(new Date()); element = feed; } else { Entry entry = factory.newEntry(); entry.setId(baseURI + APPConstants.ATOM + encodeURL(suggestedPath)); // entry.setId(encodeURL(suggestedPath)); entry.setTitle(suggestedPath); entry.setSummary(resource.getDescription()); entry.addAuthor(username); entry.setUpdated(new Date()); Object content = resource.getContent(); if (content instanceof byte[]) { ByteArrayInputStream in = new ByteArrayInputStream((byte[]) content); entry.setContent(in); } else if (content instanceof InputStream) { entry.setContent((InputStream) content); } else { entry.setContent((String) content); } element = entry; } java.util.Properties properties = resource.getProperties(); addPropertyExtensionElement(properties, factory, element, PropertyExtensionFactory.PROPERTIES, PropertyExtensionFactory.PROPERTY); final String mediaType = resource.getMediaType(); if (mediaType != null && mediaType.length() > 0) { element.addSimpleExtension(new QName(APPConstants.NAMESPACE, APPConstants.NAMESPACE_MEDIA_TYPE), mediaType); } // We are not setting the UUID as the id of the feed since the UUID can be null. Hence we are not changing the old code if (resource.getUUID() != null) { element.addSimpleExtension(APPConstants.QN_UUID_TYPE, resource.getUUID()); } element.addSimpleExtension(new QName(APPConstants.NAMESPACE, "parentPath"), resource.getParentPath()); if (((ResourceImpl) resource).isContentModified()) { element.addSimpleExtension(new QName(APPConstants.NAMESPACE, "contentModified"), "true"); } RequestOptions requestOptions = getAuthorization(); requestOptions.setSlug(relativePath); requestOptions.setAcceptCharset("UTF-8"); ClientResponse resp; //TODO: Needs to implement the REST PUT/POST operations properly. if (!alreadyExists) { resp = abderaClient.post(baseURI + APPConstants.ATOM + encodeURL(parentPath), element, requestOptions); } else { resp = abderaClient.put(baseURI + APPConstants.ATOM + encodeURL(suggestedPath), element, requestOptions); } if (resp.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { abderaClient.teardown(); String msg = "User is not authorized to add the resource to " + suggestedPath; log.error(msg); throw new RegistryException(msg); } else if (resp.getType() != Response.ResponseType.SUCCESS) { String msg = "Add resource fail. Suggested Path: " + suggestedPath + ", Response Status: " + resp.getStatus() + ", Response Type: " + resp.getType(); abderaClient.teardown(); log.error(msg); throw new RegistryException(msg); } // ResourceImpl impl = (ResourceImpl)resource; // impl.setPath(resultPath); // // todo - fix this to use util routine? // int i = resultPath.lastIndexOf('/'); // impl.setParentPath(i == 0 ? "/" : resultPath.substring(0, i)); abderaClient.teardown(); if (resp.getLocation() != null) { String location = resp.getLocation().toString(); if (location != null) { if (location.startsWith(baseURI)) { return location.substring(baseURI.length() + APPConstants.ATOM.length()).replace("+", " "); } return location.replace("+", " "); } } return suggestedPath; }
From source file:org.eclipse.orion.server.tests.servlets.git.GitCloneTest.java
@Test public void testCloneOverSshWithNoPassword() throws Exception { Assume.assumeTrue(sshRepo != null);//from w w w . ja va 2 s .c o m Assume.assumeTrue(knownHosts != null); URI workspaceLocation = createWorkspace(getMethodName()); IPath workspacePath = new Path("workspace").append(getWorkspaceId(workspaceLocation)).makeAbsolute(); URIish uri = new URIish(sshRepo); WebRequest request = new PostGitCloneRequest().setURIish(uri).setWorkspacePath(workspacePath) .setName(getMethodName()).setKnownHosts(knownHosts).getWebRequest(); // cloning WebResponse response = webConversation.getResponse(request); ServerStatus status = waitForTask(response); assertFalse(status.toString(), status.isOK()); // task completed, but cloning failed assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, status.getHttpCode()); assertEquals("Auth fail", status.getMessage()); assertEquals("Auth fail", status.getJsonData().getString("DetailedMessage")); // no project should be created request = new GetMethodWebRequest(workspaceLocation.toString()); setAuthentication(request); response = webConversation.getResponse(request); JSONObject workspace = new JSONObject(response.getText()); assertEquals(0, workspace.getJSONArray(ProtocolConstants.KEY_CHILDREN).length()); }
From source file:org.apache.hadoop.fs.http.server.TestHttpFSServer.java
@Test @TestDir// w w w.j av a 2 s .c o m @TestJetty @TestHdfs public void testDelegationTokenOperations() throws Exception { createHttpFSServer(true); URL url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); AuthenticationToken token = new AuthenticationToken("u", "p", new KerberosDelegationTokenAuthenticationHandler().getType()); token.setExpires(System.currentTimeMillis() + 100000000); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET, "secret"); secretProvider.init(secretProviderProps, null, -1); Signer signer = new Signer(secretProvider); String tokenSigned = signer.sign(token.toString()); url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", AuthenticatedURL.AUTH_COOKIE + "=" + tokenSigned); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETDELEGATIONTOKEN"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", AuthenticatedURL.AUTH_COOKIE + "=" + tokenSigned); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); JSONObject json = (JSONObject) new JSONParser().parse(new InputStreamReader(conn.getInputStream())); json = (JSONObject) json.get(DelegationTokenAuthenticator.DELEGATION_TOKEN_JSON); String tokenStr = (String) json.get(DelegationTokenAuthenticator.DELEGATION_TOKEN_URL_STRING_JSON); url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("Cookie", AuthenticatedURL.AUTH_COOKIE + "=" + tokenSigned); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=CANCELDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode()); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitCloneTest.java
@Test public void testCloneOverSshWithBadPassword() throws Exception { Assume.assumeTrue(sshRepo != null);//from w w w. ja va 2s .co m Assume.assumeTrue(knownHosts != null); URI workspaceLocation = createWorkspace(getMethodName()); URIish uri = new URIish(sshRepo); IPath workspacePath = new Path("workspace").append(getWorkspaceId(workspaceLocation)).makeAbsolute(); WebRequest request = new PostGitCloneRequest().setURIish(uri).setWorkspacePath(workspacePath) .setKnownHosts(knownHosts).setPassword("I'm bad".toCharArray()).getWebRequest(); // cloning WebResponse response = webConversation.getResponse(request); ServerStatus status = waitForTask(response); assertFalse(status.toString(), status.isOK()); // task completed, but cloning failed assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, status.getHttpCode()); assertEquals("Auth fail", status.getMessage()); assertEquals("Auth fail", status.getJsonData().getString("DetailedMessage")); // no project should be created request = new GetMethodWebRequest(workspaceLocation.toString()); setAuthentication(request); response = webConversation.getResponse(request); JSONObject workspace = new JSONObject(response.getText()); assertEquals(0, workspace.getJSONArray(ProtocolConstants.KEY_CHILDREN).length()); }