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:com.pocketsoap.salesforce.soap.ChatterClient.java
private String postSuspectsComment(String postId, Map<String, String> suspects, boolean retryOnInvalidSession) throws MalformedURLException, IOException, XMLStreamException, FactoryConfigurationError { URL instanceUrl = new URL(session.instanceServerUrl); URL url = new URL(instanceUrl.getProtocol(), instanceUrl.getHost(), instanceUrl.getPort(), "/services/data/v24.0/chatter/feed-items/" + postId + "/comments"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try {// w w w . j av a2 s.c om conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "OAuth " + session.sessionId); final Comment comment = new Comment(); final List<MessageSegment> messageSegments = comment.getBody().getMessageSegments(); messageSegments.add(new TextMessageSegment("Suspects: ")); Iterator<Entry<String, String>> it = suspects.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> ids = it.next(); String sfdcId = ids.getValue(); if (sfdcId != null) { //Convert the login to an SFDC ID sfdcId = UserService.getUserId(session, sfdcId); } if (sfdcId == null) { //not mapped messageSegments.add(new TextMessageSegment(ids.getKey())); } else { messageSegments.add(new MentionMessageSegment(sfdcId)); } if (it.hasNext()) { messageSegments.add(new TextMessageSegment(", ")); } } final OutputStream bodyStream = conn.getOutputStream(); ObjectMapper mapper = new ObjectMapper(); MappingJsonFactory jsonFactory = new MappingJsonFactory(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(bodyStream); mapper.writeValue(jsonGenerator, comment); bodyStream.close(); conn.getInputStream().close(); //Don't care about the response } catch (IOException e) { if (retryOnInvalidSession && conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { SessionCache.get().revoke(credentials); return postSuspectsComment(postId, suspects, false); } BufferedReader r = new BufferedReader(new InputStreamReader(conn.getErrorStream())); String error = ""; String line; while ((line = r.readLine()) != null) { error += line + '\n'; } System.out.println(error); throw e; } return null; }
From source file:com.mobile.godot.core.controller.CoreController.java
public synchronized void removeCoOwner(String carName, String coOwnerUsername, LoginBean login) { String servlet = "RemoveCoOwner"; List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("carName", carName)); params.add(new BasicNameValuePair("coOwnerUsername", coOwnerUsername)); params.add(new BasicNameValuePair("username", login.getUsername())); params.add(new BasicNameValuePair("password", login.getPassword())); SparseIntArray mMessageMap = new SparseIntArray(); mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.COOWNER_REMOVED); mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED); GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler); Thread tAction = new Thread(action); tAction.start();// w ww . ja v a 2s. co m }
From source file:org.jvnet.hudson.plugins.m2release.nexus.StageClient.java
/** * Check if we have the required permissions for nexus staging. * // w w w . ja v a 2 s . c om * @return * @throws StageException if an exception occurred whilst checking the authorisation. */ public void checkAuthentication() throws StageException { try { URL url = new URL(nexusURL.toString() + "/service/local/status"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); addAuthHeader(conn); int status = conn.getResponseCode(); if (status == 200) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(conn.getInputStream()); /* * check for the following permissions: */ String[] requiredPerms = new String[] { "nexus:stagingprofiles", "nexus:stagingfinish", // "nexus:stagingpromote", "nexus:stagingdrop" }; XPath xpath = XPathFactory.newInstance().newXPath(); for (String perm : requiredPerms) { String expression = "//clientPermissions/permissions/permission[id=\"" + perm + "\"]/value"; Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE); if (node == null) { throw new StageException( "Invalid reponse from server - is the URL a Nexus Professional server?"); } int val = Integer.parseInt(node.getTextContent()); if (val == 0) { throw new StageException( "User has insufficient privaledges to perform staging actions (" + perm + ")"); } } } else { drainOutput(conn); if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new IOException("Incorrect username / password supplied."); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { throw new IOException("Service not found - is this a Nexus server?"); } else { throw new IOException("Server returned error code " + status + "."); } } } catch (IOException ex) { throw createStageExceptionForIOException(nexusURL, ex); } catch (XPathException ex) { throw new StageException(ex); } catch (ParserConfigurationException ex) { throw new StageException(ex); } catch (SAXException ex) { throw new StageException(ex); } }
From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java
/** * Post a new achievement/*from ww w .j a v a 2 s.c o m*/ * @param appId applicationId * @param formData form data * @param contentType content type * @return HttpResponse returned as JSON object */ @POST @Path("/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (achievementid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the achievement. Achievement ID already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Achievement ID cannot be null!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (achievementid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (achievementid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )}") }) @ApiOperation(value = "createNewAchievement", notes = "A method to store a new achievement with details (achievement ID, achievement name, achievement description, achievement point value, achievement point id, achievement badge id") public HttpResponse createNewAchievement( @ApiParam(value = "Application ID to store a new achievement", required = true) @PathParam("appId") String appId, @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Achievement detail in multiple/form-data type", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/achievements/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); String achievementid = null; String achievementname = null; String achievementdesc = null; int achievementpointvalue = 0; String achievementbadgeid = null; boolean achievementnotifcheck = false; String achievementnotifmessage = 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_14, "" + randomLong); try { if (!achievementAccess.isAppIdExist(conn, appId)) { logger.info("App not found >> "); objResponse.put("message", "Cannot create achievement. 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 create achievement. 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); FormDataPart partAchievementID = parts.get("achievementid"); if (partAchievementID != null) { achievementid = partAchievementID.getContent(); if (achievementAccess.isAchievementIdExist(conn, appId, achievementid)) { // Achievement id already exist objResponse.put("message", "Cannot create achievement. Failed to add the achievement. achievement ID already exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } FormDataPart partAchievementName = parts.get("achievementname"); if (partAchievementName != null) { achievementname = partAchievementName.getContent(); } FormDataPart partAchievementDesc = parts.get("achievementdesc"); if (partAchievementDesc != null) { // optional description text input form element achievementdesc = partAchievementDesc.getContent(); } FormDataPart partAchievementPV = parts.get("achievementpointvalue"); if (partAchievementPV != null) { // optional description text input form element achievementpointvalue = Integer.parseInt(partAchievementPV.getContent()); } FormDataPart partAchievementBID = parts.get("achievementbadgeid"); System.out.println("BADGE In Ach : " + partAchievementBID); System.out.println("BADGE In Ach : " + partAchievementBID.getContent()); if (partAchievementBID != null) { // optional description text input form element achievementbadgeid = partAchievementBID.getContent(); } if (achievementbadgeid.equals("")) { achievementbadgeid = null; } FormDataPart partNotificationCheck = parts.get("achievementnotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked achievementnotifcheck = true; } else { achievementnotifcheck = false; } FormDataPart partNotificationMsg = parts.get("achievementnotificationmessage"); if (partNotificationMsg != null) { achievementnotifmessage = partNotificationMsg.getContent(); } else { achievementnotifmessage = ""; } AchievementModel achievement = new AchievementModel(achievementid, achievementname, achievementdesc, achievementpointvalue, achievementbadgeid, achievementnotifcheck, achievementnotifmessage); try { achievementAccess.addNewAchievement(conn, appId, achievement); objResponse.put("message", "Achievement upload success (" + achievementid + ")"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { objResponse.put("message", "Cannot create achievement. Achievement ID cannot be null!"); 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 create achievement. Failed to upload " + achievementid + ". " + 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 create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (NullPointerException e) { e.printStackTrace(); objResponse.put("message", "Cannot create achievement. Failed to upload " + achievementid + ". " + 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.apache.hadoop.fs.http.server.TestHttpFSWithKerberos.java
@Test @TestDir/*from w w w . ja va 2 s . co m*/ @TestJetty @TestHdfs public void testDelegationTokenHttpFSAccess() throws Exception { createHttpFSServer(); KerberosTestUtils.doAsClient(new Callable<Void>() { @Override public Void call() throws Exception { //get delegation token doing SPNEGO authentication URL url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETDELEGATIONTOKEN"); AuthenticatedURL aUrl = new AuthenticatedURL(); AuthenticatedURL.Token aToken = new AuthenticatedURL.Token(); HttpURLConnection conn = aUrl.openConnection(url, aToken); Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK); 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); //access httpfs using the delegation token url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK); //try to renew the delegation token without SPNEGO credentials url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_UNAUTHORIZED); //renew the delegation token with SPNEGO credentials url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr); conn = aUrl.openConnection(url, aToken); conn.setRequestMethod("PUT"); Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK); //cancel delegation token, no need for SPNEGO credentials url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=CANCELDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK); //try to access httpfs with the canceled delegation token url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_UNAUTHORIZED); return null; } }); }
From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java
/** * Post a new action/*from w w w .ja v a 2 s . co m*/ * @param appId applicationId * @param formData form data * @param contentType content type * @return HttpResponse returned as JSON object */ @POST @Path("/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (actionid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the action. Action ID already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Action ID cannot be null!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (actionid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (actionid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )}") }) @ApiOperation(value = "createNewAction", notes = "A method to store a new action with details (action ID, action name, action description,action point value") public HttpResponse createNewAction( @ApiParam(value = "Application ID to store a new action", required = true) @PathParam("appId") String appId, @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Action detail in multiple/form-data type", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/actions/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); String actionid = null; String actionname = null; String actiondesc = null; int actionpointvalue = 0; boolean actionnotifcheck = false; String actionnotifmessage = 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_14, "" + randomLong); try { if (!actionAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot create action. 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 create action. 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); FormDataPart partID = parts.get("actionid"); if (partID != null) { actionid = partID.getContent(); if (actionAccess.isActionIdExist(conn, appId, actionid)) { objResponse.put("message", "Cannot create action. Failed to add the action. action ID already exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } FormDataPart partName = parts.get("actionname"); if (partName != null) { actionname = partName.getContent(); } FormDataPart partDesc = parts.get("actiondesc"); if (partDesc != null) { // optional description text input form element actiondesc = partDesc.getContent(); } FormDataPart partPV = parts.get("actionpointvalue"); if (partPV != null) { // optional description text input form element actionpointvalue = Integer.parseInt(partPV.getContent()); } FormDataPart partNotificationCheck = parts.get("actionnotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked actionnotifcheck = true; } else { actionnotifcheck = false; } FormDataPart partNotificationMsg = parts.get("actionnotificationmessage"); if (partNotificationMsg != null) { actionnotifmessage = partNotificationMsg.getContent(); } else { actionnotifmessage = ""; } ActionModel action = new ActionModel(actionid, actionname, actiondesc, actionpointvalue, actionnotifcheck, actionnotifmessage); try { actionAccess.addNewAction(conn, appId, action); objResponse.put("message", "Action upload success (" + actionid + ")"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { objResponse.put("message", "Cannot create action. Action ID cannot be null!"); 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 create action. Failed to upload " + actionid + ". " + 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 create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (NullPointerException e) { e.printStackTrace(); objResponse.put("message", "Cannot create action. Failed to upload " + actionid + ". " + 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.esri.gpt.control.arcims.ServletConnectorProxy.java
/** * Communicates with redirect url and works as a transparent proxy * // w w w.j a v a 2s . co m * @param request * the servlet request * @param response * the servlet response * @throws IOException * if an exception occurs */ private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpURLConnection httpCon = null; URL redirectURL = null; InputStream input = null; OutputStream output = null; InputStream proxyInput = null; OutputStream proxyOutput = null; try { input = request.getInputStream(); output = response.getOutputStream(); String sQueryStr = request.getQueryString(); String sAuthorization = request.getHeader("Authorization"); String requestBody = readInputCharacters(input); String requestMethod = request.getMethod(); String contentType = request.getContentType(); String encoding = request.getCharacterEncoding(); LOGGER.finer(" Request method = " + requestMethod); LOGGER.finer(" Query string = " + sQueryStr); LOGGER.finer(" Authorization header =" + sAuthorization); LOGGER.finer(" Character Encoding = " + encoding); LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr); redirectURL = new URL(this._redirectURL + "?" + sQueryStr); httpCon = (HttpURLConnection) redirectURL.openConnection(); httpCon.setDoInput(true); httpCon.setDoOutput(true); httpCon.setUseCaches(false); httpCon.setRequestMethod(requestMethod); httpCon.setRequestProperty("Content-type", contentType); if (sAuthorization != null) { httpCon.addRequestProperty("Authorization", sAuthorization); } proxyOutput = httpCon.getOutputStream(); send(requestBody, proxyOutput); String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate"); if (authenticateHdr != null) { LOGGER.finer(" WWW-Authenticate : " + authenticateHdr); response.setHeader("WWW-Authenticate", StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr))); } LOGGER.finer(" Response Code : " + httpCon.getResponseCode()); if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { proxyInput = httpCon.getInputStream(); send(proxyInput, output); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (proxyInput != null) { proxyInput.close(); } if (proxyOutput != null) { proxyOutput.close(); } if (httpCon != null) { httpCon.disconnect(); } } }
From source file:com.axibase.tsd.driver.jdbc.protocol.SdkProtocolImpl.java
private InputStream executeRequest(String method, int queryTimeout, String url) throws AtsdException, IOException, GeneralSecurityException { if (logger.isDebugEnabled()) { logger.debug("[request] {} {}", method, url); }/*w w w .j a v a2s .c o m*/ this.conn = getHttpURLConnection(url); if (contentDescription.isSsl()) { doTrustToCertificates((HttpsURLConnection) this.conn); } setBaseProperties(method, queryTimeout); if (MetadataFormat.HEADER.name().equals(contentDescription.getMetadataFormat()) && StringUtils.isEmpty(contentDescription.getJsonScheme())) { MetadataRetriever.retrieveJsonSchemeFromHeader(conn.getHeaderFields(), contentDescription); } long contentLength = conn.getContentLengthLong(); if (logger.isDebugEnabled()) { logger.debug("[response] " + contentLength); } contentDescription.setContentLength(contentLength); final boolean gzipped = COMPRESSION_ENCODING.equals(conn.getContentEncoding()); final int code = conn.getResponseCode(); InputStream body; if (code != HttpsURLConnection.HTTP_OK) { if (logger.isDebugEnabled()) { logger.debug("Response code: " + code); } if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AtsdException("Wrong credentials provided"); } body = conn.getErrorStream(); if (code != UNSUCCESSFUL_SQL_RESULT_CODE) { try { final String error = GeneralError.errorFromInputStream(body); throw new AtsdRuntimeException(error); } catch (IOException e) { throw new AtsdRuntimeException("HTTP code " + code); } } } else { body = conn.getInputStream(); } return gzipped ? new GZIPInputStream(body) : body; }
From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java
/** * Post a new level/*from www . j a v a 2 s. c om*/ * @param appId applicationId * @param formData form data * @param contentType content type * @return HttpResponse with the returnString */ @POST @Path("/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (levelnum)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the level. levelnum already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Level number cannot be null!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (levelnum)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (levelnum)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Level upload success ( (levelnum) )}") }) @ApiOperation(value = "createLevel", notes = "A method to store a new level with details (Level number, level name, level point value, level point id)") public HttpResponse createLevel( @ApiParam(value = "Application ID to store a new level", required = true) @PathParam("appId") String appId, @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, "POST " + "gamification/levels/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); int levelnum = 0; 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(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong); try { if (!levelAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot create 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 create 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); } Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType); FormDataPart partNum = parts.get("levelnum"); if (partNum != null) { levelnum = Integer.parseInt(partNum.getContent()); if (levelAccess.isLevelNumExist(conn, appId, levelnum)) { // level id already exist objResponse.put("message", "Cannot create level. Failed to add the level. levelnum already exist!"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } FormDataPart partName = parts.get("levelname"); if (partName != null) { levelname = partName.getContent(); } FormDataPart partPV = parts.get("levelpointvalue"); if (partPV != null) { // optional description text input form element levelpointvalue = Integer.parseInt(partPV.getContent()); } FormDataPart partNotificationCheck = parts.get("levelnotificationcheck"); if (partNotificationCheck != null) { // checkbox is checked levelnotifcheck = true; } else { levelnotifcheck = false; } FormDataPart partNotificationMsg = parts.get("levelnotificationmessage"); if (partNotificationMsg != null) { levelnotifmessage = partNotificationMsg.getContent(); } else { levelnotifmessage = ""; } LevelModel model = new LevelModel(levelnum, levelname, levelpointvalue, levelnotifcheck, levelnotifmessage); try { levelAccess.addNewLevel(conn, appId, model); objResponse.put("message", "Level upload success (" + levelnum + ")"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot create 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); } } else { objResponse.put("message", "Cannot create level. Level number cannot be null!"); 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 create 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 create 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 e) { e.printStackTrace(); objResponse.put("message", "Cannot create 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 (NullPointerException e) { e.printStackTrace(); objResponse.put("message", "Cannot create 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); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:org.betaconceptframework.astroboa.resourceapi.resource.SecurityResource.java
private void checkUserIsAuthorizedToUseEncryptionUtility() { //Anonymous user is not authorized to use encryption utility if (astroboaClient.isUserAnonymous()) { logger.warn("Anonymous User tried to use the Resource API encrypt utility for repository " + astroboaClient.getConnectedRepositoryId()); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); }//ww w .j a v a 2 s. c o m }