List of usage examples for org.springframework.http ResponseEntity toString
@Override
public String toString()
From source file:org.cloudfoundry.community.servicebroker.vrealize.VraClient.java
public VrServiceInstance deleteInstance(VrServiceInstance instance) { try {// w w w .j a v a2 s. c o m String token = tokenService.getToken(); LOG.info("getting delete template link from instance metadata."); String deleteTemplateLink = instance.getMetadata().get(VrServiceInstance.DELETE_TEMPLATE_LINK) .toString(); String deleteTemplatePath = pathFromLink(deleteTemplateLink); LOG.info("requesting delete template."); JsonElement template = vraRepository.getRequest("Bearer " + token, deleteTemplatePath).getBody(); LOG.info("customizing delete template."); JsonElement edited = prepareDeleteRequestTemplate(template, instance.getId()); LOG.info("getting delete link from instance metadata."); String deleteLink = instance.getMetadata().get(VrServiceInstance.DELETE_LINK).toString(); String deletePath = pathFromLink(deleteLink); LOG.info("posting delete request."); ResponseEntity<JsonElement> response = vraRepository.postRequest("Bearer " + token, deletePath, edited); LOG.debug("delete request response: " + response.toString()); String requestId = getRequestIdFromLocation(getLocation(response)); LOG.info("adding delete request metadata."); instance.getMetadata().put(VrServiceInstance.DELETE_REQUEST_ID, requestId); LastOperation lo = new LastOperation(OperationState.IN_PROGRESS, requestId, true); instance.withLastOperation(lo); return instance; } catch (Throwable t) { LOG.error("error processing delete request.", t); throw new ServiceBrokerException("Unable to process delete request.", t); } }
From source file:de.codecentric.boot.admin.services.SpringBootAdminRegistrator.java
/** * Registers the client application at spring-boot-admin-server. * @return true if successful/* w w w .j a v a 2 s .co m*/ */ public boolean register() { Application app = createApplication(); String adminUrl = adminProps.getUrl() + '/' + adminProps.getContextPath(); try { ResponseEntity<Application> response = template.postForEntity(adminUrl, app, Application.class); if (response.getStatusCode().equals(HttpStatus.CREATED)) { LOGGER.debug("Application registered itself as {}", response.getBody()); return true; } else if (response.getStatusCode().equals(HttpStatus.CONFLICT)) { LOGGER.warn("Application failed to registered itself as {} because of conflict in registry.", app); } else { LOGGER.warn("Application failed to registered itself as {}. Response: {}", app, response.toString()); } } catch (Exception ex) { LOGGER.warn("Failed to register application as {} at spring-boot-admin ({}): {}", app, adminUrl, ex.getMessage()); } return false; }
From source file:com.sastix.cms.server.controllers.ResourceController.java
@RequestMapping(value = "/v" + Constants.REST_API_1_0 + "/" + Constants.GET_DATA + "/{context}/**", method = RequestMethod.GET) public ResponseEntity<InputStreamResource> getDataResponse(@PathVariable String context, HttpServletRequest req, HttpServletResponse response) throws Exception { LOG.trace(Constants.GET_DATA + " uri={}", context); //Extract UURI String resourceUri = req.getRequestURI().substring(req.getRequestURI().indexOf(context)); //Decode URI/*from w w w.j a v a 2 s .com*/ resourceUri = URLDecoder.decode(resourceUri, "UTF-8"); //Extract TenantID final String tenantID = context.substring(context.lastIndexOf('-') + 1); // Populate UID final String uuid = hashedDirectoryService.hashText(resourceUri); ResponseEntity<InputStreamResource> responseEntity = resourceService.getResponseInputStream(uuid); if (responseEntity == null) { responseEntity = resourceService.getResponseInputStream(uuid + "-" + tenantID); } if (responseEntity == null) { LOG.error("resource {} was requested but does not exist", context); throw new ResourceAccessError("Resource " + context + " was requested but does not exist"); } LOG.trace(responseEntity.toString()); return responseEntity; }
From source file:de.codecentric.boot.admin.services.ApplicationRegistrator.java
/** * Registers the client application at spring-boot-admin-server. * * @return true if successful registration on at least one admin server *//*from w ww .j av a 2 s .c om*/ public boolean register() { boolean isRegistrationSuccessful = false; Application self = createApplication(); for (String adminUrl : admin.getAdminUrl()) { try { @SuppressWarnings("rawtypes") ResponseEntity<Map> response = template.postForEntity(adminUrl, new HttpEntity<>(self, HTTP_HEADERS), Map.class); if (response.getStatusCode().equals(HttpStatus.CREATED)) { if (registeredId.compareAndSet(null, response.getBody().get("id").toString())) { LOGGER.info("Application registered itself as {}", response.getBody()); } else { LOGGER.debug("Application refreshed itself as {}", response.getBody()); } isRegistrationSuccessful = true; if (admin.isRegisterOnce()) { break; } } else { LOGGER.warn("Application failed to registered itself as {}. Response: {}", self, response.toString()); } } catch (Exception ex) { LOGGER.warn("Failed to register application as {} at spring-boot-admin ({}): {}", self, admin.getAdminUrl(), ex.getMessage()); } } return isRegistrationSuccessful; }
From source file:es.onebox.rest.utils.service.QueryService.java
/** * Main method to perform request to Onebox REST API. * * @param authenticationForm/* w w w . ja v a2s.co m*/ * @param queryForm * @return Response form request */ public ResponseDTO query(AuthenticationForm authenticationForm, QueryForm queryForm) { ResponseDTO responseDTO = new ResponseDTO(); Exception ex = null; try { URL url = new URL(queryForm.getUrl()); URI uri = url.toURI(); Date date = new Date(); long timestamp = date.getTime(); HttpMethod httpMethod; if (queryForm.getMethod().equalsIgnoreCase("post")) { httpMethod = HttpMethod.POST; } else { httpMethod = HttpMethod.GET; } // Getting String to encode with HMAC-SHA1 // First step in the signing algorithm String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, queryForm); logger.info("String to sign: " + stringToSign); // Encoding String // This is the actual authorization string that will be sent in the request String authorization = generate_HMAC_SHA1_Signature(stringToSign, authenticationForm.getPassword() + authenticationForm.getLicense()); logger.info("Authorization string: " + authorization); // Adding to return object responseDTO.setDate(date); responseDTO.setStringToSign(stringToSign); responseDTO.setAuthorization(authorization); // Setting Headers HttpHeaders headers = new HttpHeaders(); if (queryForm.getAccept().equals("json")) { headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); } else { headers.setAccept(Arrays.asList(MediaType.TEXT_XML)); } headers.add("Authorization", authorization); headers.add("OB_DATE", "" + timestamp); headers.add("OB_Terminal", authenticationForm.getTerminal()); headers.add("OB_User", authenticationForm.getUser()); headers.add("OB_Channel", authenticationForm.getChannelId()); headers.add("OB_POS", authenticationForm.getPos()); // Adding Headers to return object responseDTO.setHttpHeaders(headers); HttpEntity<String> entity; if (httpMethod == HttpMethod.POST) { // Adding post parameters to POST body String parameterStringBody = queryForm.getParametersAsString(); entity = new HttpEntity<String>(parameterStringBody, headers); logger.info("POST Body: " + parameterStringBody); } else { entity = new HttpEntity<String>(headers); } // Creating rest client RestTemplate restTemplate = new RestTemplate(); // Converting to UTF-8. OB Rest replies in windows charset. restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); // Performing request to Onebox REST API ResponseEntity<String> result = restTemplate.exchange(uri, httpMethod, entity, String.class); // TODO this functionlity is to map response to objetcs. It is not finished. Only placed here for POC /* if (queryForm.getMapResponse().booleanValue()) { ResponseEntity<EventSearchBean> event = restTemplate.exchange(uri, httpMethod, entity, EventSearchBean.class); } */ // Adding response to return object responseDTO.setResponseEntity(result); logger.debug(result.toString()); } catch (HttpClientErrorException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (MalformedURLException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (SignatureException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (URISyntaxException e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters")); } catch (Exception e) { logger.error(e.getMessage()); ex = e; e.printStackTrace(); responseDTO.setError(e); responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.authentication")); } finally { if (ex != null && ex instanceof HttpServerErrorException) { HttpServerErrorException e2 = (HttpServerErrorException) ex; ResponseEntity<String> responseEntity = new ResponseEntity<String>(e2.getResponseHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); List<String> ob_error_codes = e2.getResponseHeaders().get("OB_Error_Code"); String ob_error_code; ResponseErrorCodesEnum ob_error = null; if (ob_error_codes != null && ob_error_codes.size() == 1) { ob_error_code = ob_error_codes.get(0); try { ob_error = ResponseErrorCodesEnum.valueOf("ERROR_" + ob_error_code); } catch (Exception e) { logger.error("API ERROR CODE NOT DEFINED: " + "ERROR_" + ob_error_code); } responseDTO.setObResponseErrorCode(ob_error); } responseDTO.setResponseEntity(responseEntity); } } return responseDTO; }
From source file:org.project.openbaton.nubomedia.paas.core.openshift.AuthenticationManager.java
public String authenticate(String baseURL, String username, String password) throws UnauthorizedException { String res = ""; String authBase = username + ":" + password; String authHeader = "Basic " + Base64.encodeBase64String(authBase.getBytes()); logger.debug("Auth header " + authHeader); String url = baseURL + suffix; HttpHeaders authHeaders = new HttpHeaders(); authHeaders.add("Authorization", authHeader); authHeaders.add("X-CSRF-Token", "1"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("client_id", "openshift-challenging-client").queryParam("response_type", "token"); HttpEntity<String> authEntity = new HttpEntity<>(authHeaders); ResponseEntity<String> response = null; try {/*from w ww. jav a 2 s.c o m*/ response = template.exchange(builder.build().encode().toUriString(), HttpMethod.GET, authEntity, String.class); } catch (ResourceAccessException e) { return "PaaS Missing"; } catch (HttpClientErrorException e) { throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid"); } logger.debug("Response " + response.toString()); if (response.getStatusCode().equals(HttpStatus.FOUND)) { URI location = response.getHeaders().getLocation(); logger.debug("Location " + location); res = this.getToken(location.toString()); } else if (response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid"); } return res; }
From source file:org.springframework.cloud.vault.util.PrepareVault.java
/** * Initialize Vault and unseal the vault. * * @return the root token.//from ww w . j a v a 2s . c o m */ public VaultToken initializeVault() { Assert.notNull(vaultProperties, "VaultProperties must not be null"); Map<String, String> parameters = parameters(vaultProperties); int createKeys = 2; int requiredKeys = 2; InitializeVault initializeVault = InitializeVault.of(createKeys, requiredKeys); ResponseEntity<VaultInitialized> initResponse = restTemplate.exchange(INITIALIZE_URL_TEMPLATE, HttpMethod.PUT, new HttpEntity<>(initializeVault), VaultInitialized.class, parameters); if (!initResponse.getStatusCode().is2xxSuccessful()) { throw new IllegalStateException("Cannot initialize vault: " + initResponse.toString()); } VaultInitialized initialized = initResponse.getBody(); for (int i = 0; i < requiredKeys; i++) { UnsealKey unsealKey = UnsealKey.of(initialized.getKeys().get(i)); ResponseEntity<UnsealProgress> unsealResponse = restTemplate.exchange(UNSEAL_URL_TEMPLATE, HttpMethod.PUT, new HttpEntity<>(unsealKey), UnsealProgress.class, parameters); UnsealProgress unsealProgress = unsealResponse.getBody(); if (!unsealProgress.isSealed()) { break; } } return VaultToken.of(initialized.getRootToken()); }
From source file:org.springframework.cloud.vault.util.PrepareVault.java
/** * Create a token for the given {@code tokenId} and {@code policy}. * /* ww w . j a v a2s . com*/ * @param tokenId * @param policy * @return */ public VaultToken createToken(String tokenId, String policy) { Map<String, String> parameters = parameters(vaultProperties); CreateToken createToken = new CreateToken(); createToken.setId(tokenId); if (policy != null) { createToken.setPolicies(Collections.singletonList(policy)); } HttpHeaders headers = authenticatedHeaders(); HttpEntity<CreateToken> entity = new HttpEntity<>(createToken, headers); ResponseEntity<TokenCreated> createTokenResponse = restTemplate.exchange(CREATE_TOKEN_URL_TEMPLATE, HttpMethod.POST, entity, TokenCreated.class, parameters); if (!createTokenResponse.getStatusCode().is2xxSuccessful()) { throw new IllegalStateException("Cannot create token: " + createTokenResponse.toString()); } AuthToken authToken = createTokenResponse.getBody().getAuth(); return VaultToken.of(authToken.getClientToken()); }
From source file:org.springframework.cloud.vault.util.PrepareVault.java
/** * Check whether Vault is available (vault created and unsealed). * * @return/*from ww w. java 2s. c om*/ */ public boolean isAvailable() { Map<String, String> parameters = parameters(vaultProperties); ResponseEntity<String> exchange = null; try { exchange = restTemplate.getForEntity(SEAL_STATUS_URL_TEMPLATE, String.class, parameters); if (exchange.getStatusCode().is2xxSuccessful()) { return true; } } catch (HttpStatusCodeException e) { if (e.getStatusCode().is4xxClientError()) { return false; } } if (exchange.getStatusCode().is4xxClientError()) { return false; } throw new IllegalStateException("Vault error: " + exchange.toString()); }
From source file:org.springframework.cloud.vault.util.PrepareVault.java
/** * Mount an auth backend.//w w w .j a va2 s .c om * * @param authBackend */ public void mountAuth(String authBackend) { Assert.hasText(authBackend, "AuthBackend must not be empty"); Map<String, String> parameters = parameters(vaultProperties); parameters.put("authBackend", authBackend); Map<String, String> requestEntity = Collections.singletonMap("type", authBackend); HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestEntity, authenticatedHeaders()); ResponseEntity<String> responseEntity = restTemplate.exchange(MOUNT_AUTH_URL_TEMPLATE, HttpMethod.POST, entity, String.class, parameters); if (!responseEntity.getStatusCode().is2xxSuccessful()) { throw new IllegalStateException("Cannot create mount auth backend: " + responseEntity.toString()); } responseEntity.getBody(); }