Search in sources :

Example 91 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project wikidata-query-rdf by wikimedia.

the class WikibaseRepository method fetchRecentChanges.

/**
 * Fetch recent changes starting from nextStartTime or continuing from
 * lastContinue depending on the contents of lastContinue way to use
 * MediaWiki. See RecentChangesPoller for how to poll these. Or just use it.
 *
 * @param nextStartTime if lastContinue is null then this is the start time
 *            of the query
 * @param batchSize the number of recent changes to fetch
 * @param lastContinue Continuation object from last batch, or null.
 * @return result of query
 * @throws RetryableException thrown if there is an error communicating with
 *             wikibase
 */
public RecentChangeResponse fetchRecentChanges(Instant nextStartTime, Continue lastContinue, int batchSize) throws RetryableException {
    URI uri = uris.recentChanges(nextStartTime, lastContinue, batchSize);
    log.debug("Polling for changes from {}", uri);
    HttpGet request = new HttpGet(uri);
    request.setConfig(configWithTimeout);
    try {
        return checkApi(getJson(request, RecentChangeResponse.class));
    } catch (UnknownHostException | SocketException e) {
        // We want to bail on this, since it happens to be sticky for some reason
        throw new RuntimeException(e);
    } catch (JsonParseException | JsonMappingException e) {
        // An invalid response will probably not fix itself with a retry, so let's bail
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RetryableException("Error fetching recent changes", e);
    }
}
Also used : SocketException(java.net.SocketException) RetryableException(org.wikidata.query.rdf.tool.exception.RetryableException) UnknownHostException(java.net.UnknownHostException) HttpGet(org.apache.http.client.methods.HttpGet) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) URI(java.net.URI)

Example 92 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project nifi by apache.

the class SiteToSiteRestApiClient method readResponse.

private TransactionResultEntity readResponse(final InputStream inputStream) throws IOException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StreamUtils.copy(inputStream, bos);
    String responseMessage = null;
    try {
        responseMessage = new String(bos.toByteArray(), "UTF-8");
        logger.debug("readResponse responseMessage={}", responseMessage);
        final ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(responseMessage, TransactionResultEntity.class);
    } catch (JsonParseException | JsonMappingException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to parse JSON.", e);
        }
        final TransactionResultEntity entity = new TransactionResultEntity();
        entity.setResponseCode(ResponseCode.ABORT.getCode());
        entity.setMessage(responseMessage);
        return entity;
    }
}
Also used : TransactionResultEntity(org.apache.nifi.web.api.entity.TransactionResultEntity) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 93 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project metron by apache.

the class ThreatIntelJoinBoltTest method test.

public void test(String threatTriageConfig, boolean badConfig) throws IOException {
    ThreatIntelJoinBolt threatIntelJoinBolt = new ThreatIntelJoinBolt("zookeeperUrl");
    threatIntelJoinBolt.setCuratorFramework(client);
    threatIntelJoinBolt.setZKCache(cache);
    SensorEnrichmentConfig enrichmentConfig = JSONUtils.INSTANCE.load(new FileInputStream(sampleSensorEnrichmentConfigPath), SensorEnrichmentConfig.class);
    boolean withThreatTriage = threatTriageConfig != null;
    if (withThreatTriage) {
        try {
            enrichmentConfig.getThreatIntel().setTriageConfig(JSONUtils.INSTANCE.load(threatTriageConfig, ThreatTriageConfig.class));
            if (badConfig) {
                Assert.fail(threatTriageConfig + "\nThis should not parse!");
            }
        } catch (JsonMappingException pe) {
            if (!badConfig) {
                throw pe;
            }
        }
    }
    threatIntelJoinBolt.getConfigurations().updateSensorEnrichmentConfig(sensorType, enrichmentConfig);
    HashMap<String, Object> globalConfig = new HashMap<>();
    String baseDir = UnitTestHelper.findDir("GeoLite");
    File geoHdfsFile = new File(new File(baseDir), "GeoIP2-City-Test.mmdb.gz");
    globalConfig.put(GeoLiteDatabase.GEO_HDFS_FILE, geoHdfsFile.getAbsolutePath());
    threatIntelJoinBolt.getConfigurations().updateGlobalConfig(globalConfig);
    threatIntelJoinBolt.withMaxCacheSize(100);
    threatIntelJoinBolt.withMaxTimeRetain(10000);
    threatIntelJoinBolt.prepare(new HashMap<>(), topologyContext, outputCollector);
    Map<String, Object> fieldMap = threatIntelJoinBolt.getFieldMap("incorrectSourceType");
    Assert.assertNull(fieldMap);
    fieldMap = threatIntelJoinBolt.getFieldMap(sensorType);
    Assert.assertTrue(fieldMap.containsKey("hbaseThreatIntel"));
    MessageGetStrategy messageGetStrategy = mock(MessageGetStrategy.class);
    Tuple messageTuple = mock(Tuple.class);
    when(messageGetStrategy.get(messageTuple)).thenReturn(message);
    Map<String, Tuple> streamMessageMap = new HashMap<>();
    streamMessageMap.put("message", messageTuple);
    JSONObject joinedMessage = threatIntelJoinBolt.joinMessages(streamMessageMap, messageGetStrategy);
    assertFalse(joinedMessage.containsKey("is_alert"));
    when(messageGetStrategy.get(messageTuple)).thenReturn(messageWithTiming);
    joinedMessage = threatIntelJoinBolt.joinMessages(streamMessageMap, messageGetStrategy);
    assertFalse(joinedMessage.containsKey("is_alert"));
    when(messageGetStrategy.get(messageTuple)).thenReturn(alertMessage);
    joinedMessage = threatIntelJoinBolt.joinMessages(streamMessageMap, messageGetStrategy);
    assertTrue(joinedMessage.containsKey("is_alert") && "true".equals(joinedMessage.get("is_alert")));
    if (withThreatTriage && !badConfig) {
        assertTrue(joinedMessage.containsKey("threat.triage.score"));
        Double score = (Double) joinedMessage.get("threat.triage.score");
        assertTrue(Math.abs(10d - score) < 1e-10);
    } else {
        assertFalse(joinedMessage.containsKey("threat.triage.score"));
    }
}
Also used : ThreatTriageConfig(org.apache.metron.common.configuration.enrichment.threatintel.ThreatTriageConfig) HashMap(java.util.HashMap) MessageGetStrategy(org.apache.metron.common.message.MessageGetStrategy) FileInputStream(java.io.FileInputStream) JSONObject(org.json.simple.JSONObject) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) JSONObject(org.json.simple.JSONObject) File(java.io.File) SensorEnrichmentConfig(org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig) Tuple(org.apache.storm.tuple.Tuple)

