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:org.wso2.carbon.registry.app.ResourceServlet.java
/** * Logic that will be executed for a get request. * * @param request the HTTP Servlet request. * @param response the HTTP Servlet response. * * @throws IOException if an error occurred. *//*w ww . java 2s . co m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String uri = request.getRequestURI(); int idx = uri.indexOf("resource"); String path = uri.substring(idx + 8); if (path == null) { String msg = "Could not get the resource content. Path is not specified."; log.error(msg); response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); return; } Resource resource; try { UserRegistry registry = Utils.getRegistry(request); try { path = new URI(path).normalize().toString(); } catch (URISyntaxException e) { log.error("Unable to normalize requested resource path: " + path, e); } String decodedPath = URLDecoder.decode(path, RegistryConstants.DEFAULT_CHARSET_ENCODING); CurrentSession.setUserRealm(registry.getUserRealm()); CurrentSession.setUser(registry.getUserName()); try { if (!AuthorizationUtils.authorize( RegistryUtils.getAbsolutePath(registry.getRegistryContext(), decodedPath), ActionConstants.GET)) { response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return; } resource = registry.get(decodedPath); } finally { CurrentSession.removeUserRealm(); CurrentSession.removeUser(); } } catch (AuthorizationFailedException e) { log.error(e.getMessage()); response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\""); return; } catch (RegistryException e) { String msg = "Error retrieving the resource " + path + ". " + e.getMessage(); log.error(msg, e); throw e; } if (resource instanceof Collection) { String msg = "Could not get the resource content. Path " + path + " refers to a collection."; log.error(msg); response.setStatus(HttpURLConnection.HTTP_NOT_IMPLEMENTED); return; } // date based conditional get long ifModifiedSinceValue = request.getDateHeader("If-Modified-Since"); long lastModifiedValue = resource.getLastModified().getTime(); if (ifModifiedSinceValue > 0) { // convert the time values from milliseconds to seconds ifModifiedSinceValue /= 1000; lastModifiedValue /= 1000; /* condition to check we have latest updates in terms of dates */ if (ifModifiedSinceValue >= lastModifiedValue) { /* no need to response with data */ response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED); return; } } response.setDateHeader("Last-Modified", lastModifiedValue); // eTag based conditional get String ifNonMatchValue = request.getHeader("if-none-match"); String currentETag = Utils.calculateEntityTag(resource); if (ifNonMatchValue != null) { if (ifNonMatchValue.equals(currentETag)) { /* the version is not modified */ response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED); return; } } response.setHeader("ETag", currentETag); if (resource.getMediaType() != null && resource.getMediaType().length() > 0) { response.setContentType(resource.getMediaType()); } else { response.setHeader("Content-Disposition", "attachment; filename=" + RegistryUtils.getResourceName(path)); response.setContentType("application/download"); } InputStream contentStream = null; if (resource.getContent() != null) { contentStream = resource.getContentStream(); } if (contentStream != null) { try { ServletOutputStream servletOutputStream = response.getOutputStream(); byte[] contentChunk = new byte[RegistryConstants.DEFAULT_BUFFER_SIZE]; int byteCount; while ((byteCount = contentStream.read(contentChunk)) != -1) { servletOutputStream.write(contentChunk, 0, byteCount); } response.flushBuffer(); servletOutputStream.flush(); } finally { contentStream.close(); } } else { Object content = resource.getContent(); if (content != null) { if (content instanceof byte[]) { ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write((byte[]) content); response.flushBuffer(); servletOutputStream.flush(); } else { PrintWriter writer = response.getWriter(); writer.write(content.toString()); writer.flush(); } } } resource.discard(); } catch (RegistryException e) { String msg = "Failed to get resource content. " + e.getMessage(); log.error(msg, e); response.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR); } }
From source file:rapture.repo.VersionedRepo.java
@Override public void addDocuments(List<String> keys, String value, String user, String comment) { // We want to add these displayNames, but point them to the same // document content String context = IDGenerator.getUUID(); LockHandle lockHandle = lockHandler.acquireLock(context, DEFAULT_STAGE, 5, 5); if (lockHandle != null) { try {//w w w .jav a 2 s. c o m // Create a new stage to be consistent createStage(DEFAULT_STAGE); addToStage(DEFAULT_STAGE, keys, value, false); commitStage(DEFAULT_STAGE, user, comment); for (String x : keys) { cacheKeyStore.put(x, value); } } finally { lockHandler.releaseLock(context, DEFAULT_STAGE, lockHandle); } } else { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Could not get lock for write"); } }
From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java
/** {@inheritDoc} */ @Override//from w w w .ja va2 s . c o m public JobInfoResponse submitJob(JobInfoRequest jir) { logger.info("called"); JobInfoResponse response; JobInfoElement jInfo = jir.getJobInfo(); // validate parameters try { validateJobParams(jInfo); } catch (CloudServiceException e) { response = new JobInfoResponse(e); return response; } // ensure that job won't overload system // synchronize until an entry is created and INIT-ed in DB // throttling related parameters int maxRunningJobs = conf.getInt("netflix.genie.server.max.running.jobs", 0); int jobForwardThreshold = conf.getInt("netflix.genie.server.forward.jobs.threshold", 0); int maxIdleHostThreshold = conf.getInt("netflix.genie.server.max.idle.host.threshold", 0); int idleHostThresholdDelta = conf.getInt("netflix.genie.server.idle.host.threshold.delta", 0); synchronized (this) { try { int numRunningJobs = JobCountManager.getNumInstanceJobs(); logger.info("Number of running jobs: " + numRunningJobs); // find an instance with fewer than (numRunningJobs - // idleHostThresholdDelta) int idleHostThreshold = numRunningJobs - idleHostThresholdDelta; // if numRunningJobs is already >= maxRunningJobs, forward // aggressively // but cap it at the max if ((idleHostThreshold > maxIdleHostThreshold) || (numRunningJobs >= maxRunningJobs)) { idleHostThreshold = maxIdleHostThreshold; } // check to see if job should be forwarded - only forward it // once. the assumption is that jobForwardThreshold < maxRunningJobs // (set in properties file) if ((numRunningJobs >= jobForwardThreshold) && (!jInfo.isForwarded())) { logger.info( "Number of running jobs greater than forwarding threshold - trying to auto-forward"); String idleHost = JobCountManager.getIdleInstance(idleHostThreshold); if (!idleHost.equals(NetUtil.getHostName())) { jInfo.setForwarded(true); stats.incrGenieForwardedJobs(); response = forwardJobRequest( "http://" + idleHost + ":" + serverPort + "/" + jobResourcePrefix, jir); return response; } // else, no idle hosts found - run here if capacity exists } if (numRunningJobs >= maxRunningJobs) { // if we get here, job can't be forwarded to an idle // instance anymore and current node is overloaded response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_UNAVAILABLE, "Number of running jobs greater than system limit (" + maxRunningJobs + ") - try another instance or try again later")); return response; } // if job can be launched, update the URIs buildJobURIs(jInfo); } catch (CloudServiceException e) { response = new JobInfoResponse(e); logger.error(response.getErrorMsg(), e); return response; } // init state in DB - return if job already exists try { pm.createEntity(jInfo); } catch (RollbackException e) { logger.error("Can't create entity in the database", e); if (e.getCause() instanceof EntityExistsException) { logger.error(e.getCause().getMessage()); // most likely entity already exists - return useful message response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_CONFLICT, "Job already exists for id: " + jInfo.getJobID())); return response; } else { // unknown exception - send it back response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, "Received exception: " + e.getCause())); return response; } } } // end synchronize // increment number of submitted jobs stats.incrGenieJobSubmissions(); // try to run the job - return success or error try { JobManagerFactory.getJobManager(jInfo.getJobType()).launch(jInfo); // update entity in DB jInfo.setUpdateTime(System.currentTimeMillis()); pm.updateEntity(jInfo); // verification jInfo = pm.getEntity(jInfo.getJobID(), JobInfoElement.class); // return successful response response = new JobInfoResponse(); response.setMessage("Successfully launched job: " + jInfo.getJobID()); response.setJob(jInfo); return response; } catch (Exception e) { logger.error("Failed to submit job: ", e); // update db jInfo.setJobStatus(JobStatus.FAILED, e.getMessage()); jInfo.setUpdateTime(System.currentTimeMillis()); pm.updateEntity(jInfo); // increment counter for failed jobs stats.incrGenieFailedJobs(); // if it is a known exception, handle differently if (e instanceof CloudServiceException) { response = new JobInfoResponse((CloudServiceException) e); } else { response = new JobInfoResponse( new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage())); } return response; } }
From source file:nl.ru.cmbi.vase.web.rest.JobRestResource.java
@MethodMapping(value = "/hsspresult/{id}", httpMethod = HttpMethod.GET, produces = RestMimeTypes.TEXT_PLAIN) public String hsspResult(String id) { if (Config.isXmlOnly()) { log.warn("rest/hsspresult was requested, but not enabled"); // hssp job submission is not allowed if hssp is turned off throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND); }//from w ww. j a va 2 s . c o m File hsspFile = new File(Config.getHSSPCacheDir(), id + ".hssp.bz2"); String jobStatus = this.status(id); try { if (jobStatus.equals("SUCCESS") && hsspFile.isFile()) { StringWriter sw = new StringWriter(); InputStream hsspIn = new BZip2CompressorInputStream(new FileInputStream(hsspFile)); IOUtils.copy(hsspIn, sw); hsspIn.close(); sw.close(); return sw.toString(); } URL url = new URL(hsspRestURL + "/result/pdb_file/hssp_stockholm/" + id + "/"); Writer writer = new StringWriter(); IOUtils.copy(url.openStream(), writer); writer.close(); JSONObject output = new JSONObject(writer.toString()); String result = output.getString("result"); if (jobStatus.equals("SUCCESS") && Config.hsspPdbCacheEnabled()) { // Write it to the cache: OutputStream fileOut = new BZip2CompressorOutputStream(new FileOutputStream(hsspFile)); IOUtils.write(result, fileOut); fileOut.close(); } else return ""; return result; } catch (Exception e) { log.error(e.getMessage(), e); throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR); } }
From source file:org.mulesoft.restx.clientapi.RestxServer.java
/** * Used to send requests to the server. The right headers are assembled and a * suitable HTTP method will be selected if not specified by the caller. * /*from www . ja va2 s. co m*/ * @param url The URL on the server to which the request should be sent. Since * this relies on an established server connection, the URL here is * just the path component of the URL (including possible query * parameters), starting with '/'. * @param data Any data we want to send with the request (in case of PUT or * POST). If data is specified, but no method is given, then the * method will default to POST. If a method is specified as well then * it must be POST or PUT. If no data should be sent then this should * be 'null'. * @param method The desired HTTP method of the request. * @param status The expected status. If the HTTP status from the server is * different than the expected status, an exception will be thrown. If * no status check should be performed then set this to 'null'. * @param headers A {@link HashMap<String, String>} in which any additional * request headers should be specified. For example: { "Accept" : * "application/json" }. The hash map will not be modified by this * method. * @return A {@link HttpResult} object with status and data that was returned by * the server. * @throws RestxClientException */ public HttpResult send(String url, String data, HttpMethod method, Integer status, HashMap<String, String> headers) throws RestxClientException { // Set default values for the method if nothing was specified. Depends on // whether we want to send data or not. if (method == null) { if (data == null) { method = HttpMethod.GET; } else { method = HttpMethod.POST; } } // Combine default headers with any additional headers if (headers == null) { headers = DEFAULT_REQ_HEADERS; } else { final HashMap<String, String> hm = new HashMap<String, String>(headers); for (final String name : DEFAULT_REQ_HEADERS.keySet()) { hm.put(name, DEFAULT_REQ_HEADERS.get(name)); } headers = hm; } URL fullUrl = null; HttpURLConnection conn = null; try { if (!url.startsWith("/")) { url = "/" + url; } fullUrl = new URL(serverUri + url); conn = (HttpURLConnection) fullUrl.openConnection(); // Set the request headers for (final Entry<String, String> header : headers.entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } // Set the request method conn.setRequestMethod(HttpMethod.toString(method)); // Send the message body if (data != null) { conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); try { wr.write(data); } finally { wr.close(); } } // Get the response final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; final StringBuffer buf = new StringBuffer(); while ((line = rd.readLine()) != null) { // For now we do nothing particularly efficient. We just assemble all // the data we get into a big string. buf.append(line); } rd.close(); final int respStatus = conn.getResponseCode(); if (status != null) { if (status != respStatus) { if (buf.length() > 256) { buf.delete(256, buf.length()); } throw new RestxClientException("Status code " + status + " was expected for request to '" + fullUrl + "'. Instead we received " + respStatus + " " + buf); } } return new HttpResult(conn.getResponseCode(), buf.toString()); } catch (final IOException e) { if (conn != null) { // This exception was thrown after we started to connect to the // server int code; String msg; try { // We may even have an initialised response already, in which // case // we are passing that information back to the caller. code = conn.getResponseCode(); msg = conn.getResponseMessage(); } catch (final IOException e1) { // The problem occurred before the response status in the HTTP // connection was initialised. code = HttpURLConnection.HTTP_INTERNAL_ERROR; msg = e.getMessage(); } if (status != null) { if (status != code) { throw new RestxClientException("Status code " + status + " was expected for request to '" + fullUrl + "'. Instead we received " + code); } } return new HttpResult(code, msg); } // The exception was thrown before we even initialised our connection throw new RestxClientException("Cannot connect with URI '" + fullUrl + "': " + e.getMessage()); } }
From source file:org.intermine.webservice.client.util.HttpConnection.java
/** * Handles an error response received while executing a service request. * Throws a {@link ServiceException} or one of its subclasses, depending on * the failure conditions.//from w w w.j a v a 2 s . co m * * @throws ServiceException exception describing the failure. * @throws IOException error reading the error response from the * service. */ protected void handleErrorResponse() throws IOException { String message = executedMethod.getResponseBodyAsString(); try { JSONObject jo = new JSONObject(message); message = jo.getString("error"); } catch (JSONException e) { // Pass } switch (executedMethod.getStatusCode()) { case HttpURLConnection.HTTP_NOT_FOUND: throw new ResourceNotFoundException(this); case HttpURLConnection.HTTP_BAD_REQUEST: if (message != null) { throw new BadRequestException(message); } else { throw new BadRequestException(this); } case HttpURLConnection.HTTP_FORBIDDEN: if (message != null) { throw new ServiceForbiddenException(message); } else { throw new ServiceForbiddenException(this); } case HttpURLConnection.HTTP_NOT_IMPLEMENTED: throw new NotImplementedException(this); case HttpURLConnection.HTTP_INTERNAL_ERROR: if (message != null) { throw new InternalErrorException(message); } else { throw new InternalErrorException(this); } case HttpURLConnection.HTTP_UNAVAILABLE: throw new ServiceUnavailableException(this); default: if (message != null) { throw new ServiceException(message); } else { throw new ServiceException(this); } } }
From source file:org.apache.hadoop.yarn.server.webproxy.TestWebAppProxyServlet.java
/** * Test main method of WebAppProxyServer *///from w ww. ja v a2s. c om @Test(timeout = 5000) public void testWebAppProxyServerMainMethod() throws Exception { WebAppProxyServer mainServer = null; Configuration conf = new YarnConfiguration(); conf.set(YarnConfiguration.PROXY_ADDRESS, "localhost:9099"); try { mainServer = WebAppProxyServer.startServer(conf); int counter = 20; URL wrongUrl = new URL("http://localhost:9099/proxy/app"); HttpURLConnection proxyConn = null; while (counter > 0) { counter--; try { proxyConn = (HttpURLConnection) wrongUrl.openConnection(); proxyConn.connect(); proxyConn.getResponseCode(); // server started ok counter = 0; } catch (Exception e) { Thread.sleep(100); } } assertNotNull(proxyConn); // wrong application Id assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, proxyConn.getResponseCode()); } finally { if (mainServer != null) { mainServer.stop(); } } }
From source file:com.netflix.genie.server.resources.JobResource.java
/** * Get jobs for given filter criteria.//ww w. j a v a 2 s . c o m * * @param id id for job * @param name name of job (can be a SQL-style pattern such as HIVE%) * @param userName user who submitted job * @param statuses statuses of jobs to find * @param tags tags for the job * @param clusterName the name of the cluster * @param clusterId the id of the cluster * @param commandName the name of the command run by the job * @param commandId the id of the command run by the job * @param page page number for job * @param limit max number of jobs to return * @param descending Whether the order of the results should be descending or ascending * @param orderBys Fields to order the results by * @return successful response, or one with HTTP error code * @throws GenieException For any error */ @GET @ApiOperation(value = "Find jobs", notes = "Find jobs by the submitted criteria.", response = Job.class, responseContainer = "List") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job not found"), @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") }) public List<Job> getJobs(@ApiParam(value = "Id of the job.") @QueryParam("id") final String id, @ApiParam(value = "Name of the job.") @QueryParam("name") final String name, @ApiParam(value = "Name of the user who submitted the job.") @QueryParam("userName") final String userName, @ApiParam(value = "Statuses of the jobs to fetch.", allowableValues = "INIT, RUNNING, SUCCEEDED, KILLED, FAILED") @QueryParam("status") final Set<String> statuses, @ApiParam(value = "Tags for the job.") @QueryParam("tag") final Set<String> tags, @ApiParam(value = "Name of the cluster on which the job ran.") @QueryParam("executionClusterName") final String clusterName, @ApiParam(value = "Id of the cluster on which the job ran.") @QueryParam("executionClusterId") final String clusterId, @ApiParam(value = "The page to start on.") @QueryParam("commandName") final String commandName, @ApiParam(value = "Id of the cluster on which the job ran.") @QueryParam("commandId") final String commandId, @ApiParam(value = "The page to start on.") @QueryParam("page") @DefaultValue("0") final int page, @ApiParam(value = "Max number of results per page.") @QueryParam("limit") @DefaultValue("1024") final int limit, @ApiParam(value = "Whether results should be sorted in descending or ascending order. Defaults to descending") @QueryParam("descending") @DefaultValue("true") final boolean descending, @ApiParam(value = "The fields to order the results by. Must not be collection fields. Default is updated.") @QueryParam("orderBy") final Set<String> orderBys) throws GenieException { LOG.info("Called with [id | jobName | userName | statuses | executionClusterName " + "| executionClusterId | page | limit | descending | orderBys]"); LOG.info(id + " | " + name + " | " + userName + " | " + statuses + " | " + tags + " | " + clusterName + " | " + clusterId + " | " + commandName + " | " + commandId + " | " + page + " | " + limit + " | " + descending + " | " + orderBys); Set<JobStatus> enumStatuses = null; if (!statuses.isEmpty()) { enumStatuses = EnumSet.noneOf(JobStatus.class); for (final String status : statuses) { if (StringUtils.isNotBlank(status)) { enumStatuses.add(JobStatus.parse(status)); } } } return this.jobService.getJobs(id, name, userName, enumStatuses, tags, clusterName, clusterId, commandName, commandId, page, limit, descending, orderBys); }
From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java
/** * Create a new app/*from ww w . j a v a 2s. c o m*/ * * @param contentType form content type * @param formData form data * @return Application data in JSON */ @POST @Path("/data") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "createApplication", notes = "Method to create a new application") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database Error"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error in parsing form data"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID already exist"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID cannot be empty"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Error checking app ID exist"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "New application created") }) public HttpResponse createApplication( @ApiParam(value = "Application detail in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType, @ApiParam(value = "Content of form data", required = true) @ContentParam byte[] formData) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/applications/data"); long randomLong = new Random().nextLong(); //To be able to match JSONObject objResponse = new JSONObject(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); String appid = null; String appdesc = null; String commtype = null; Connection conn = null; if (name.equals("anonymous")) { return unauthorizedMessage(); } Map<String, FormDataPart> parts; try { conn = dbm.getConnection(); parts = MultipartHelper.getParts(formData, contentType); FormDataPart partAppID = parts.get("appid"); if (partAppID != null) { // these data belong to the (optional) file id text input form element appid = partAppID.getContent(); // appid must be unique System.out.println(appid); if (applicationAccess.isAppIdExist(conn, appid)) { // app id already exist objResponse.put("message", "App ID already exist"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } FormDataPart partAppDesc = parts.get("appdesc"); if (partAppDesc != null) { appdesc = partAppDesc.getContent(); } else { appdesc = ""; } FormDataPart partCommType = parts.get("commtype"); if (partAppDesc != null) { commtype = partCommType.getContent(); } else { commtype = "def_type"; } ApplicationModel newApp = new ApplicationModel(appid, appdesc, commtype); try { L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_1, "" + randomLong); applicationAccess.addNewApplication(conn, newApp); applicationAccess.addMemberToApp(conn, newApp.getId(), name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_2, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_3, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_4, "" + newApp.getId()); objResponse.put("message", "New application created"); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot Add New Application. Database Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } else { // app id cannot be empty objResponse.put("message", "Cannot Add New Application. App ID cannot be empty."); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (IOException e) { e.printStackTrace(); objResponse.put("message", "Cannot Add New Application. Error in parsing form data. " + 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 Add New 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); } } }
From source file:com.commsen.jwebthumb.WebThumbService.java
private HttpURLConnection getFetchConnection(WebThumbFetchRequest webThumbFetchRequest) throws WebThumbException { Validate.notNull(webThumbFetchRequest, "webThumbFetchRequest is null!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Attempting to send webThumbFetchRequest: " + webThumbFetchRequest); }// w ww . ja v a 2s . c om WebThumb webThumb = new WebThumb(apikey, webThumbFetchRequest); try { HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream()); int responseCode = connection.getResponseCode(); String contentType = getContentType(connection); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("webThumbFetchRequest sent. Got response: " + responseCode + " " + connection.getResponseMessage()); LOGGER.fine("Content type: " + contentType); } if (responseCode == HttpURLConnection.HTTP_OK) { if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) { throw new WebThumbException( "Server side error: " + IOUtils.toString(connection.getInputStream())); } return connection; } else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { WebThumbResponse webThumbResponse = SimpleXmlSerializer.parseResponse(connection.getErrorStream(), WebThumbResponse.class); throw new WebThumbException("Server side error: " + webThumbResponse.getError().getValue()); } else { throw new WebThumbException("Server side error: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (MalformedURLException e) { throw new WebThumbException("failed to send request", e); } catch (IOException e) { throw new WebThumbException("failed to send request", e); } }