List of usage examples for org.springframework.http HttpStatus valueOf
public static HttpStatus valueOf(int statusCode)
From source file:fi.csc.kapaVirtaAS.VirtaXRoadEndpoint.java
@RequestMapping(value = "/ws", method = RequestMethod.POST) public ResponseEntity<String> getVirtaResponse(@RequestBody String XRoadRequestMessage) throws Exception { FaultMessageService faultMessageService = new FaultMessageService(); MessageTransformer messageTransformer = new MessageTransformer(conf, faultMessageService); VirtaClient virtaClient = new VirtaClient(conf); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("text", "xml", Charsets.UTF_8)); HttpResponse virtaResponse;/*from w w w . j av a 2 s .co m*/ try { String virtaRequestMessage = messageTransformer.transform(XRoadRequestMessage, MessageTransformer.MessageDirection.XRoadToVirta); //Send transformed SOAP-request to Virta virtaResponse = virtaClient.getVirtaWS(virtaRequestMessage, messageTransformer.createAuthenticationString(XRoadRequestMessage)); } catch (Exception e) { log.error(e.toString()); HttpStatus errorStatus = HttpStatus.INTERNAL_SERVER_ERROR; String errorMessage = ERROR_MESSAGE; if (e instanceof DOMException) { errorStatus = HttpStatus.BAD_REQUEST; errorMessage = "Request SOAP-headers did not contain client identifiers (http://x-road.eu/xsd/identifiers)"; } return new ResponseEntity<>(faultMessageService.generateSOAPFault(errorMessage, faultMessageService.getReqValidFail(), messageTransformer.getXroadHeaderElement()), httpHeaders, errorStatus); } try { if (virtaResponse.getStatusLine().getStatusCode() != 200) { log.error(virtaResponse.getStatusLine().getReasonPhrase()); throw new HttpResponseException(virtaResponse.getStatusLine().getStatusCode(), virtaResponse.getStatusLine().getReasonPhrase()); } BufferedReader rd = new BufferedReader(new InputStreamReader(virtaResponse.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { result.append(line); } String virtaResponseMessage = result.toString(); return new ResponseEntity<>(messageTransformer.transform(virtaResponseMessage, MessageTransformer.MessageDirection.VirtaToXRoad), httpHeaders, HttpStatus.OK); } catch (Exception e) { log.error(e.toString()); HttpStatus status = HttpStatus.valueOf(virtaResponse.getStatusLine().getStatusCode()); if (status.value() == 200) { status = HttpStatus.INTERNAL_SERVER_ERROR; } else if (IOUtils.toString(virtaResponse.getEntity().getContent()).toLowerCase() .contains("access denied")) { status = HttpStatus.FORBIDDEN; } return new ResponseEntity<>( faultMessageService.generateSOAPFault(ERROR_MESSAGE + status.name(), faultMessageService.getResValidFail(), messageTransformer.getXroadHeaderElement()), httpHeaders, status); } }
From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java
/** * Down-loads and saves the file from a {@link CmrRepositoryDefinition}. Files will be saved in * the directory that is denoted as the given Path object. Original file names will be used. * // www . j a va2 s.co m * @param cmrRepositoryDefinition * Repository. * @param files * Map with file names and sizes. * @param postDownloadRunnable * {@link PostDownloadRunnable} that will be executed after successful request. * @param useGzipCompression * If the GZip compression should be used when files are downloaded. * @param decompressContent * If the useGzipCompression is <code>true</code>, this parameter will define if the * received content will be de-compressed. If false is passed content will be saved * to file in the same format as received, but the path of the file will be altered * with additional '.gzip' extension at the end. * @param subMonitor * {@link SubMonitor} for process reporting. * @throws IOException * If {@link IOException} occurs. * @throws BusinessException * If status of HTTP response is not successful (codes 2xx). */ private void downloadAndSaveObjects(CmrRepositoryDefinition cmrRepositoryDefinition, Map<String, Long> files, PostDownloadRunnable postDownloadRunnable, boolean useGzipCompression, boolean decompressContent, final SubMonitor subMonitor) throws IOException, BusinessException { DefaultHttpClient httpClient = new DefaultHttpClient(); final TransferDataMonitor transferDataMonitor = new TransferDataMonitor(subMonitor, files, useGzipCompression); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { response.setEntity(new DownloadHttpEntityWrapper(response.getEntity(), transferDataMonitor)); } }); if (useGzipCompression && decompressContent) { httpClient.addResponseInterceptor(new GzipHttpResponseInterceptor()); } for (Map.Entry<String, Long> fileEntry : files.entrySet()) { String fileName = fileEntry.getKey(); String fileLocation = getServerUri(cmrRepositoryDefinition) + fileName; HttpGet httpGet = new HttpGet(fileLocation); if (useGzipCompression) { httpGet.addHeader("accept-encoding", "gzip"); } transferDataMonitor.startTransfer(fileName); HttpResponse response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); if (HttpStatus.valueOf(statusLine.getStatusCode()).series().equals(Series.SUCCESSFUL)) { HttpEntity entity = response.getEntity(); try (InputStream is = entity.getContent()) { postDownloadRunnable.process(is, fileName); } } transferDataMonitor.endTransfer(fileName); } }
From source file:io.ignitr.springboot.common.error.IgnitionErrorAttributes.java
/** * Adds the http status to the error response. * * @param errorAttributes error attributes collection * @param requestAttributes request attributes collection *//*from w w w. j a va 2 s .c o m*/ private void addStatus(Map<String, Object> errorAttributes, RequestAttributes requestAttributes) { Integer status = getAttribute(requestAttributes, "javax.servlet.error.status_code"); Throwable error = getError(requestAttributes); if (error instanceof IgnitionException) { // If the error is an ignition compatible error we need to get the status code from the exception status = ((IgnitionException) error).getHttpStatus().value(); } else if (status == null && error instanceof MethodArgumentNotValidException) { // If a validation error occurs default to 400 - Bad Request status = 400; } else { // If a status cannot be found default to 500 - Internal Server Error status = 500; } errorAttributes.put("status", status); try { errorAttributes.put("message", HttpStatus.valueOf(status).getReasonPhrase()); } catch (Exception ex) { // Unable to obtain a reason errorAttributes.put("message", "Http Status " + status); } }
From source file:it.infn.mw.iam.core.web.IamErrorController.java
@RequestMapping(PATH) public ModelAndView error(HttpServletRequest request) { ModelAndView errorPage = new ModelAndView(IAM_ERROR_VIEW); HttpStatus status = HttpStatus.valueOf(getErrorCode(request)); errorPage.addObject("errorMessage", String.format("%d. %s", status.value(), status.getReasonPhrase())); Exception exception = getRequestException(request); if (exception != null) { errorPage.addObject("exceptionMessage", exception.getMessage()); errorPage.addObject("exceptionStackTrace", ExceptionUtils.getStackTrace(exception).trim()); }//from w w w . j a v a 2 s .c om return errorPage; }
From source file:net.es.sense.rm.api.SenseRmController.java
private ResponseEntity<?> toResponseEntity(HttpHeaders headers, ResourceResponse rr) { if (rr == null) { return new ResponseEntity<>(headers, HttpStatus.INTERNAL_SERVER_ERROR); }// w ww .j a v a2s .com switch (rr.getStatus()) { case NOT_MODIFIED: return new ResponseEntity<>(headers, HttpStatus.NOT_MODIFIED); default: Error.ErrorBuilder eb = Error.builder().error(rr.getStatus().getReasonPhrase()); rr.getError().ifPresent(e -> eb.error_description(e)); return new ResponseEntity<>(eb.build(), HttpStatus.valueOf(rr.getStatus().getStatusCode())); } }
From source file:nl.ellipsis.webdav.server.methods.AbstractMethod.java
/** * Send a multistatus element containing a complete error report to the client. * If the errorList contains only one error, send the error directly without * wrapping it in a multistatus message. * /*from w ww . ja v a 2 s .c o m*/ * @param req * Servlet request * @param resp * Servlet response * @param errorList * List of error to be displayed */ protected static void sendReport(HttpServletRequest req, HttpServletResponse resp, Hashtable<String, Integer> errorList) throws IOException { if (errorList.size() == 1) { int code = errorList.elements().nextElement(); HttpStatus s = HttpStatus.valueOf(code); String status = s.getReasonPhrase(); if (status != null && !status.isEmpty()) { resp.sendError(code, status); } else { resp.sendError(code); } } else { resp.setStatus(HttpStatus.MULTI_STATUS.value()); String absoluteUri = req.getRequestURI(); // String relativePath = getRelativePath(req); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement(NS_DAV_PREFIX, NS_DAV_FULLNAME, WebDAVConstants.XMLTag.MULTISTATUS, XMLWriter.OPENING); Enumeration<String> pathList = errorList.keys(); while (pathList.hasMoreElements()) { String errorPath = (String) pathList.nextElement(); int errorCode = ((Integer) errorList.get(errorPath)).intValue(); generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.RESPONSE, XMLWriter.OPENING); generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.HREF, XMLWriter.OPENING); String toAppend = null; if (absoluteUri.endsWith(errorPath)) { toAppend = absoluteUri; } else if (absoluteUri.contains(errorPath)) { int endIndex = absoluteUri.indexOf(errorPath) + errorPath.length(); toAppend = absoluteUri.substring(0, endIndex); } if (StringUtils.isEmpty(toAppend)) { toAppend = CharsetUtil.FORWARD_SLASH; } else if (!toAppend.startsWith(CharsetUtil.FORWARD_SLASH) && !toAppend.startsWith(PROTOCOL_HTTP)) { toAppend = CharsetUtil.FORWARD_SLASH + toAppend; } generatedXML.writeText(errorPath); generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.HREF, XMLWriter.CLOSING); generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.STATUS, XMLWriter.OPENING); HttpStatus s = HttpStatus.valueOf(errorCode); generatedXML.writeText("HTTP/1.1 " + errorCode + " " + s.getReasonPhrase()); generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.STATUS, XMLWriter.CLOSING); generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.RESPONSE, XMLWriter.CLOSING); } generatedXML.writeElement(NS_DAV_PREFIX, WebDAVConstants.XMLTag.MULTISTATUS, XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); } }
From source file:org.alfresco.bm.dataload.rm.records.DeclareInPlaceRecords.java
@Override protected EventResult processEvent(Event event) throws Exception { StringBuilder eventOutputMsg = new StringBuilder("Declaring file as record: \n"); super.suspendTimer(); if (event == null) { throw new IllegalStateException("This processor requires an event."); }// w ww .j a va 2 s . c o m DBObject dataObj = (DBObject) event.getData(); if (dataObj == null) { throw new IllegalStateException( MessageFormat.format(INVALID_DATA_MSG_TEMPLATE, FIELD_ID, FIELD_USERNAME, FIELD_PASSWORD)); } String id = (String) dataObj.get(FIELD_ID); String username = (String) dataObj.get(FIELD_USERNAME); String password = (String) dataObj.get(FIELD_PASSWORD); if (isBlank(id) || isBlank(username) || isBlank(password)) { throw new IllegalStateException( MessageFormat.format(INVALID_DATA_MSG_TEMPLATE, FIELD_ID, FIELD_USERNAME, FIELD_PASSWORD)); } try { // Get the record from database RecordData dbRecord = recordService.getRecord(id); if (dbRecord.getExecutionState() != ExecutionState.SCHEDULED) { throw new IllegalStateException("The record + " + id + " was found but it was already processed"); } // Call the REST API super.resumeTimer(); Record record = restAPIFactory.getFilesAPI(new UserModel(username, password)).declareAsRecord(id); String statusCode = restAPIFactory.getRmRestWrapper().getStatusCode(); super.suspendTimer(); TimeUnit.MILLISECONDS.sleep(declareInPlaceRecordDelay); if (HttpStatus.valueOf(Integer.parseInt(statusCode)) == HttpStatus.CREATED) { eventOutputMsg.append("success"); dbRecord.setExecutionState(ExecutionState.SUCCESS); dbRecord.setName(record.getName()); } else { eventOutputMsg.append("Failed with code " + statusCode + ".\n " + restAPIFactory.getRmRestWrapper().assertLastError().getBriefSummary() + ". \n" + restAPIFactory.getRmRestWrapper().assertLastError().getStackTrace()); dbRecord.setExecutionState(ExecutionState.FAILED); } recordService.updateRecord(dbRecord); return new EventResult(eventOutputMsg.toString(), new Event(getEventNameInPlaceRecordsDeclared(), dataObj)); } catch (Exception e) { String error = e.getMessage(); String stack = ExceptionUtils.getStackTrace(e); // Grab REST API information DBObject data = BasicDBObjectBuilder.start().append("error", error).append(FIELD_ID, id) .append(FIELD_USERNAME, username).append(FIELD_PASSWORD, password).append("stack", stack).get(); // Build failure result return new EventResult(data, false); } }
From source file:org.craftercms.studio.exceptions.formatter.impl.AbstractExceptionFormatter.java
/** * Validates that message and http are//w w w . j a va2s. co m * not null (and >200) and that message is not empty. * * @throws IllegalStateException if either defaultMessage or httpResponseCode are not valid. */ private void validateDefaultMessageParams(Exception ex) { if (StringUtils.isEmpty(ex.getMessage())) { throw new IllegalStateException("Default message can't be null or empty"); } try { HttpStatus.valueOf(this.httpResponseCode); } catch (IllegalArgumentException e) { throw new IllegalStateException( String.format("%s is not a valid Http Response Code", this.httpResponseCode)); } }
From source file:org.craftercms.studio.impl.v1.deployment.PreviewDeployerImpl.java
@EventListener(EVENT_PREVIEW_SYNC) public void onPreviewSync(PreviewEventContext context) { String site = context.getSite(); String requestUrl = getDeployTargetUrl(site); HttpPost postRequest = new HttpPost(requestUrl); if (context.isWaitTillDeploymentIsDone()) { String requestBody = getDeployTargetRequestBody(true); HttpEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); postRequest.setEntity(requestEntity); }//www.j ava 2 s . co m // TODO: DB: add all required params to post method try { CloseableHttpResponse response = httpClient.execute(postRequest); HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusLine().getStatusCode()); if (!httpStatus.is2xxSuccessful()) { logger.error("Preview sync request for site " + site + " returned status " + httpStatus + " (" + httpStatus.getReasonPhrase() + ")"); } } catch (IOException e) { logger.error("Error while sending preview sync request for site " + site, e); } finally { postRequest.releaseConnection(); } }
From source file:org.craftercms.studio.impl.v1.deployment.PreviewDeployerImpl.java
@Override @SuppressWarnings("deprecation") public boolean createTarget(String site) { boolean toReturn = true; String requestUrl = getCreateTargetUrl(); HttpPost postRequest = new HttpPost(requestUrl); String requestBody = getCreateTargetRequestBody(site); HttpEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); postRequest.setEntity(requestEntity); try {// www . j a v a 2 s. c o m CloseableHttpResponse response = httpClient.execute(postRequest); if (HttpStatus.valueOf(response.getStatusLine().getStatusCode()) != HttpStatus.CREATED) { toReturn = false; } } catch (IOException e) { logger.error("Error while sending preview sync request for site " + site, e); toReturn = false; } finally { postRequest.releaseConnection(); } return toReturn; }