Example 94 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project verify-hub by alphagov.

the class IdaJsonProcessingExceptionMapperTest method toResponse_shouldReturnBadRequestAndErrorStatusDtoWhenErrorDeemedToBeFromClient.

@Test
public void toResponse_shouldReturnBadRequestAndErrorStatusDtoWhenErrorDeemedToBeFromClient() throws Exception {
    String clientErrorMessage = "This is a client error";
    Response response = mapper.toResponse(new JsonMappingException(clientErrorMessage));
    ErrorStatusDto errorStatus = (ErrorStatusDto) response.getEntity();
    assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
    assertThat(errorStatus.isAudited()).isEqualTo(false);
    assertThat(errorStatus.getClientMessage()).isEqualTo(clientErrorMessage);
    assertThat(errorStatus.getExceptionType()).isEqualTo(ExceptionType.JSON_PARSING);
}
Also used : Response(javax.ws.rs.core.Response) ErrorStatusDto(uk.gov.ida.common.ErrorStatusDto) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) Test(org.junit.Test)

Example 95 with JsonMappingException

use of com.fasterxml.jackson.databind.JsonMappingException in project verify-hub by alphagov.

the class IdaJsonProcessingExceptionMapperTest method toResponse_shouldReturnBadRequestAndErrorStatusDtoWhenErrorDeemedToBeFromClient.

@Test
public void toResponse_shouldReturnBadRequestAndErrorStatusDtoWhenErrorDeemedToBeFromClient() throws Exception {
    String clientErrorMessage = "This is a client error";
    Response response = mapper.toResponse(new JsonMappingException(clientErrorMessage));
    ErrorStatusDto errorStatus = (ErrorStatusDto) response.getEntity();
    assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
    assertThat(errorStatus.isAudited()).isEqualTo(false);
    assertThat(errorStatus.getClientMessage()).isEqualTo(clientErrorMessage);
    assertThat(errorStatus.getExceptionType()).isEqualTo(ExceptionType.JSON_PARSING);
}
Also used : Response(javax.ws.rs.core.Response) ErrorStatusDto(uk.gov.ida.common.ErrorStatusDto) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) Test(org.junit.Test)

Aggregations

JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)140 IOException (java.io.IOException)68 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)54 JsonParseException (com.fasterxml.jackson.core.JsonParseException)52 Test (org.junit.Test)31 JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)19 HashMap (java.util.HashMap)16 ArrayList (java.util.ArrayList)14 Map (java.util.Map)14 JsonNode (com.fasterxml.jackson.databind.JsonNode)12 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)11 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)10 File (java.io.File)9 InputStream (java.io.InputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 List (java.util.List)7 Writer (org.alfresco.rest.framework.jacksonextensions.JacksonHelper.Writer)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 Response (javax.ws.rs.core.Response)6 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)5