List of usage examples for com.fasterxml.jackson.datatype.joda JodaModule JodaModule
public JodaModule()
From source file:org.apache.nifi.processors.att.m2x.PutM2XStream.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final FlowFile flowFile = session.get(); if (flowFile == null) { return;/* w w w .j av a 2s . c o m*/ } final ProcessorLog logger = getLogger(); final OkHttpClient httpClient = getHttpClient(); final StateManager stateManager = context.getStateManager(); final String apiKey = context.getProperty(M2X_API_KEY).getValue(); final String apiUrl = context.getProperty(M2X_API_URL).getValue(); final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue(); final String streamName = context.getProperty(M2X_STREAM_NAME).getValue(); final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue(); final String streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/") .append(deviceId).append("/streams/").append(streamName).append("/value").toString(); try { final AtomicReference<String> postBodyRef = new AtomicReference<>(); session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream is) { try { String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp"); if (StringUtils.isEmpty(timestamp)) { timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate()); } final String value = IOUtils.toString(is, StandardCharsets.UTF_8); final M2XStreamValue m2xValue = new M2XStreamValue(); m2xValue.setValue(value); m2xValue.setTimestamp(timestamp); final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); final String postBody = mapper.writeValueAsString(m2xValue); logger.warn("POST body is {}", new Object[] { postBody }); postBodyRef.set(postBody); } catch (Exception e) { logger.error(e.getMessage(), e); } } }); final String postBody = postBodyRef.get(); if (StringUtils.isEmpty(postBody)) { logger.error("FlowFile {} contents didn't produce a valid M2X stream value", new Object[] { flowFile }); session.transfer(flowFile, REL_FAILURE); return; } final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey) .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build(); final Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { logger.error(response.message()); context.yield(); session.penalize(flowFile); return; } } catch (IOException e) { logger.error(e.getMessage(), e); context.yield(); session.penalize(flowFile); return; } session.transfer(flowFile, REL_SUCCESS); }
From source file:gr.abiss.calipso.test.AbstractControllerIT.java
@BeforeClass public void setup() { // log request/response in errors RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); // pickup from the command line if given for the jetty-maven-plugin String port = System.getProperty("jetty.http.port"); RestAssured.port = port != null ? Integer.parseInt(port) : 8080; this.WEBSOCKET_URI = new StringBuffer("ws://localhost:").append(RestAssured.port).append("/calipso/ws") .toString();/*from w w w . j av a 2 s.c o m*/ // TODO: // String basePath = System.getProperty("server.base"); // if (basePath == null) { // basePath = "/rest-garage-sample/"; // } // RestAssured.basePath = basePath; // // String baseHost = System.getProperty("server.host"); // if (baseHost == null) { // baseHost = "http://localhost"; // } // RestAssured.baseURI = baseHost; // configure our object mapper RestAssured.config = RestAssuredConfig.config().objectMapperConfig( // config object mapper new ObjectMapperConfig().jackson2ObjectMapperFactory(new Jackson2ObjectMapperFactory() { @Override public ObjectMapper create(Class aClass, String s) { ObjectMapper objectMapper = new ObjectMapper(); // support joda classes<->JSON objectMapper.registerModule(new JodaModule()); // ignore unknown properties objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper; } })); }
From source file:org.mayocat.application.AbstractService.java
protected void configureObjectMapper() { // Initialize our own object mapper. We don't want to use Dropwizard's one (environment.getObjectMapper) because // we don't have full control over its initialization, and we don't necessarily want mayocat's one to be // configured identically as the one used by DW. objectMapper = new ObjectMapper(new YAMLFactory()); // Standard modules objectMapper.registerModule(new GuavaModule()); objectMapper.registerModule(new JodaModule()); objectMapper.registerModule(new AfterburnerModule()); // Dropwizard modules objectMapper.registerModule(new GuavaExtrasModule()); objectMapper.registerModule(new LogbackModule()); // Mayocat modules objectMapper.registerModule(new TimeZoneModule()); objectMapper.registerModule(new NIOModule()); objectMapper.registerModule(new MayocatJodaModule()); objectMapper.registerModule(new MayocatLocaleBCP47LanguageTagModule()); objectMapper.registerModule(new MayocatGroovyModule()); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); }
From source file:com.thinkbiganalytics.integration.IntegrationTestBase.java
@Before public void setupRestAssured() throws URISyntaxException { UserContext.setUser(UserContext.User.ADMIN); RestAssured.baseURI = kyloConfig.getProtocol() + kyloConfig.getHost(); RestAssured.port = kyloConfig.getPort(); RestAssured.basePath = kyloConfig.getBasePath(); RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); Jackson2ObjectMapperFactory factory = (aClass, s) -> { ObjectMapper om = new ObjectMapper(); om.registerModule(new JodaModule()); om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); configureObjectMapper(om);//from w w w. j a va 2s .c om return om; }; com.jayway.restassured.mapper.ObjectMapper objectMapper = new Jackson2Mapper(factory); RestAssured.objectMapper(objectMapper); startClean(); }
From source file:org.killbill.billing.client.KillBillHttpClient.java
/** * @param kbServerUrl Kill Bill url//from w w w. jav a 2 s. c o m * @param username Kill Bill username * @param password Kill Bill password * @param apiKey Kill Bill api key * @param apiSecret Kill Bill api secret * @param proxyHost hostname of a proxy server that the client should use * @param proxyPort port number of a proxy server that the client should use * @param connectTimeOut connect timeout in milliseconds * @param readTimeOut read timeout in milliseconds * @param requestTimeout request timeout in milliseconds * @param strictSSL whether to bypass SSL certificates validation * @param SSLProtocol SSL protocol to use * */ public KillBillHttpClient(final String kbServerUrl, final String username, final String password, final String apiKey, final String apiSecret, final String proxyHost, final Integer proxyPort, final Integer connectTimeOut, final Integer readTimeOut, final Integer requestTimeout, final Boolean strictSSL, final String SSLProtocol) { this.kbServerUrl = kbServerUrl; this.username = username; this.password = password; this.apiKey = apiKey; this.apiSecret = apiSecret; final AsyncHttpClientConfig.Builder cfg = new AsyncHttpClientConfig.Builder(); if (requestTimeout != null) { cfg.setRequestTimeout(requestTimeout); int timeoutSec = (int) TimeUnit.MILLISECONDS.toSeconds(requestTimeout); if (TimeUnit.SECONDS.toMillis(timeoutSec) != requestTimeout) { timeoutSec += 1; } requestTimeoutSec = timeoutSec; } else { cfg.setRequestTimeout(DEFAULT_HTTP_TIMEOUT_SEC * 1000); requestTimeoutSec = DEFAULT_HTTP_TIMEOUT_SEC; } cfg.setConnectTimeout(MoreObjects.firstNonNull(connectTimeOut, DEFAULT_HTTP_TIMEOUT_SEC * 1000)); cfg.setReadTimeout(MoreObjects.firstNonNull(readTimeOut, DEFAULT_HTTP_TIMEOUT_SEC * 1000)); cfg.setUserAgent(USER_AGENT); if (proxyHost != null && proxyPort != null) { final ProxyServer proxyServer = new ProxyServer(proxyHost, proxyPort); cfg.setProxyServer(proxyServer); } if (strictSSL != null) { try { cfg.setSSLContext(SslUtils.getInstance().getSSLContext(strictSSL, SSLProtocol)); } catch (final GeneralSecurityException e) { throw new RuntimeException(e); } } this.httpClient = new AsyncHttpClient(cfg.build()); mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); }
From source file:lib.Global.java
private ObjectMapper buildObjectMapper() { return new ObjectMapper().registerModules(new GuavaModule(), new JodaModule()) .setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES) .enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); }
From source file:com.metamx.rdiclient.RdiClientImplTest.java
@Test public void testMmxAuctionSummary() throws Exception { final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JodaModule()); final Serializer<MmxAuctionSummary> serializer = new JacksonSerializer<>(objectMapper); final RdiClientImpl<MmxAuctionSummary> rdiClient = makeRdiClient(serializer, 1); mockClient.setGoHandler(new GoHandler() { @Override//from w ww. ja v a 2s . c om protected <Intermediate, Final> ListenableFuture<Final> go(Request<Intermediate, Final> request) throws Exception { Assert.assertEquals(new URL(TARGET_URL), request.getUrl()); Preconditions.checkArgument(request.getHandler() instanceof StatusResponseHandler, "WTF?! Expected StatusResponseHandler."); Preconditions.checkArgument( ImmutableList.of("application/json") .equals(request.getHeaders().get(HttpHeaders.Names.CONTENT_TYPE)), "WTF?! Content-type should have been JSON!"); Preconditions.checkArgument( ImmutableList.of("gzip") .equals(request.getHeaders().get(HttpHeaders.Names.CONTENT_ENCODING)), "WTF?! Should have been gzip!"); return Futures.immediateFuture((Final) okResponse()); } }.times(3)); final List<MmxAuctionSummary> events = Arrays.asList(sampleEventBasic, sampleEventBasic, sampleEventBasic); rdiClient.start(); for (MmxAuctionSummary event : events) { rdiClient.send(event); } rdiClient.close(); Assert.assertTrue("mockClient succeeded", mockClient.succeeded()); }
From source file:org.apache.nifi.processors.att.m2x.GetM2XStream.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { final ProcessorLog logger = getLogger(); final OkHttpClient httpClient = getHttpClient(); final StateManager stateManager = context.getStateManager(); final String apiKey = context.getProperty(M2X_API_KEY).getValue(); final String apiUrl = context.getProperty(M2X_API_URL).getValue(); final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue(); final String streamName = context.getProperty(M2X_STREAM_NAME).getValue(); final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue(); final String startTime = getLastStartTime(context, stateManager); final String streamUrl = getStreamUrl(apiUrl, deviceId, streamName, startTime); String responseBody;// w ww . java 2 s .c o m try { final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey).build(); final Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { logger.error(response.message()); context.yield(); return; } responseBody = response.body().string(); } catch (IOException e) { logger.error(e.getMessage(), e); context.yield(); return; } final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); try { final M2XStreamValues m2xValues = mapper.readValue(responseBody, M2XStreamValues.class); final List<M2XStreamValue> m2xValueList = m2xValues.getValues(); if (!CollectionUtils.isEmpty(m2xValueList)) { for (final M2XStreamValue m2xValue : m2xValueList) { final DateTime timestamp = m2xValue.getTimestamp(); final Object valueObj = m2xValue.getValue(); final Set<Map.Entry<String, Object>> properties = m2xValue.getAdditionalProperties().entrySet(); final ByteArrayInputStream bytes = new ByteArrayInputStream( String.valueOf(valueObj).getBytes(StandardCharsets.UTF_8)); FlowFile newFlowFile = session.create(); newFlowFile = session.importFrom(bytes, newFlowFile); newFlowFile = session.putAttribute(newFlowFile, "m2x.device.id", deviceId); newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.name", streamName); newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.start", m2xValues.getStart().toString()); newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.end", m2xValues.getEnd().toString()); newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.limit", String.valueOf(m2xValues.getLimit())); newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.timestamp", timestamp.toString()); newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value.millis", String.valueOf(timestamp.getMillis())); for (final Map.Entry<String, Object> e : properties) { newFlowFile = session.putAttribute(newFlowFile, "m2x.stream.value." + e.getKey(), String.valueOf(e.getValue())); } session.getProvenanceReporter().create(newFlowFile); session.transfer(newFlowFile, REL_SUCCESS); } } setLastStartTime(stateManager, m2xValues.getEnd().toString()); } catch (Throwable t) { logger.error(t.getMessage(), t); context.yield(); } }
From source file:org.mayocat.configuration.internal.DefaultConfigurationService.java
public ObjectMapper getObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new GuavaModule()); mapper.registerModule(new JodaModule()); mapper.registerModule(new GuavaExtrasModule()); mapper.registerModule(new TimeZoneModule()); return mapper; }
From source file:com.metamx.rdiclient.RdiClientImplTest.java
@Test public void testBadResponseCode() throws Exception { final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JodaModule()); final Serializer<MmxAuctionSummary> serializer = new JacksonSerializer<>(objectMapper); final RdiClientImpl<MmxAuctionSummary> rdiClient = makeRdiClient(serializer, 1); mockClient.setGoHandler(new GoHandler() { @Override/*from w w w . j a v a 2s . c o m*/ protected <Intermediate, Final> ListenableFuture<Final> go(Request<Intermediate, Final> request) throws Exception { return Futures.immediateFuture((Final) serverResponse(503, "Internal Server Error.")); } }.times(12)); final List<MmxAuctionSummary> events = Arrays.asList(sampleEventBasic, sampleEventBasic, sampleEventBasic); rdiClient.start(); for (MmxAuctionSummary event : events) { final ListenableFuture<RdiResponse> result = rdiClient.send(event); Exception e = null; try { result.get(); } catch (Exception e2) { e = e2; } Assert.assertTrue(e instanceof ExecutionException); Assert.assertTrue(e.getCause() instanceof RdiHttpResponseException); Assert.assertTrue(((RdiHttpResponseException) e.getCause()).getStatusCode() == 503); Assert.assertTrue(((RdiHttpResponseException) e.getCause()).getStatusReasonPhrase() .equals("Internal Server Error.")); } rdiClient.close(); }