Search in sources :

Example 36 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project indy by Commonjava.

the class AutoProxCalculatorResource method eval.

@ApiOperation(value = "Calculate the effects of referencing a store with the given type and name to determine what AutoProx will auto-create", response = AutoProxCalculation.class)
@ApiResponse(code = 200, message = "Result of calculation")
@Path("/{packageType}/{type: (hosted|group|remote)}/{name}")
@GET
@Produces(ApplicationContent.application_json)
public Response eval(@PathParam("packageType") final String packageType, @PathParam("type") final String type, @PathParam("name") final String remoteName) {
    Response response = checkEnabled();
    if (response != null) {
        return response;
    }
    try {
        StoreKey key = new StoreKey(packageType, StoreType.get(type), remoteName);
        final AutoProxCalculation calc = controller.eval(key);
        response = formatOkResponseWithJsonEntity(serializer.writeValueAsString(calc == null ? Collections.singletonMap("error", "Nothing was created") : calc));
    } catch (final IndyWorkflowException e) {
        logger.error(String.format("Failed to create demo RemoteRepository for: '%s'. Reason: %s", remoteName, e.getMessage()), e);
        response = formatResponse(e);
    } catch (final JsonProcessingException e) {
        logger.error(String.format("Failed to create demo RemoteRepository for: '%s'. Reason: %s", remoteName, e.getMessage()), e);
        response = formatResponse(e);
    }
    return response;
}
Also used : ResponseUtils.formatResponse(org.commonjava.indy.bind.jaxrs.util.ResponseUtils.formatResponse) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) AutoProxCalculation(org.commonjava.indy.autoprox.rest.dto.AutoProxCalculation) StoreKey(org.commonjava.indy.model.core.StoreKey) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponse(io.swagger.annotations.ApiResponse)

Example 37 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project indy by Commonjava.

the class ContentController method renderListing.

public String renderListing(final String acceptHeader, final StoreKey key, final String requestPath, final String serviceUrl, final UriFormatter uriFormatter) throws IndyWorkflowException {
    String path = requestPath;
    if (path.endsWith(LISTING_HTML_FILE)) {
        path = normalize(parentPath(path));
    }
    final List<StoreResource> listed = getListing(key, path);
    if (ApplicationContent.application_json.equals(acceptHeader)) {
        final DirectoryListingDTO dto = new DirectoryListingDTO(StoreResource.convertToEntries(listed));
        try {
            return mapper.writeValueAsString(dto);
        } catch (final JsonProcessingException e) {
            throw new IndyWorkflowException("Failed to render listing to JSON: %s. Reason: %s", e, dto, e.getMessage());
        }
    }
    final Map<String, Set<String>> listingUrls = new TreeMap<>();
    final String storeUrl = uriFormatter.formatAbsolutePathTo(serviceUrl, key.getType().singularEndpointName(), key.getName());
    if (listed != null) {
        // second pass, process the remainder.
        for (int pass = 0; pass < 2; pass++) {
            for (final ConcreteResource res : listed) {
                String p = res.getPath();
                if (pass == 0 && !p.endsWith("/")) {
                    continue;
                } else if (pass == 1) {
                    if (!p.endsWith("/")) {
                        final String dirpath = p + "/";
                        if (listingUrls.containsKey(normalize(storeUrl, dirpath))) {
                            p = dirpath;
                        }
                    } else {
                        continue;
                    }
                }
                final String localUrl = normalize(storeUrl, p);
                Set<String> sources = listingUrls.get(localUrl);
                if (sources == null) {
                    sources = new HashSet<>();
                    listingUrls.put(localUrl, sources);
                }
                sources.add(normalize(res.getLocationUri(), res.getPath()));
            }
        }
    }
    final List<String> sources = new ArrayList<>();
    if (listed != null) {
        for (final ConcreteResource res : listed) {
            // KeyedLocation is all we use in Indy.
            logger.debug("Formatting sources URL for: {}", res);
            final KeyedLocation kl = (KeyedLocation) res.getLocation();
            final String uri = uriFormatter.formatAbsolutePathTo(serviceUrl, kl.getKey().getType().singularEndpointName(), kl.getKey().getName());
            if (!sources.contains(uri)) {
                logger.debug("adding source URI: '{}'", uri);
                sources.add(uri);
            }
        }
    }
    Collections.sort(sources);
    String parentPath = normalize(parentPath(path));
    if (!parentPath.endsWith("/")) {
        parentPath += "/";
    }
    final String parentUrl;
    if (parentPath.equals(path)) {
        parentPath = null;
        parentUrl = null;
    } else {
        parentUrl = uriFormatter.formatAbsolutePathTo(serviceUrl, key.getType().singularEndpointName(), key.getName(), parentPath);
    }
    final Map<String, Object> params = new HashMap<>();
    params.put("items", listingUrls);
    params.put("parentUrl", parentUrl);
    params.put("parentPath", parentPath);
    params.put("path", path);
    params.put("storeKey", key);
    params.put("storeUrl", storeUrl);
    params.put("baseUrl", serviceUrl);
    params.put("sources", sources);
    // render...
    try {
        return templates.render(acceptHeader, "directory-listing", params);
    } catch (final IndyGroovyException e) {
        throw new IndyWorkflowException(e.getMessage(), e);
    }
}
Also used : DirectoryListingDTO(org.commonjava.indy.model.core.dto.DirectoryListingDTO) HashSet(java.util.HashSet) Set(java.util.Set) KeyedLocation(org.commonjava.indy.model.galley.KeyedLocation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) IndyGroovyException(org.commonjava.indy.subsys.template.IndyGroovyException) StoreResource(org.commonjava.indy.content.StoreResource) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) ConcreteResource(org.commonjava.maven.galley.model.ConcreteResource) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 38 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project drill by apache.

