List of usage examples for java.net HttpURLConnection HTTP_INTERNAL_ERROR
int HTTP_INTERNAL_ERROR
To view the source code for java.net HttpURLConnection HTTP_INTERNAL_ERROR.
Click Source Link
From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java
@POST @Path("/repo") @Produces(MediaType.APPLICATION_JSON)//w ww . jav a2s . c om @ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") }) public HttpResponse updateRepository( @ApiParam(value = "Data in JSON", required = true) @ContentParam byte[] contentB) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/gamifier/repo"); long randomLong = new Random().nextLong(); //To be able to match UserAgent userAgent = (UserAgent) getContext().getMainAgent(); // take username as default name String name = userAgent.getLoginName(); System.out.println("User name : " + name); if (name.equals("anonymous")) { return unauthorizedMessage(); } L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_9, "" + randomLong); JSONObject objResponse = new JSONObject(); String content = new String(contentB); if (content.equals(null)) { objResponse.put("message", "Cannot update repository. Cannot parse json data into string"); //L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); L2pLogger.logEvent(this, Event.AGENT_UPLOAD_FAILED, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // if(!initializeDBConnection()){ // objResponse.put("message", "Cannot connect to database"); // L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); // return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); // } JSONObject obj; String originRepositoryName; String newRepositoryName; String fileContent; String appId; String epURL; String aopScript; try { obj = (JSONObject) JSONValue.parseWithException(content); originRepositoryName = stringfromJSON(obj, "originRepositoryName"); newRepositoryName = stringfromJSON(obj, "newRepositoryName"); //fileContent = stringfromJSON(obj,"fileContent"); appId = stringfromJSON(obj, "appId"); epURL = stringfromJSON(obj, "epURL"); aopScript = stringfromJSON(obj, "aopScript"); } catch (ParseException e) { e.printStackTrace(); objResponse.put("message", "Cannot update repository. Cannot parse json data into string. " + 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 repository. Cannot parse json data into string. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // check if repo exist TreeWalk treeWalk = null; Repository newRepository = null; Repository originRepository = null; // helper variables // variables holding content to be modified and added to repository later String widget = null; try { RepositoryHelper.deleteRemoteRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo, gitHubPasswordNewRepo); } catch (GitHubException e) { //e.printStackTrace(); } try { PersonIdent caeUser = new PersonIdent(gitHubUserNewRepo, gitHubUserMailNewRepo); originRepository = RepositoryHelper.getRemoteRepository(originRepositoryName, gitHubOrganizationOrigin); newRepository = RepositoryHelper.generateNewRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo, gitHubPasswordNewRepo); File originDir = originRepository.getDirectory(); // now load the TreeWalk containing the origin repository content treeWalk = RepositoryHelper.getRepositoryContent(originRepositoryName, gitHubOrganizationOrigin); //System.out.println("PATH " + treeWalk.getPathString()); System.out.println("PATH2 " + originDir.getParent()); System.out.println("PATH3 " + newRepository.getDirectory().getParent()); // treeWalk.setFilter(PathFilter.create("frontend/")); ObjectReader reader = treeWalk.getObjectReader(); // walk through the tree and retrieve the needed templates while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = reader.open(objectId); switch (treeWalk.getNameString()) { case "widget.xml": widget = new String(loader.getBytes(), "UTF-8"); break; } } // replace widget.xml //widget = createWidgetCode(widget, htmlElementTemplate, yjsImports, gitHubOrganization, repositoryName, frontendComponent); widget = RepositoryHelper.appendWidget(widget, gitHubOrganizationNewRepo, newRepositoryName); RepositoryHelper.copyFolder(originRepository.getDirectory().getParentFile(), newRepository.getDirectory().getParentFile()); String aopfilestring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/aop.pack.js", Charset.forName("UTF-8")); String oidcwidgetfilestring = RepositoryHelper .readFile("../GamificationGamifierService/jsfiles/oidc-widget.js", Charset.forName("UTF-8")); String gamifierstring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/gamifier.js", Charset.forName("UTF-8")); gamifierstring = gamifierstring.replace("$Application_Id$", appId); gamifierstring = gamifierstring.replace("$Endpoint_URL$", epURL); gamifierstring = gamifierstring.replace("$AOP_Script$", aopScript); // add files to new repository newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "", "widget.xml", widget); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "aop.pack.js", aopfilestring); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "oidc-widget.js", oidcwidgetfilestring); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "gamifier.js", gamifierstring); // stage file Git.wrap(newRepository).add().addFilepattern(".").call(); // commit files Git.wrap(newRepository).commit().setMessage("Generated new repo ").setCommitter(caeUser).call(); // push (local) repository content to GitHub repository "gh-pages" branch RepositoryHelper.pushToRemoteRepository(newRepository, gitHubUserNewRepo, gitHubPasswordNewRepo, "master", "gh-pages"); // close all open resources } catch (GitHubException e1) { // TODO Auto-generated catch block e1.printStackTrace(); objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IOException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (Exception e) { objResponse.put("message", "Cannot update repository. Github exception. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { newRepository.close(); originRepository.close(); treeWalk.close(); } objResponse.put("message", "Updated"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_22, "" + appId); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_23, "" + name); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK); }
From source file:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java
/** * Post a new quest/*from w ww .ja v a2s. c o m*/ * @param appId applicationId * @param contentB content JSON * @return HttpResponse with the returnString */ @POST @Path("/{appId}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Quests upload success ( (questid) )\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (questid)\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the quest. Quest ID already exist!\"}"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Quest ID cannot be null!\"}"), }) @ApiOperation(value = "createNewQuest", notes = "A method to store a new quest with details") public HttpResponse createNewQuest( @ApiParam(value = "Application ID to store a new quest", required = true) @PathParam("appId") String appId, @ApiParam(value = "Quest detail in JSON", required = true) @ContentParam byte[] contentB) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/quests/" + appId); long randomLong = new Random().nextLong(); //To be able to match // parse given multipart form data JSONObject objResponse = new JSONObject(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } String questid = null; 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>>(); boolean questnotifcheck = false; String questnotifmessage = ""; Connection conn = null; try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong); String content = new String(contentB); if (content.equals(null)) { objResponse.put("message", "Cannot create 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); } JSONObject obj = (JSONObject) JSONValue.parseWithException(content); try { if (!questAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot create 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 create 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); } questid = stringfromJSON(obj, "questid"); if (questAccess.isQuestIdExist(conn, appId, questid)) { objResponse.put("message", "Cannot create quest. Failed to add the quest. Quest ID already exist! "); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } questname = stringfromJSON(obj, "questname"); queststatus = stringfromJSON(obj, "queststatus"); questachievementid = stringfromJSON(obj, "questachievementid"); questquestflag = boolfromJSON(obj, "questquestflag"); questpointflag = boolfromJSON(obj, "questpointflag"); questpointvalue = intfromJSON(obj, "questpointvalue"); questactionids = listPairfromJSON(obj, "questactionids", "action", "times"); // OK to be null questdescription = (String) obj.get("questdescription"); if (questdescription.equals(null)) { questdescription = ""; } questquestidcompleted = (String) obj.get("questidcompleted"); if (questquestflag) { if (questquestidcompleted.equals(null)) { objResponse.put("message", "Cannot create 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); } } else { questquestidcompleted = null; } questnotifcheck = boolfromJSON(obj, "questnotificationcheck"); if (questnotifcheck) { questnotifmessage = stringfromJSON(obj, "questnotificationmessage"); } System.out.println(questquestidcompleted); QuestModel model = new QuestModel(questid, questname, questdescription, QuestStatus.valueOf(queststatus), questachievementid, questquestflag, questquestidcompleted, questpointflag, questpointvalue, questnotifcheck, questnotifmessage); model.setActionIds(questactionids); questAccess.addNewQuest(conn, appId, model); objResponse.put("message", "New quest created " + questid); 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 (MalformedStreamException e) { // the stream failed to follow required syntax objResponse.put("message", "Cannot create quest. MalformedStreamException. Failed to upload " + questid + ". " + 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 quest. IO Exception. Failed to upload " + questid + ". " + 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 quest. Database error. " + 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 quest. NullPointerException. Failed to upload " + questid + ". " + 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 create quest. ParseException. Failed to parse JSON. " + 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.netflix.genie.server.resources.CommandConfigResource.java
/** * Delete all applications from database. * * @return All The deleted comamnd//from w w w . j a v a 2s. c o m * @throws GenieException For any error */ @DELETE @ApiOperation(value = "Delete all commands", notes = "Delete all available commands and get them back.", response = Command.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Command not found"), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public List<Command> deleteAllCommands() throws GenieException { LOG.info("called to delete all commands."); return this.commandConfigService.deleteAllCommands(); }
From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java
/** {@inheritDoc} */ @Override/*from w ww . j a v a 2 s.c o m*/ public JobInfoResponse getJobInfo(String jobId) { logger.info("called for jobId: " + jobId); JobInfoResponse response; JobInfoElement jInfo; try { jInfo = pm.getEntity(jobId, JobInfoElement.class); } catch (Exception e) { logger.error("Failed to get job info: ", e); response = new JobInfoResponse( new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage())); return response; } if (jInfo == null) { String msg = "Job not found: " + jobId; logger.error(msg); response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_NOT_FOUND, msg)); return response; } else { response = new JobInfoResponse(); response.setJob(jInfo); response.setMessage("Returning job information for: " + jInfo.getJobID()); return response; } }
From source file:com.netflix.genie.server.resources.ApplicationConfigResource.java
/** * Delete all applications from database. * * @return All The deleted applications/*w w w. j a v a 2 s . c o m*/ * @throws GenieException For any error */ @DELETE @ApiOperation(value = "Delete all applications", notes = "Delete all available applications and get them back.", response = Application.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public List<Application> deleteAllApplications() throws GenieException { LOG.info("Delete all Applications"); return this.applicationConfigService.deleteAllApplications(); }
From source file:rapture.common.client.BaseHttpApi.java
protected String makeRequest(String fn, String request) throws ClientProtocolException, IOException { boolean notInError = true; log.trace("Entering makeRequest (" + fn + "," + request + ")"); while (notInError) { try {/*from www . java 2 s . c o m*/ HttpPost httppost = new HttpPost(fullUrl); MultipartEntity entity = new MultipartEntity(); entity.addPart("FUNCTION", new StringBody(fn)); final byte[] compressedParams = getCompressedParams(request); if (compressedParams != null) { InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(compressedParams), "params.txt") { @Override public long getContentLength() { return compressedParams.length; } }; entity.addPart("PARAMS", isb); } else { entity.addPart("PARAMS", new StringBody(request)); } long length = entity.getContentLength(); // will force it to // recalculate length if (log.isDebugEnabled()) log.trace("Content Length is " + length); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); String responseObjectJson = inputStreamToString(response.getEntity().getContent()).toString(); return responseObjectJson; } catch (IOException e) { log.error(String.format("Got exception during makeRequest. Will try to recover.")); String oldUrl = currentUrl; stateManager.markURLBad(currentUrl); currentUrl = stateManager.getURL(); if (currentUrl == null) { String message = String.format( "Got exception accessing %s, and there are no available Rapture end points", oldUrl); throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, message, e); } httpclient = null; setup(); } } return ""; }
From source file:i5.las2peer.services.servicePackage.TemplateService.java
/** * Example method that shows how to change a user email address in a database. * //from w ww.j a va 2 s .com * 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:com.netflix.genie.server.resources.ClusterConfigResource.java
/** * Delete a cluster configuration./* w ww . j av a 2s .c o m*/ * * @param id unique id for cluster to delete * @return the deleted cluster * @throws GenieException For any error */ @DELETE @Path("/{id}") @ApiOperation(value = "Delete a cluster", notes = "Delete a cluster with the supplied id.", response = Cluster.class) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Cluster not found"), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public Cluster deleteCluster( @ApiParam(value = "Id of the cluster to delete.", required = true) @PathParam("id") final String id) throws GenieException { LOG.info("Delete called for id: " + id); return this.clusterConfigService.deleteCluster(id); }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public String execute(String request, int connectTimeout, int readTimeout) { // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection() // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in // max 1 second. String response = null;//from w w w.ja va 2 s . co m HttpsURLConnection connection = null; try { String correctedRequest = checkSessionToken(request); connection = getConnection(correctedRequest, connectTimeout, readTimeout); if (connection != null) { connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) { if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { response = IOUtils.toString(connection.getErrorStream()); } else { response = IOUtils.toString(connection.getInputStream()); } if (response != null) { if (!response.contains("Authentication failed")) { if (loginCounter > 0) { connectionManager.checkConnection(responseCode); } loginCounter = 0; } else { connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM); loginCounter++; } } } connection.disconnect(); if (response == null && connectionManager != null && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()), connectTimeout, readTimeout); loginCounter++; } else { connectionManager.checkConnection(responseCode); loginCounter++; return null; } } return response; } } catch (SocketTimeoutException e) { informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION); } catch (java.net.ConnectException e) { informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION); } catch (MalformedURLException e) { informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION); } catch (java.net.UnknownHostException e) { informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION); } catch (IOException e) { logger.error("An IOException occurred: ", e); if (connectionManager != null) { informConnectionManager(ConnectionManager.GENERAL_EXCEPTION); } } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java
/** * //from w w w. ja v a 2s. co m * storeGraph * * @param graph a JSONObject * * @return HttpResponse * */ @POST @Path("/") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError"), @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "graphStored") }) @ApiOperation(value = "storeGraph", notes = "") public HttpResponse storeGraph(@ContentParam String graph) { JSONObject graph_JSON = (JSONObject) JSONValue.parse(graph); String insertQuery = ""; int id = (int) graph_JSON.get("graphId"); if (id == -1) { id = 0; // in case of a new graph } String description = (String) graph_JSON.get("description"); JSONArray array = (JSONArray) graph_JSON.get("nodes"); String nodes = array.toJSONString(); array = (JSONArray) graph_JSON.get("links"); String links = array.toJSONString(); Connection conn = null; PreparedStatement stmnt = null; try { conn = dbm.getConnection(); // formulate statement insertQuery = "INSERT INTO graphs ( graphId, description, nodes, links ) " + "VALUES ('" + id + "', '" + description + "', '" + nodes + "', '" + links + "') ON DUPLICATE KEY UPDATE " + "description = + '" + description + "', " + "nodes = + '" + nodes + "', " + "links = + '" + links + "';"; stmnt = conn.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS); // execute query stmnt.executeUpdate(); ResultSet genKeys = stmnt.getGeneratedKeys(); if (genKeys.next()) { int newId = genKeys.getInt(1); // return HTTP response on success with new id String r = newId + ""; HttpResponse graphStored = new HttpResponse(r, HttpURLConnection.HTTP_CREATED); return graphStored; } // return HTTP response on success with id of updated graph String r = id + ""; HttpResponse graphStored = new HttpResponse(r, HttpURLConnection.HTTP_CREATED); return graphStored; } catch (Exception e) { String er = "Internal error: " + e.getMessage(); HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR); return internalError; } finally { // free resources if (stmnt != null) { try { stmnt.close(); } catch (Exception e) { String er = "Internal error: " + e.getMessage(); HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR); return internalError; } } if (conn != null) { try { conn.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); String er = "Internal error: " + e.getMessage(); HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR); return internalError; } } } }