Search in sources :

Example 41 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project joynr by bmwcarit.

the class ProxyTest method createProxyAndCallAsyncMethodFail.

@Test
public void createProxyAndCallAsyncMethodFail() throws Exception {
    // Expect this exception to be passed back to the callback onFailure and thrown in the future
    final JoynrCommunicationException expectedException = new JoynrCommunicationException();
    // final JoynCommunicationException expectedException = null;
    TestInterface proxy = getTestInterfaceProxy();
    // when joynrMessageSender1.sendRequest is called, get the replyCaller from the mock dispatcher and call
    // messageCallback on it.
    Mockito.doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws JsonParseException, JsonMappingException, IOException {
            // capture the replyCaller passed into the dispatcher for calling later
            ArgumentCaptor<ReplyCaller> replyCallerCaptor = ArgumentCaptor.forClass(ReplyCaller.class);
            verify(replyCallerDirectory).addReplyCaller(anyString(), replyCallerCaptor.capture(), any(ExpiryDate.class));
            // pass the exception to the replyCaller
            replyCallerCaptor.getValue().error(expectedException);
            return null;
        }
    }).when(requestReplyManager).sendRequest(Mockito.<String>any(), Mockito.<DiscoveryEntryWithMetaInfo>any(), Mockito.<Request>any(), Mockito.<MessagingQos>any());
    boolean exceptionThrown = false;
    String reply = "";
    final Future<String> future = proxy.asyncMethod(callback);
    try {
        // the test usually takes only 200 ms, so if we wait 1 sec, something has gone wrong
        reply = future.get(1000);
    } catch (JoynrCommunicationException e) {
        exceptionThrown = true;
    }
    Assert.assertTrue("exception must be thrown from get", exceptionThrown);
    verify(callback).onFailure(expectedException);
    verifyNoMoreInteractions(callback);
    Assert.assertEquals(RequestStatusCode.ERROR, future.getStatus().getCode());
    Assert.assertEquals("", reply);
}
Also used : ArgumentCaptor(org.mockito.ArgumentCaptor) IOException(java.io.IOException) Matchers.anyString(org.mockito.Matchers.anyString) JoynrCommunicationException(io.joynr.exceptions.JoynrCommunicationException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ReplyCaller(io.joynr.dispatching.rpc.ReplyCaller) SynchronizedReplyCaller(io.joynr.dispatching.rpc.SynchronizedReplyCaller) InvocationOnMock(org.mockito.invocation.InvocationOnMock) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) Test(org.junit.Test)

Example 42 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project irida by phac-nml.

the class AnalysisController method getSistrAnalysis.

/**
 * Get the sistr analysis information to display
 *
 * @param id ID of the analysis submission
 * @return Json results for the SISTR analysis
 */
@SuppressWarnings("resource")
@RequestMapping("/ajax/sistr/{id}")
@ResponseBody
public Map<String, Object> getSistrAnalysis(@PathVariable Long id) {
    AnalysisSubmission submission = analysisSubmissionService.read(id);
    Collection<Sample> samples = sampleService.getSamplesForAnalysisSubmission(submission);
    Map<String, Object> result = ImmutableMap.of("parse_results_error", true);
    final String sistrFileKey = "sistr-predictions";
    // Get details about the workflow
    UUID workflowUUID = submission.getWorkflowId();
    IridaWorkflow iridaWorkflow;
    try {
        iridaWorkflow = workflowsService.getIridaWorkflow(workflowUUID);
    } catch (IridaWorkflowNotFoundException e) {
        logger.error("Error finding workflow, ", e);
        throw new EntityNotFoundException("Couldn't find workflow for submission " + submission.getId(), e);
    }
    AnalysisType analysisType = iridaWorkflow.getWorkflowDescription().getAnalysisType();
    if (analysisType.equals(AnalysisType.SISTR_TYPING)) {
        Analysis analysis = submission.getAnalysis();
        Path path = analysis.getAnalysisOutputFile(sistrFileKey).getFile();
        try {
            String json = new Scanner(new BufferedReader(new FileReader(path.toFile()))).useDelimiter("\\Z").next();
            // verify file is proper json file
            ObjectMapper mapper = new ObjectMapper();
            List<Map<String, Object>> sistrResults = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {
            });
            if (sistrResults.size() > 0) {
                // should only ever be one sample for these results
                if (samples.size() == 1) {
                    Sample sample = samples.iterator().next();
                    result = sistrResults.get(0);
                    result.put("parse_results_error", false);
                    result.put("sample_name", sample.getSampleName());
                } else {
                    logger.error("Invalid number of associated samles for submission " + submission);
                }
            } else {
                logger.error("SISTR results for file [" + path + "] are not correctly formatted");
            }
        } catch (FileNotFoundException e) {
            logger.error("File [" + path + "] not found", e);
        } catch (JsonParseException | JsonMappingException e) {
            logger.error("Error attempting to parse file [" + path + "] as JSON", e);
        } catch (IOException e) {
            logger.error("Error reading file [" + path + "]", e);
        }
    }
    return result;
}
Also used : AnalysisType(ca.corefacility.bioinformatics.irida.model.enums.AnalysisType) IridaWorkflow(ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow) AnalysisSubmission(ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission) JsonParseException(com.fasterxml.jackson.core.JsonParseException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(java.nio.file.Path) Sample(ca.corefacility.bioinformatics.irida.model.sample.Sample) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) IridaWorkflowNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowNotFoundException) Analysis(ca.corefacility.bioinformatics.irida.model.workflow.analysis.Analysis) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 43 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project dcos-commons by mesosphere.

