Search in sources :

Example 81 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project webofneeds by researchstudio-sat.

the class AtomIndexer method indexAtomModel.

public void indexAtomModel(Model atomModel, String id, boolean useTestCore) throws IOException, JsonLdError {
    // create the json from rdf model
    StringWriter sw = new StringWriter();
    RDFDataMgr.write(sw, atomModel, Lang.JSONLD);
    String jsonld = sw.toString();
    Object jsonObject = JsonUtils.fromString(jsonld);
    Object frame = JsonUtils.fromString(" {\"@type\": \"" + WON.Atom + "\"} ");
    JsonLdOptions options = new JsonLdOptions();
    Map<String, Object> framed = JsonLdProcessor.frame(jsonObject, frame, options);
    // add the uri of the atom as id field to avoid multiple adding of atoms but
    // instead allow updates
    framed.put("id", id);
    // add latitude and longitude values in one field for Solr spatial queries
    DefaultAtomModelWrapper atomModelWrapper = new DefaultAtomModelWrapper(atomModel, null);
    Resource atomContentNode = atomModelWrapper.getAtomContentNode();
    Coordinate atomCoordinate = atomModelWrapper.getLocationCoordinate(atomContentNode);
    if (atomCoordinate != null) {
        framed.put(SOLR_IS_LOCATION_COORDINATES_FIELD, String.valueOf(atomCoordinate.getLatitude()) + "," + String.valueOf(atomCoordinate.getLongitude()));
    }
    for (Resource contentNode : atomModelWrapper.getSeeksNodes()) {
        Coordinate coordinate = atomModelWrapper.getLocationCoordinate(contentNode);
        if (coordinate != null) {
            framed.put(SOLR_SEEKS_LOCATION_COORDINATES_FIELD, String.valueOf(coordinate.getLatitude()) + "," + String.valueOf(coordinate.getLongitude()));
        }
    }
    for (Resource contentNode : atomModelWrapper.getSeeksSeeksNodes()) {
        Coordinate coordinate = atomModelWrapper.getLocationCoordinate(contentNode);
        if (coordinate != null) {
            framed.put(SOLR_SEEKS_SEEKS_LOCATION_COORDINATES_FIELD, String.valueOf(coordinate.getLatitude()) + "," + String.valueOf(coordinate.getLongitude()));
        }
    }
    // write the final json string
    sw = new StringWriter();
    JsonUtils.writePrettyPrint(sw, framed);
    String atomJson = sw.toString();
    // post the atom to the solr index
    String indexUri = config.getSolrEndpointUri(useTestCore);
    indexUri += "update/json/docs";
    if (config.isCommitIndexedAtomImmediately()) {
        indexUri += "?commit=" + config.isCommitIndexedAtomImmediately();
    }
    logger.debug("Post atom to solr index. \n Solr URI: {} \n Atom (JSON): {}", indexUri, atomJson);
    try {
        httpService.postJsonRequest(indexUri, atomJson);
    } catch (HttpClientErrorException e) {
        logger.info("Error indexing atom with solr. \n Solr URI: {} \n Atom (JSON): {}", indexUri, atomJson);
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) StringWriter(java.io.StringWriter) JsonLdOptions(com.github.jsonldjava.core.JsonLdOptions) DefaultAtomModelWrapper(won.protocol.util.DefaultAtomModelWrapper) Coordinate(won.protocol.model.Coordinate) Resource(org.apache.jena.rdf.model.Resource)

Example 82 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project open-kilda by telstra.

the class OtsdbQueryServiceImpl method query.

@Override
public StatsResult query(Date start, Date end, Aggregator aggregator, String metric, Map<String, Object> tags) {
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/api/query");
    uriBuilder.queryParam("start", start.getTime());
    uriBuilder.queryParam("end", end.getTime());
    List<String> tagParts = tags.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(toList());
    String tagsString = "{" + String.join(",", tagParts) + "}";
    uriBuilder.queryParam("m", String.format("%s:%s{tags}", aggregator.toString(), metric));
    try {
        StatsResult[] result = restTemplate.exchange(uriBuilder.build().toString(), HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), StatsResult[].class, tagsString).getBody();
        return result != null && result.length > 0 ? result[0] : new EmptyStatsResult();
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.BAD_REQUEST && e.getResponseBodyAsString().contains("net.opentsdb.tsd.BadRequestException: No such name for ")) {
            return new EmptyStatsResult();
        }
        throw e;
    }
}
Also used : StatsResult(org.openkilda.testing.service.otsdb.model.StatsResult) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) HttpHeaders(org.springframework.http.HttpHeaders) Date(java.util.Date) HttpMethod(org.springframework.http.HttpMethod) Aggregator(org.openkilda.testing.service.otsdb.model.Aggregator) Autowired(org.springframework.beans.factory.annotation.Autowired) EmptyStatsResult(org.openkilda.testing.service.otsdb.model.EmptyStatsResult) HttpStatus(org.springframework.http.HttpStatus) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Collectors.toList(java.util.stream.Collectors.toList) Slf4j(lombok.extern.slf4j.Slf4j) HttpEntity(org.springframework.http.HttpEntity) List(java.util.List) Service(org.springframework.stereotype.Service) Map(java.util.Map) Qualifier(org.springframework.beans.factory.annotation.Qualifier) RestTemplate(org.springframework.web.client.RestTemplate) HttpHeaders(org.springframework.http.HttpHeaders) EmptyStatsResult(org.openkilda.testing.service.otsdb.model.EmptyStatsResult) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) StatsResult(org.openkilda.testing.service.otsdb.model.StatsResult) EmptyStatsResult(org.openkilda.testing.service.otsdb.model.EmptyStatsResult)