the class JSONOptions method getWith.

@SuppressWarnings("unchecked")
public <T> T getWith(LogicalPlanPersistence lpPersistance, Class<T> c) {
    try {
        if (opaque != null) {
            final Class<?> opaqueClass = opaque.getClass();
            if (opaqueClass.equals(c)) {
                return (T) opaque;
            } else {
                // e.g. SystemTable$1 for SystemTable.OPTION
                if (c.isEnum()) {
                    final String opaqueName = opaqueClass.getName().replaceAll("\\$\\d+$", "");
                    final String cName = c.getName();
                    if (opaqueName.equals(cName)) {
                        return (T) opaque;
                    }
                }
                throw new IllegalArgumentException(String.format("Attempted to retrieve a option with type of %s.  " + "However, the JSON options carried an opaque value of type %s.", c.getName(), opaqueClass.getName()));
            }
        }
        //logger.debug("Read tree {}", root);
        return lpPersistance.getMapper().treeToValue(root, c);
    } catch (JsonProcessingException e) {
        throw new LogicalPlanParsingException(String.format("Failure while trying to convert late bound " + "json options to type of %s. Reference was originally located at line %d, column %d.", c.getCanonicalName(), location.getLineNr(), location.getColumnNr()), e);
    }
}
Also used : LogicalPlanParsingException(org.apache.drill.common.exceptions.LogicalPlanParsingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 39 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project IPK-BrAPI-Validator by plantbreeding.

the class RunnerService method TestAllEndpointsWithFreq.

/**
 * Test all endpoints with a certain frequency set in database
 *
 * @param testCollection Config instance.
 * @param frequency      Get endpoints with this frequency.
 * @return List of TestSuiteReport containing the test results.
 * @throws SQLException SQL connection
 */
public static int TestAllEndpointsWithFreq(TestCollection testCollection, String frequency) throws SQLException {
    List<Resource> l = ResourceService.getAllEndpointsWithFreq(frequency);
    LOGGER.info("Endpoints found: " + l.size());
    int count = 0;
    boolean sent;
    for (int i = 0; i < l.size(); i++) {
        Resource resource = l.get(i);
        TestSuiteReport testSuiteReport = RunnerService.testEndpointWithCall(resource, testCollection);
        final int N = resource.getStoreprev();
        // Get last N reports
        List<TestReport> prevReports = TestReportService.getLastReports(resource, N);
        if (prevReports.size() >= N) {
            // Delete older than last N.
            TestReportService.deleteOlderThan(prevReports.get(prevReports.size() - 1));
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            TestReport report = new TestReport(resource, mapper.writeValueAsString(testSuiteReport));
            String reportId = TestReportService.saveReport(report);
            testSuiteReport.setId(reportId);
        } catch (JsonProcessingException e) {
            LOGGER.warn("Unable to save report:" + e.getMessage());
        }
        EmailManager manager = new EmailManager(resource);
        manager.setPrevReports(prevReports);
        sent = manager.sendReport(testSuiteReport);
        if (sent) {
            count += 1;
        }
    }
    return count;
}
Also used : EmailManager(de.ipk_gatersleben.bit.bi.bridge.brapicomp.ci.EmailManager) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 40 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project syndesis-qe by syndesisio.

the class AtlasMapperGenerator method processDataShapeIntoFields.

private List<Field> processDataShapeIntoFields(String stepSpecification, DataShapeKinds dsKind) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
    List<Field> fields = null;
    log.debug(stepSpecification);
    if (dsKind.equals(DataShapeKinds.JAVA)) {
        try {
            JavaClass jClass = mapper.readValue(stepSpecification, JavaClass.class);
            jClass = mapper.readValue(stepSpecification, JavaClass.class);
            List<JavaField> jfields = getJavaFields(jClass);
            fields = jfields.stream().map(f -> (Field) f).collect(Collectors.toList());
        } catch (IOException e) {
            log.error("error: {}" + e);
        }
    } else if (dsKind.equals(DataShapeKinds.JSON_SCHEMA) || dsKind.equals(DataShapeKinds.JSON_INSTANCE)) {
        JsonInspectionResponse inspectionResponse = atlasmapEndpoint.inspectJson(generateJsonInspectionRequest(stepSpecification));
        try {
            String mapperString = mapper.writeValueAsString(inspectionResponse);
            log.debug(mapperString);
            fields = inspectionResponse.getJsonDocument().getFields().getField();
        } catch (JsonProcessingException e) {
            log.error("error: {}" + e);
        }
    } else if (dsKind.equals(DataShapeKinds.XML_SCHEMA) || dsKind.equals(DataShapeKinds.XML_INSTANCE)) {
        // TODO(tplevko)
        throw new UnsupportedOperationException("XML support is not implemented yet");
    }
    return fields;
}
Also used : Field(io.atlasmap.v2.Field) JavaField(io.atlasmap.java.v2.JavaField) JavaField(io.atlasmap.java.v2.JavaField) JavaClass(io.atlasmap.java.v2.JavaClass) JsonInspectionResponse(io.atlasmap.json.v2.JsonInspectionResponse) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)648 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)205 IOException (java.io.IOException)156 HashMap (java.util.HashMap)105 Map (java.util.Map)77 ArrayList (java.util.ArrayList)67 JsonNode (com.fasterxml.jackson.databind.JsonNode)54 List (java.util.List)50 Test (org.junit.Test)44 InputStream (java.io.InputStream)24 Collectors (java.util.stream.Collectors)24 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)23 Json (com.sequenceiq.cloudbreak.domain.json.Json)21 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)20 Function (java.util.function.Function)18 Test (org.testng.annotations.Test)18 File (java.io.File)17 Date (java.util.Date)17 UnsupportedEncodingException (java.io.UnsupportedEncodingException)15 URL (java.net.URL)15