List of usage examples for com.fasterxml.jackson.databind ObjectMapper writeValueAsBytes
@SuppressWarnings("resource") public byte[] writeValueAsBytes(Object value) throws JsonProcessingException
From source file:org.apache.nifi.processors.msgpack.MessagePackPack.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile flowFile = session.get();// w ww. j av a 2 s .com if (flowFile == null) { return; } final ObjectMapper reader = new ObjectMapper(); final ObjectMapper writer = new ObjectMapper(new MessagePackFactory()); writer.setAnnotationIntrospector(new JsonArrayFormat()); final AtomicBoolean failed = new AtomicBoolean(false); flowFile = session.write(flowFile, new StreamCallback() { @Override public void process(InputStream is, OutputStream os) throws IOException { try (final OutputStream msgpack = new BufferedOutputStream(os)) { final JsonNode json = reader.readTree(is); final byte[] bytes = writer.writeValueAsBytes(json); msgpack.write(bytes); msgpack.flush(); } catch (JsonProcessingException e) { getLogger().error(e.getMessage(), e); failed.set(true); } } }); if (failed.get()) { session.transfer(flowFile, REL_FAILURE); return; } flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), MIME_TYPE); flowFile = session.putAttribute(flowFile, MIME_EXT_KEY, MIME_EXT); session.transfer(flowFile, REL_SUCCESS); }
From source file:io.orchestrate.client.HttpClient.java
/** {@inheritDoc} */ @Override//w w w. java 2 s . c o m public OrchestrateFuture<KvMetadata> execute(final KvStoreOperation kvStoreOp) { checkNotNull(kvStoreOp, "kvStoreOp"); final OrchestrateFutureImpl<KvMetadata> future = new OrchestrateFutureImpl<KvMetadata>(kvStoreOp); final ObjectMapper mapper = builder.getMapper().getMapper(); final byte[] content; try { final Object value = kvStoreOp.getValue(); if (value instanceof String) { content = ((String) value).getBytes(); } else { content = mapper.writeValueAsBytes(value); } } catch (final JsonProcessingException e) { future.setException(e); return future; } final UEncoder urlEncoder = new UEncoder(); final String uri = urlEncoder.encodeURL(kvStoreOp.getCollection()).concat("/") .concat(urlEncoder.encodeURL(kvStoreOp.getKey())); final HttpRequestPacket.Builder httpHeaderBuilder = HttpRequestPacket.builder().method(Method.PUT) .contentType("application/json").uri(uri); if (kvStoreOp.hasCurrentRef()) { final String ref = "\"".concat(kvStoreOp.getCurrentRef()).concat("\""); httpHeaderBuilder.header(Header.IfMatch, ref); } else if (kvStoreOp.hasIfAbsent()) { httpHeaderBuilder.header(Header.IfNoneMatch, "\"*\""); } httpHeaderBuilder.contentLength(content.length); final HttpContent httpContent = httpHeaderBuilder.build().httpContentBuilder() .content(new ByteBufferWrapper(ByteBuffer.wrap(content))).build(); execute(httpContent, future); return future; }
From source file:io.orchestrate.client.HttpClient.java
/** {@inheritDoc} */ @Override/*ww w . j a va 2 s . c om*/ public OrchestrateFuture<Boolean> execute(final EventStoreOperation eventStoreOp) { checkNotNull(eventStoreOp, "eventStoreOp"); final OrchestrateFutureImpl<Boolean> future = new OrchestrateFutureImpl<Boolean>(eventStoreOp); final ObjectMapper mapper = builder.getMapper().getMapper(); final byte[] content; try { final Object value = eventStoreOp.getValue(); if (value instanceof String) { content = ((String) value).getBytes(); } else { content = mapper.writeValueAsBytes(value); } } catch (final JsonProcessingException e) { future.setException(e); return future; } final UEncoder urlEncoder = new UEncoder(); final String uri = urlEncoder.encodeURL(eventStoreOp.getCollection()).concat("/") .concat(urlEncoder.encodeURL(eventStoreOp.getKey())).concat("/events/") .concat(urlEncoder.encodeURL(eventStoreOp.getType())); final HttpRequestPacket.Builder httpHeaderBuilder = HttpRequestPacket.builder().method(Method.PUT) .contentType("application/json").uri(uri); if (eventStoreOp.hasTimestamp()) { httpHeaderBuilder.query("timestamp=" + eventStoreOp.getTimestamp()); } httpHeaderBuilder.contentLength(content.length); final HttpContent httpContent = httpHeaderBuilder.build().httpContentBuilder() .content(new ByteBufferWrapper(ByteBuffer.wrap(content))).build(); execute(httpContent, future); return future; }
From source file:com.cloudera.livy.client.common.TestHttpMessages.java
/** * Tests that all defined messages can be serialized and deserialized using Jackson. *//*from w ww. j a va 2 s. c om*/ @Test public void testMessageSerialization() throws Exception { ObjectMapper mapper = new ObjectMapper(); for (Class<?> msg : HttpMessages.class.getClasses()) { if (msg.isInterface()) { continue; } String name = msg.getSimpleName(); Constructor c = msg.getConstructors()[0]; Object[] params = new Object[c.getParameterTypes().length]; Type[] genericTypes = c.getGenericParameterTypes(); for (int i = 0; i < params.length; i++) { params[i] = dummyValue(c.getParameterTypes()[i], genericTypes[i]); } Object o1 = c.newInstance(params); byte[] serialized = mapper.writeValueAsBytes(o1); Object o2 = mapper.readValue(serialized, msg); assertNotNull("could not deserialize " + name, o2); for (Field f : msg.getFields()) { checkEquals(name, f, o1, o2); } } }
From source file:com.yahoo.pulsar.broker.loadbalance.SimpleLoadManagerImplTest.java
private void createNamespacePolicies(PulsarService pulsar) throws Exception { NamespaceIsolationPolicies policies = new NamespaceIsolationPolicies(); // set up policy that use this broker as primary NamespaceIsolationData policyData = new NamespaceIsolationData(); policyData.namespaces = new ArrayList<String>(); policyData.namespaces.add("pulsar/use/primary-ns.*"); policyData.primary = new ArrayList<String>(); policyData.primary.add(pulsar1.getAdvertisedAddress() + "*"); policyData.secondary = new ArrayList<String>(); policyData.secondary.add("prod2-broker([78]).messaging.usw.example.co.*"); policyData.auto_failover_policy = new AutoFailoverPolicyData(); policyData.auto_failover_policy.policy_type = AutoFailoverPolicyType.min_available; policyData.auto_failover_policy.parameters = new HashMap<String, String>(); policyData.auto_failover_policy.parameters.put("min_limit", "1"); policyData.auto_failover_policy.parameters.put("usage_threshold", "100"); policies.setPolicy("primaryBrokerPolicy", policyData); ObjectMapper jsonMapper = ObjectMapperFactory.create(); ZooKeeper globalZk = pulsar.getGlobalZkCache().getZooKeeper(); ZkUtils.createFullPathOptimistic(globalZk, AdminResource.path("clusters", "use", "namespaceIsolationPolicies"), new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); byte[] content = jsonMapper.writeValueAsBytes(policies.getPolicies()); globalZk.setData(AdminResource.path("clusters", "use", "namespaceIsolationPolicies"), content, -1); }
From source file:gov.bnl.channelfinder.PropertiesResource.java
/** * PUT method for creating multiple properties. * * @param data XmlProperties data (from payload) * @return HTTP Response// w w w. j av a 2 s. co m * @throws IOException * when audit or log fail */ @PUT @Consumes("application/json") public Response create(List<XmlProperty> data) throws IOException { Client client = getNewClient(); UserManager um = UserManager.getInstance(); um.setUser(securityContext.getUserPrincipal(), securityContext.isUserInRole("Administrator")); ObjectMapper mapper = new ObjectMapper(); try { BulkRequestBuilder bulkRequest = client.prepareBulk(); for (XmlProperty property : data) { bulkRequest.add(client.prepareUpdate("properties", "property", property.getName()) .setDoc(mapper.writeValueAsBytes(property)) .setUpsert(new IndexRequest("properties", "property", property.getName()) .source(mapper.writeValueAsBytes(property)))); } bulkRequest.setRefresh(true); BulkResponse bulkResponse = bulkRequest.execute().actionGet(); if (bulkResponse.hasFailures()) { return handleException(um.getUserName(), "PUT", Response.Status.INTERNAL_SERVER_ERROR, bulkResponse.buildFailureMessage()); } else { Response r = Response.noContent().build(); audit.info( um.getUserName() + "|" + uriInfo.getPath() + "|PUT|OK|" + r.getStatus() + "|data=" + data); return r; } } catch (Exception e) { return handleException(um.getUserName(), "PUT", Response.Status.INTERNAL_SERVER_ERROR, e); } finally { client.close(); } }
From source file:gov.bnl.channelfinder.PropertiesResource.java
/** * POST method for creating multiple properties. * * If the channels don't exist it will fail * * @param data XmlProperties data (from payload) * @return HTTP Response/* w w w . j a v a 2 s . co m*/ * @throws IOException * when audit or log fail */ @POST @Consumes("application/json") public Response update(List<XmlProperty> data) throws IOException { Client client = getNewClient(); UserManager um = UserManager.getInstance(); um.setUser(securityContext.getUserPrincipal(), securityContext.isUserInRole("Administrator")); ObjectMapper mapper = new ObjectMapper(); try { BulkRequestBuilder bulkRequest = client.prepareBulk(); for (XmlProperty property : data) { bulkRequest.add(client.prepareUpdate("properties", "property", property.getName()) .setDoc(mapper.writeValueAsBytes(property)) .setUpsert(new IndexRequest("properties", "property", property.getName()) .source(mapper.writeValueAsBytes(property)))); if (property.getChannels() != null) { HashMap<String, String> param = new HashMap<String, String>(); param.put("name", property.getName()); param.put("owner", property.getOwner()); param.put("value", property.getValue()); for (XmlChannel channel : property.getChannels()) { bulkRequest.add(new UpdateRequest("channelfinder", "channel", channel.getName()) .refresh(true) .script("removeProperty = new Object();" + "for (xmlProp in ctx._source.properties) " + "{ if (xmlProp.name == property.name) { removeProperty = xmlProp} }; " + "ctx._source.tags.remove(removeProperty);" + "ctx._source.tags.add(property)") .addScriptParam("property", param)); } } } bulkRequest.setRefresh(true); BulkResponse bulkResponse = bulkRequest.execute().actionGet(); if (bulkResponse.hasFailures()) { audit.severe(bulkResponse.buildFailureMessage()); if (bulkResponse.buildFailureMessage().contains("DocumentMissingException")) { return handleException(um.getUserName(), "POST", Response.Status.NOT_FOUND, bulkResponse.buildFailureMessage()); } else { return handleException(um.getUserName(), "POST", Response.Status.INTERNAL_SERVER_ERROR, bulkResponse.buildFailureMessage()); } } else { Response r = Response.noContent().build(); audit.info( um.getUserName() + "|" + uriInfo.getPath() + "|PUT|OK|" + r.getStatus() + "|data=" + data); return r; } } catch (Exception e) { return handleException(um.getUserName(), "POST", Response.Status.INTERNAL_SERVER_ERROR, e); } finally { client.close(); } }
From source file:gov.bnl.channelfinder.ChannelsResource.java
/** * PUT method for creating/replacing a channel instance identified by the payload. * The <b>complete</b> set of properties for the channel must be supplied, * which will replace the existing set of properties. * * @param chan name of channel to create or add * @param data new data (properties/tags) for channel <tt>chan</tt> * @return HTTP response//from w w w . ja va 2 s .c o m */ @PUT @Path("{chName: " + chNameRegex + "}") @Consumes("application/json") public Response create(@PathParam("chName") String chan, XmlChannel data) { audit.severe("PUT:" + XmlChannel.toLog(data)); UserManager um = UserManager.getInstance(); um.setUser(securityContext.getUserPrincipal(), securityContext.isUserInRole("Administrator")); if (data.getName() == null || data.getName().isEmpty()) { return handleException(um.getUserName(), "PUT", Response.Status.BAD_REQUEST, "Specified channel name '" + chan + "' and payload channel name '" + data.getName() + "' do not match"); } if (!validateChannelName(chan, data)) { return handleException(um.getUserName(), "PUT", Response.Status.BAD_REQUEST, "Specified channel name '" + chan + "' and payload channel name '" + data.getName() + "' do not match"); } long start = System.currentTimeMillis(); Client client = getNewClient(); ObjectMapper mapper = new ObjectMapper(); try { start = System.currentTimeMillis(); data = validateChannel(data, client); audit.info(um.getUserName() + "|" + uriInfo.getPath() + "|PUT|validation : " + (System.currentTimeMillis() - start)); IndexRequest indexRequest = new IndexRequest("channelfinder", "channel", chan) .source(mapper.writeValueAsBytes(data)); UpdateRequest updateRequest = new UpdateRequest("channelfinder", "channel", chan) .doc(mapper.writeValueAsBytes(data)).upsert(indexRequest).refresh(true); UpdateResponse result = client.update(updateRequest).actionGet(); Response r = Response.noContent().build(); audit.info(um.getUserName() + "|" + uriInfo.getPath() + "|PUT|OK|" + r.getStatus() + "|data=" + XmlChannel.toLog(data)); return r; } catch (IllegalArgumentException e) { return handleException(um.getUserName(), "PUT", Response.Status.BAD_REQUEST, e); } catch (Exception e) { return handleException(um.getUserName(), "PUT", Response.Status.INTERNAL_SERVER_ERROR, e); } finally { client.close(); } }
From source file:com.unilever.audit.services2.Sync_Down.java
/** * Retrieves representation of an instance of * com.unilever.audit.services2.AuditResource * * @param id// w w w. j av a 2s . c o m * @param dataType * @return an instance of java.lang.String */ @GET @Path("getSyncObject/{id}/{dataType}/{compress}") @Produces("application/json") public byte[] getSyncObject(@PathParam("id") int id, @PathParam("dataType") String dataType, @PathParam("compress") int compress) { GZIPOutputStream gzip = null; count++; ByteArrayOutputStream out = null; SyncDownObjects syncDownObjects = getObject(dataType, id); try { out = new ByteArrayOutputStream(); gzip = new GZIPOutputStream(out); ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); AnnotationIntrospector introspector1 = new JacksonAnnotationIntrospector(); mapper.setAnnotationIntrospectors(introspector, introspector1); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); //String jsonString = mapper.writeValueAsString(syncDownObjects); //JSONObject jsonobject = (JSONObject) new JSONParser().parse(jsonString); //gzip.write(jsonobject.toString().getBytes("8859_1")); //gzip.write(jsonobject.toString().getBytes("UTF-8")); gzip.write(mapper.writeValueAsBytes(syncDownObjects)); gzip.close(); } catch (IOException ex) { ex.printStackTrace(); } //catch (ParseException ex) { // ex.printStackTrace(); // } System.out.println("======================= count : " + count); return out.toByteArray(); }