Search in sources :

Example 61 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project traccar by tananaev.

the class UniversalGeolocationProvider method getLocation.

@Override
public void getLocation(Network network, final LocationProviderCallback callback) {
    try {
        String request = Context.getObjectMapper().writeValueAsString(network);
        Context.getAsyncHttpClient().preparePost(url).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(request.length())).setBody(request).execute(new AsyncCompletionHandler() {

            @Override
            public Object onCompleted(Response response) throws Exception {
                try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) {
                    JsonObject json = reader.readObject();
                    if (json.containsKey("error")) {
                        callback.onFailure(new GeolocationException(json.getJsonObject("error").getString("message")));
                    } else {
                        JsonObject location = json.getJsonObject("location");
                        callback.onSuccess(location.getJsonNumber("lat").doubleValue(), location.getJsonNumber("lng").doubleValue(), json.getJsonNumber("accuracy").doubleValue());
                    }
                }
                return null;
            }

            @Override
            public void onThrowable(Throwable t) {
                callback.onFailure(t);
            }
        });
    } catch (JsonProcessingException e) {
        callback.onFailure(e);
    }
}
Also used : Response(com.ning.http.client.Response) AsyncCompletionHandler(com.ning.http.client.AsyncCompletionHandler) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 62 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project traccar by tananaev.

the class CsvBuilder method addLine.

public void addLine(Object object) {
    SortedSet<Method> methods = getSortedMethods(object);
    for (Method method : methods) {
        if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) {
            try {
                if (method.getReturnType().equals(boolean.class)) {
                    builder.append(method.invoke(object));
                    addSeparator();
                } else if (method.getReturnType().equals(int.class)) {
                    builder.append(method.invoke(object));
                    addSeparator();
                } else if (method.getReturnType().equals(long.class)) {
                    builder.append(method.invoke(object));
                    addSeparator();
                } else if (method.getReturnType().equals(double.class)) {
                    builder.append(method.invoke(object));
                    addSeparator();
                } else if (method.getReturnType().equals(String.class)) {
                    builder.append((String) method.invoke(object));
                    addSeparator();
                } else if (method.getReturnType().equals(Date.class)) {
                    Date value = (Date) method.invoke(object);
                    builder.append(DATE_FORMAT.print(new DateTime(value)));
                    addSeparator();
                } else if (method.getReturnType().equals(Map.class)) {
                    Map value = (Map) method.invoke(object);
                    if (value != null) {
                        try {
                            String map = Context.getObjectMapper().writeValueAsString(value);
                            map = map.replaceAll("[\\{\\}\"]", "");
                            map = map.replaceAll(",", " ");
                            builder.append(map);
                            addSeparator();
                        } catch (JsonProcessingException e) {
                            Log.warning(e);
                        }
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException error) {
                Log.warning(error);
            }
        }
    }
    addLineEnding();
}
Also used : Method(java.lang.reflect.Method) Map(java.util.Map) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Date(java.util.Date) DateTime(org.joda.time.DateTime) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 63 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project atlasmap by atlasmap.

the class GenerateInspectionsMojo method generateInspection.

private void generateInspection(List<String> artifacts, Collection<String> classNames) throws MojoFailureException, MojoExecutionException {
    List<URL> urls = artifacts == null ? Collections.emptyList() : resolveClasspath(artifacts);
    ClassLoader origTccl = Thread.currentThread().getContextClassLoader();
    for (String className : classNames) {
        Class<?> clazz = null;
        JavaClass c = null;
        // Not even this plugin will be available on this new URLClassLoader
        try (URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[urls.size()]), origTccl)) {
            clazz = loader.loadClass(className);
            ClassInspectionService classInspectionService = new ClassInspectionService();
            classInspectionService.setConversionService(DefaultAtlasConversionService.getInstance());
            c = classInspectionService.inspectClass(loader, clazz);
        } catch (ClassNotFoundException | IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
        try {
            ObjectMapper objectMapper = Json.mapper();
            File target = outputFile;
            if (target == null) {
                target = new File(outputDir, "atlasmap-inpection-" + className + ".json");
            }
            objectMapper.writeValue(target, c);
            getLog().info("Created: " + target);
        } catch (JsonProcessingException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) IOException(java.io.IOException) URL(java.net.URL) JavaClass(io.atlasmap.java.v2.JavaClass) URLClassLoader(java.net.URLClassLoader) ClassInspectionService(io.atlasmap.java.inspect.ClassInspectionService) URLClassLoader(java.net.URLClassLoader) File(java.io.File) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 64 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project carbon-apimgt by wso2.

the class EndpointsApiServiceImpl method endpointsEndpointIdPut.

/**
 * Updates an existing endpoint
 *
 * @param endpointId        ID of the endpoint
 * @param body              Updated endpoint details
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return updated endpoint
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response endpointsEndpointIdPut(String endpointId, EndPointDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        Endpoint endpoint = MappingUtil.toEndpoint(body);
        Endpoint retrievedEndpoint = apiPublisher.getEndpoint(endpointId);
        if (retrievedEndpoint == null) {
            String msg = "Endpoint not found " + endpointId;
            log.error(msg);
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(ExceptionCodes.ENDPOINT_NOT_FOUND);
            return Response.status(ExceptionCodes.ENDPOINT_NOT_FOUND.getHttpStatusCode()).entity(errorDTO).build();
        }
        String existingFingerprint = endpointsEndpointIdGetFingerprint(endpointId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        Endpoint updatedEndpint = new Endpoint.Builder(endpoint).id(endpointId).build();
        apiPublisher.updateEndpoint(updatedEndpint);
        Endpoint updatedEndpoint = apiPublisher.getEndpoint(endpointId);
        String newFingerprint = endpointsEndpointIdGetFingerprint(endpointId, null, null, request);
        return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(MappingUtil.toEndPointDTO(updatedEndpoint)).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while getting the endpoint :" + endpointId;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (JsonProcessingException e) {
        String errorMessage = "Error while Converting Endpoint Security Details in Endpoint :" + endpointId;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    } catch (IOException e) {
        String errorMessage = "Error while Converting Endpoint Security Details in Endpoint :" + endpointId;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
}
Also used : Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 65 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdPut.

/**
 * Updates an API by UUID
 *
 * @param apiId             UUID of API
 * @param body              Updated API details
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return Updated API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdPut(String apiId, APIDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String existingFingerprint = apisApiIdGetFingerprint(apiId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        API.APIBuilder api = MappingUtil.toAPI(body).id(apiId);
        apiPublisher.updateAPI(api);
        String newFingerprint = apisApiIdGetFingerprint(apiId, null, null, request);
        APIDTO apidto = MappingUtil.toAPIDto(apiPublisher.getAPIbyUUID(apiId));
        return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(apidto).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while updating API : " + apiId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (JsonProcessingException e) {
        String errorMessage = "Error while updating API : " + apiId;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    } catch (IOException e) {
        String errorMessage = "Error while updating API : " + apiId;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) API(org.wso2.carbon.apimgt.core.models.API) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)153 IOException (java.io.IOException)43 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)42 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)15 Test (org.junit.Test)14 InputStream (java.io.InputStream)11 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 List (java.util.List)8 Map (java.util.Map)8 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)7 ErrorResponseBody (com.nike.riposte.server.error.handler.ErrorResponseBody)6 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)6 OutputStreamWriter (java.io.OutputStreamWriter)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 TaskDTO (com.linkedin.thirdeye.datalayer.dto.TaskDTO)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 SimpleDateFormat (java.text.SimpleDateFormat)4 Test (org.testng.annotations.Test)4