Example 83 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project tutorials by eugenp.

the class PetApi method updatePetWithForm.

/**
 * Updates a pet in the store with form data
 *
 * <p><b>405</b> - Invalid input
 * @param petId ID of pet that needs to be updated
 * @param name Updated name of the pet
 * @param status Updated status of the pet
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void updatePetWithForm(Long petId, String name, String status) throws RestClientException {
    Object postBody = null;
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling updatePetWithForm");
    }
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = UriComponentsBuilder.fromPath("/pet/{petId}").buildAndExpand(uriVariables).toUriString();
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    if (name != null)
        formParams.add("name", name);
    if (status != null)
        formParams.add("status", status);
    final String[] accepts = { "application/xml", "application/json" };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { "application/x-www-form-urlencoded" };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
    String[] authNames = new String[] { "petstore_auth" };
    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {
    };
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) MediaType(org.springframework.http.MediaType)

Example 84 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project tutorials by eugenp.

the class PetApi method updatePet.

/**
 * Update an existing pet
 *
 * <p><b>400</b> - Invalid ID supplied
 * <p><b>404</b> - Pet not found
 * <p><b>405</b> - Validation exception
 * @param body Pet object that needs to be added to the store
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void updatePet(Pet body) throws RestClientException {
    Object postBody = body;
    // verify the required parameter 'body' is set
    if (body == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updatePet");
    }
    String path = UriComponentsBuilder.fromPath("/pet").build().toUriString();
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    final String[] accepts = { "application/xml", "application/json" };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { "application/json", "application/xml" };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
    String[] authNames = new String[] { "petstore_auth" };
    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {
    };
    apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) MediaType(org.springframework.http.MediaType)

Example 85 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project tutorials by eugenp.

the class PetApi method uploadFile.

/**
 * uploads an image
 *
 * <p><b>200</b> - successful operation
 * @param petId ID of pet to update
 * @param additionalMetadata Additional data to pass to server
 * @param file file to upload
 * @return ModelApiResponse
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException {
    Object postBody = null;
    // verify the required parameter 'petId' is set
    if (petId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile");
    }
    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("petId", petId);
    String path = UriComponentsBuilder.fromPath("/pet/{petId}/uploadImage").buildAndExpand(uriVariables).toUriString();
    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();
    if (additionalMetadata != null)
        formParams.add("additionalMetadata", additionalMetadata);
    if (file != null)
        formParams.add("file", new FileSystemResource(file));
    final String[] accepts = { "application/json" };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { "multipart/form-data" };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
    String[] authNames = new String[] { "petstore_auth" };
    ParameterizedTypeReference<ModelApiResponse> returnType = new ParameterizedTypeReference<ModelApiResponse>() {
    };
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) FileSystemResource(org.springframework.core.io.FileSystemResource) ModelApiResponse(com.baeldung.petstore.client.model.ModelApiResponse) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) MediaType(org.springframework.http.MediaType)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)109 HttpHeaders (org.springframework.http.HttpHeaders)31 Test (org.junit.Test)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 HashMap (java.util.HashMap)21 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)21 MediaType (org.springframework.http.MediaType)19 RestTemplate (org.springframework.web.client.RestTemplate)19 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)18 HttpEntity (org.springframework.http.HttpEntity)16 URI (java.net.URI)15 Map (java.util.Map)8 HttpStatus (org.springframework.http.HttpStatus)8 RestClientException (org.springframework.web.client.RestClientException)8 ResourceAccessException (org.springframework.web.client.ResourceAccessException)7 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)6 Date (java.util.Date)5 List (java.util.List)5 OpenAppNamespaceDTO (com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO)4 ArrayList (java.util.ArrayList)4