the class DefaultServiceSpecTest method invalidTaskName.

@Test
public void invalidTaskName() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("invalid-task-name.yml").getFile());
    try {
        DefaultServiceSpec.newGenerator(file, SCHEDULER_CONFIG).build();
        Assert.fail("Expected exception");
    } catch (JsonMappingException e) {
        Assert.assertTrue(e.getCause().toString(), e.getCause() instanceof JsonParseException);
        JsonParseException cause = (JsonParseException) e.getCause();
        Assert.assertTrue(cause.getMessage(), cause.getMessage().contains("Duplicate field 'meta-data-task'"));
    }
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) File(java.io.File) Test(org.junit.Test)

Example 44 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project service-proxy by membrane.

the class EtcdResponse method get.

@SuppressWarnings("unchecked")
public String get(String name) {
    JsonParser par = getParser(body);
    String result = null;
    Map<String, Object> respData = null;
    try {
        respData = new ObjectMapper().readValue(par, Map.class);
    } catch (JsonParseException e) {
    } catch (JsonMappingException e) {
    } catch (IOException e) {
    }
    if (respData.containsKey("node")) {
        LinkedHashMap<String, Object> nodeJson = (LinkedHashMap<String, Object>) respData.get("node");
        if (nodeJson.containsKey(name)) {
            result = nodeJson.get(name).toString();
        }
    }
    if (result == null) {
        throw new RuntimeException();
    }
    return result;
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonParser(com.fasterxml.jackson.core.JsonParser) LinkedHashMap(java.util.LinkedHashMap)

Example 45 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project rdf4j by eclipse.

the class JSONLDWriter method endRDF.

@Override
public void endRDF() throws RDFHandlerException {
    final JSONLDInternalRDFParser serialiser = new JSONLDInternalRDFParser();
    try {
        Object output = JsonLdProcessor.fromRDF(model, serialiser);
        final JSONLDMode mode = getWriterConfig().get(JSONLDSettings.JSONLD_MODE);
        final JsonLdOptions opts = new JsonLdOptions();
        // opts.addBlankNodeIDs =
        // getWriterConfig().get(BasicParserSettings.PRESERVE_BNODE_IDS);
        opts.setUseRdfType(getWriterConfig().get(JSONLDSettings.USE_RDF_TYPE));
        opts.setUseNativeTypes(getWriterConfig().get(JSONLDSettings.USE_NATIVE_TYPES));
        if (baseURI != null && getWriterConfig().get(BasicWriterSettings.BASE_DIRECTIVE)) {
            opts.setBase(baseURI);
        }
        if (mode == JSONLDMode.EXPAND) {
            output = JsonLdProcessor.expand(output, opts);
        }
        // TODO: Implement inframe in JSONLDSettings
        final Object inframe = null;
        if (mode == JSONLDMode.FLATTEN) {
            output = JsonLdProcessor.flatten(output, inframe, opts);
        }
        if (mode == JSONLDMode.COMPACT) {
            final Map<String, Object> ctx = new LinkedHashMap<String, Object>();
            addPrefixes(ctx, model.getNamespaces());
            final Map<String, Object> localCtx = new HashMap<String, Object>();
            localCtx.put("@context", ctx);
            output = JsonLdProcessor.compact(output, localCtx, opts);
        }
        if (getWriterConfig().get(BasicWriterSettings.PRETTY_PRINT)) {
            JsonUtils.writePrettyPrint(writer, output);
        } else {
            JsonUtils.write(writer, output);
        }
    } catch (final JsonLdError e) {
        throw new RDFHandlerException("Could not render JSONLD", e);
    } catch (final JsonGenerationException e) {
        throw new RDFHandlerException("Could not render JSONLD", e);
    } catch (final JsonMappingException e) {
        throw new RDFHandlerException("Could not render JSONLD", e);
    } catch (final IOException e) {
        throw new RDFHandlerException("Could not render JSONLD", e);
    }
}
Also used : JSONLDMode(org.eclipse.rdf4j.rio.helpers.JSONLDMode) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IOException(java.io.IOException) JsonLdError(com.github.jsonldjava.core.JsonLdError) LinkedHashMap(java.util.LinkedHashMap) JsonLdOptions(com.github.jsonldjava.core.JsonLdOptions) RDFHandlerException(org.eclipse.rdf4j.rio.RDFHandlerException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException)

Aggregations

JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)147 IOException (java.io.IOException)75 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)62 JsonParseException (com.fasterxml.jackson.core.JsonParseException)53 Test (org.junit.Test)28 JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)23 ArrayList (java.util.ArrayList)16 HashMap (java.util.HashMap)16 JsonNode (com.fasterxml.jackson.databind.JsonNode)14 File (java.io.File)14 Map (java.util.Map)14 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)11 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)10 InputStream (java.io.InputStream)9 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 List (java.util.List)7 Writer (org.alfresco.rest.framework.jacksonextensions.JacksonHelper.Writer)7 Test (org.junit.jupiter.api.Test)6 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)5