com.fasterxml.jackson.databind.ObjectWriter Java Examples
The following examples show how to use
com.fasterxml.jackson.databind.ObjectWriter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObjectReaderIT.java From pinpoint with Apache License 2.0 | 6 votes |
@Test public void testWriteValue() throws Exception { __POJO pojo = new __POJO(); pojo.setName("Jackson"); ObjectWriter writer = mapper.writer(); String jsonStr = writer.writeValueAsString(pojo); byte[] jsonByte = writer.writeValueAsBytes(pojo); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); Method writeval1 = ObjectWriter.class.getMethod("writeValueAsString", Object.class); Method writeval2 = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class); verifier.verifyTrace(event("JACKSON", writeval1, annotation("jackson.json.length", jsonStr.length()))); verifier.verifyTrace(event("JACKSON", writeval2, annotation("jackson.json.length", jsonByte.length))); verifier.verifyTraceCount(0); }
Example #2
Source File: BlogPostResource.java From angular-rest-springsecurity with Apache License 2.0 | 6 votes |
@GET @Produces(MediaType.APPLICATION_JSON) public String list() throws IOException { this.logger.info("list()"); ObjectWriter viewWriter; if (this.isAdmin()) { viewWriter = this.mapper.writerWithView(JsonViews.Admin.class); } else { viewWriter = this.mapper.writerWithView(JsonViews.User.class); } List<BlogPost> allEntries = this.blogPostDao.findAll(); return viewWriter.writeValueAsString(allEntries); }
Example #3
Source File: SqlMetadataAdapterTest.java From syndesis with Apache License 2.0 | 6 votes |
@Test public void adaptForSqlUpdateNoParamTest() throws IOException { CamelContext camelContext = new DefaultCamelContext(); SqlConnectorMetaDataExtension ext = new SqlConnectorMetaDataExtension(camelContext); Map<String,Object> parameters = new HashMap<>(); for (final String name: PROPS.stringPropertyNames()) { parameters.put(name.substring(name.indexOf('.') + 1), PROPS.getProperty(name)); } parameters.put("query", "INSERT INTO NAME (FIRSTNAME, LASTNAME) VALUES ('Sheldon', 'Cooper')"); Optional<MetaData> metadata = ext.meta(parameters); SqlMetadataRetrieval adapter = new SqlMetadataRetrieval(); SyndesisMetadata syndesisMetaData2 = adapter.adapt(camelContext, "sql", "sql-connector", parameters, metadata.get()); String expectedMetadata = IOUtils.toString(this.getClass().getResource("/sql/name_sql_update_no_param_metadata.json"), StandardCharsets.UTF_8).trim(); ObjectWriter writer = JsonUtils.writer(); String actualMetadata = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData2); assertThatJson(actualMetadata).isEqualTo(expectedMetadata); }
Example #4
Source File: NeptuneExportService.java From amazon-neptune-tools with Apache License 2.0 | 6 votes |
private void uploadCompletionFileToS3(TransferManager transferManager, File directory, S3ObjectInfo outputS3ObjectInfo) throws IOException { if (!completionFileS3Path.isEmpty()) { File completionFile = new File(TEMP_PATH, directory.getName() + ".json"); ObjectNode neptuneExportNode = JsonNodeFactory.instance.objectNode(); neptuneExportNode.put("output", outputS3ObjectInfo.toString()); completionFilePayload.set("neptuneExport", neptuneExportNode); try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(completionFile), UTF_8))) { ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter(); writer.write(objectWriter.writeValueAsString(completionFilePayload)); } S3ObjectInfo completionFileS3ObjectInfo = new S3ObjectInfo(completionFileS3Path).withNewKeySuffix(completionFile.getName()); Upload upload = transferManager.upload(completionFileS3ObjectInfo.bucket(), completionFileS3ObjectInfo.key(), completionFile); try { upload.waitForUploadResult(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.log(e.getMessage()); } } }
Example #5
Source File: UtilitiesTestBase.java From hudi with Apache License 2.0 | 6 votes |
/** * Converts the json records into CSV format and writes to a file. * * @param hasHeader whether the CSV file should have a header line. * @param sep the column separator to use. * @param lines the records in JSON format. * @param fs {@link FileSystem} instance. * @param targetPath File path. * @throws IOException */ public static void saveCsvToDFS( boolean hasHeader, char sep, String[] lines, FileSystem fs, String targetPath) throws IOException { Builder csvSchemaBuilder = CsvSchema.builder(); ArrayNode arrayNode = mapper.createArrayNode(); Arrays.stream(lines).forEachOrdered( line -> { try { arrayNode.add(mapper.readValue(line, ObjectNode.class)); } catch (IOException e) { throw new HoodieIOException( "Error converting json records into CSV format: " + e.getMessage()); } }); arrayNode.get(0).fieldNames().forEachRemaining(csvSchemaBuilder::addColumn); ObjectWriter csvObjWriter = new CsvMapper() .writerFor(JsonNode.class) .with(csvSchemaBuilder.setUseHeader(hasHeader).setColumnSeparator(sep).build()); PrintStream os = new PrintStream(fs.create(new Path(targetPath), true)); csvObjWriter.writeValue(os, arrayNode); os.flush(); os.close(); }
Example #6
Source File: SyncClient.java From floodlight_with_topoguard with Apache License 2.0 | 6 votes |
@Override public boolean execute(String[] tokens, String line) throws Exception { if (tokens.length < 2) { err.println("Usage: " + syntaxString()); return false; } if (!checkStoreSettings()) return false; StringReader sr = new StringReader(line); while (sr.read() != ' '); JsonParser jp = mjf.createJsonParser(sr); JsonNode keyNode = validateJson(jp); if (keyNode == null) return false; ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter(); out.println("Deleting Key:"); out.println(writer.writeValueAsString(keyNode)); out.println(""); storeClient.delete(keyNode); out.println("Success"); return false; }
Example #7
Source File: JacksonRepresentationImpl.java From ontopia with Apache License 2.0 | 6 votes |
@Override protected ObjectWriter createObjectWriter() { ObjectWriter writer = super.createObjectWriter(); for (SerializationFeature feature : SerializationFeature.values()) { boolean hasDefault = DEFAULT_SERIALIZATION_FEATURES.contains(feature); Parameter parameter = ContextUtils.getParameter(ContextUtils.getCurrentApplicationContext(), SERIALIZATION_FEATURE + feature.name()); if ((parameter != null) || hasDefault) { if (ContextUtils.getParameterAsBoolean(parameter, feature.enabledByDefault() || hasDefault)) { writer = writer.with(feature); } else { writer = writer.without(feature); } } } return writer; }
Example #8
Source File: PropertyFilteringMessageBodyWriter.java From jackson-jaxrs-propertyfiltering with Apache License 2.0 | 6 votes |
@Override public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream os) throws IOException { PropertyFiltering annotation = findPropertyFiltering(annotations); PropertyFilter propertyFilter = PropertyFilterBuilder.newBuilder(uriInfo).forAnnotation(annotation); if (!propertyFilter.hasFilters()) { write(o, type, genericType, annotations, mediaType, httpHeaders, os); return; } Timer timer = getTimer(); Timer.Context context = timer.time(); try { ObjectMapper mapper = getJsonProvider().locateMapper(type, mediaType); ObjectWriter writer = JsonEndpointConfig.forWriting(mapper.writer(), annotations, null).getWriter(); writeValue(writer, propertyFilter, o, os); } finally { context.stop(); } }
Example #9
Source File: TripleCryptOutputStream.java From cyberduck with GNU General Public License v3.0 | 6 votes |
@Override public void close() throws IOException { try { final EncryptedDataContainer encrypted = cipher.doFinal(); super.write(encrypted.getContent()); final String tag = CryptoUtils.byteArrayToString(encrypted.getTag()); final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class); final FileKey fileKey = reader.readValue(status.getFilekey().array()); fileKey.setTag(tag); final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class); final ByteArrayOutputStream out = new ByteArrayOutputStream(); writer.writeValue(out, fileKey); status.setFilekey(ByteBuffer.wrap(out.toByteArray())); } catch(CryptoSystemException e) { throw new IOException(e); } finally { super.close(); } }
Example #10
Source File: FunqyLambdaBindingRecorder.java From quarkus with Apache License 2.0 | 6 votes |
public void chooseInvoker(FunqyConfig config) { // this is done at Runtime so that we can change it with an environment variable. if (config.export.isPresent()) { invoker = FunctionRecorder.registry.matchInvoker(config.export.get()); if (invoker == null) { throw new RuntimeException("quarkus.funqy.export does not match a function: " + config.export.get()); } } else if (FunctionRecorder.registry.invokers().size() == 0) { throw new RuntimeException("There are no functions to process lambda"); } else if (FunctionRecorder.registry.invokers().size() > 1) { throw new RuntimeException("Too many functions. You need to set quarkus.funqy.export"); } else { invoker = FunctionRecorder.registry.invokers().iterator().next(); } if (invoker.hasInput()) { reader = (ObjectReader) invoker.getBindingContext().get(ObjectReader.class.getName()); } if (invoker.hasOutput()) { writer = (ObjectWriter) invoker.getBindingContext().get(ObjectWriter.class.getName()); } }
Example #11
Source File: SqlMetadataAdapterTest.java From syndesis with Apache License 2.0 | 6 votes |
@Test public void adaptForSqlBatchUpdateTest() throws IOException { CamelContext camelContext = new DefaultCamelContext(); SqlConnectorMetaDataExtension ext = new SqlConnectorMetaDataExtension(camelContext); Map<String,Object> parameters = new HashMap<>(); for (final String name: PROPS.stringPropertyNames()) { parameters.put(name.substring(name.indexOf('.') + 1), PROPS.getProperty(name)); } parameters.put("query", "INSERT INTO NAME (FIRSTNAME, LASTNAME) VALUES (:#firstname, :#lastname)"); parameters.put("batch", true); Optional<MetaData> metadata = ext.meta(parameters); SqlMetadataRetrieval adapter = new SqlMetadataRetrieval(); SyndesisMetadata syndesisMetaData2 = adapter.adapt(camelContext, "sql", "sql-connector", parameters, metadata.get()); String expectedMetadata = IOUtils.toString(this.getClass().getResource("/sql/name_sql_batch_update_metadata.json"), StandardCharsets.UTF_8).trim(); ObjectWriter writer = JsonUtils.writer(); String actualMetadata = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData2); assertThatJson(actualMetadata).isEqualTo(expectedMetadata); }
Example #12
Source File: ElasticBaseTestQuery.java From dremio-oss with Apache License 2.0 | 6 votes |
public static void compareJson(String expected, String actual) throws IOException { if(ElasticsearchCluster.USE_EXTERNAL_ES5){ // ignore json comparison for now return; } ObjectMapper m = new ObjectMapper(); JsonNode expectedRootNode = m.readTree(expected); JsonNode actualRootNode = m.readTree(actual); if (!expectedRootNode.equals(actualRootNode)) { ObjectWriter writer = m.writerWithDefaultPrettyPrinter(); String message = String.format("Comparison between JSON values failed.\nExpected:\n%s\nActual:\n%s", expected, actual); // assertEquals gives a better diff assertEquals(message, writer.writeValueAsString(expectedRootNode), writer.writeValueAsString(actualRootNode)); throw new RuntimeException(message); } }
Example #13
Source File: LoadFlowResultSerializer.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
public static void write(LoadFlowResult result, Path jsonFile) { Objects.requireNonNull(result); Objects.requireNonNull(jsonFile); try (OutputStream os = Files.newOutputStream(jsonFile)) { ObjectMapper objectMapper = JsonUtil.createObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(LoadFlowResult.class, new LoadFlowResultSerializer()); objectMapper.registerModule(module); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); writer.writeValue(os, result); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example #14
Source File: SubscriptionsRepository.java From fiware-cepheus with GNU General Public License v2.0 | 5 votes |
/** * Save a subscription. * @param subscription * @throws SubscriptionPersistenceException */ public void saveSubscription(Subscription subscription) throws SubscriptionPersistenceException { try { //Mapping from model to database model ObjectWriter writer = mapper.writer(); String susbcribeContextString = writer.writeValueAsString(subscription.getSubscribeContext()); String expirationDate = subscription.getExpirationDate().toString(); //insert into database jdbcTemplate.update("insert into t_subscriptions(id,expirationDate,subscribeContext) values(?,?,?)", subscription.getSubscriptionId(), expirationDate, susbcribeContextString); } catch (Exception e) { throw new SubscriptionPersistenceException(e); } }
Example #15
Source File: RntbdResponseHeaders.java From azure-cosmosdb-java with MIT License | 5 votes |
@Override public String toString() { final ObjectWriter writer = RntbdObjectMapper.writer(); try { return writer.writeValueAsString(this); } catch (final JsonProcessingException error) { throw new CorruptedFrameException(error); } }
Example #16
Source File: JVMMetricsServlet.java From hermes with Apache License 2.0 | 5 votes |
private ObjectWriter getWriter(HttpServletRequest request) { final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); if (prettyPrint) { return mapper.writerWithDefaultPrettyPrinter(); } return mapper.writer(); }
Example #17
Source File: JacksonJsonLayoutTest.java From log4j2-elasticsearch with Apache License 2.0 | 5 votes |
@Override public ItemSource create(Object event, ObjectWriter objectWriter) { try { return new LayoutTestItemSource(objectWriter.writeValueAsString(event)); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; }
Example #18
Source File: SqlMetadataAdapterTest.java From syndesis with Apache License 2.0 | 5 votes |
@Test public void adaptForSqlStoredTest() throws IOException { CamelContext camelContext = new DefaultCamelContext(); SqlStoredConnectorMetaDataExtension ext = new SqlStoredConnectorMetaDataExtension(camelContext); Map<String,Object> parameters = new HashMap<>(); for (final String name: PROPS.stringPropertyNames()) { parameters.put(name.substring(name.indexOf(".")+1), PROPS.getProperty(name)); } Optional<MetaData> metadata = ext.meta(parameters); SqlMetadataRetrieval adapter = new SqlMetadataRetrieval(); SyndesisMetadata syndesisMetaData = adapter.adapt(camelContext, "sql", "sql-stored-connector", parameters, metadata.get()); ObjectWriter writer = JsonUtils.writer(); String expectedListOfProcedures = IOUtils.toString(this.getClass().getResource("/sql/stored_procedure_list.json"), StandardCharsets.UTF_8).trim(); String actualListOfProcedures = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData); assertThatJson(actualListOfProcedures).isEqualTo(expectedListOfProcedures); parameters.put(SqlMetadataRetrieval.PATTERN, SqlMetadataRetrieval.FROM_PATTERN); String expectedListOfStartProcedures = IOUtils.toString(this.getClass().getResource("/sql/stored_procedure_list.json"), StandardCharsets.UTF_8).trim(); String actualListOfStartProcedures = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData); assertThatJson(actualListOfStartProcedures).isEqualTo(expectedListOfStartProcedures); parameters.put("procedureName", "DEMO_ADD"); SyndesisMetadata syndesisMetaData2 = adapter.adapt(camelContext, "sql", "sql-stored-connector", parameters, metadata.get()); String expectedMetadata = IOUtils.toString(this.getClass().getResource("/sql/demo_add_metadata.json"), StandardCharsets.UTF_8).trim(); String actualMetadata = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData2); assertThatJson(actualMetadata).isEqualTo(expectedMetadata); }
Example #19
Source File: CharSeqTest.java From vavr-jackson with Apache License 2.0 | 5 votes |
@Test void test1() throws IOException { ObjectWriter writer = mapper().writer(); CharSeq src = CharSeq.of("abc"); String json = writer.writeValueAsString(src); Assertions.assertEquals("\"abc\"", json); CharSeq dst = mapper().readValue(json, CharSeq.class); Assertions.assertEquals(src, dst); }
Example #20
Source File: RepositoryAuditor.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
private Map<String, Object> createFullAttributes(final Repository repository) { boolean baseUrlAbsent = !BaseUrlHolder.isSet(); try { if (baseUrlAbsent) { BaseUrlHolder.set(""); // use empty base URL placeholder during conversion to avoid log-spam } AbstractApiRepository apiObject = convert(repository); ObjectWriter writer = mapper.writerFor(apiObject.getClass()); String json = writer.writeValueAsString(apiObject); return mapper.readerFor(new TypeReference<Map<String, Object>>() { }).readValue(json); } catch (Exception e) { log.error("Failed to convert repo object falling back to simple", e); return createSimple(repository); } finally { if (baseUrlAbsent) { BaseUrlHolder.unset(); } } }
Example #21
Source File: RestClientCall.java From ods-provisioning-app with Apache License 2.0 | 5 votes |
private RequestBody prepareBody(Object body) throws JsonProcessingException { RequestBody requestBody = null; String json = ""; if (body == null) { logger.debug("The request has no body"); } else if (body instanceof String) { json = (String) body; logger.debug("Passed String rest object: [{}]", json); requestBody = RequestBody.create(this.mediaType, json); } else if (body instanceof Map) { Map<String, String> paramMap = ((Map) body); logger.debug("Passed parameter map, keys: [{}]", paramMap.keySet()); FormBody.Builder form = new FormBody.Builder(); for (Map.Entry<String, String> param : paramMap.entrySet()) { form.add(param.getKey(), param.getValue()); } logger.debug("Created form {}", json); requestBody = form.build(); } else { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); json = ow.writeValueAsString(body); logger.debug("Converted rest object: {}", json); requestBody = RequestBody.create(this.mediaType, json); } return requestBody; }
Example #22
Source File: SaveProcessDefinitionInfoCmd.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
public Void execute(CommandContext commandContext) { if (processDefinitionId == null) { throw new ActivitiIllegalArgumentException("process definition id is null"); } if (infoNode == null) { throw new ActivitiIllegalArgumentException("process definition info node is null"); } ProcessDefinitionInfoEntityManager definitionInfoEntityManager = commandContext.getProcessDefinitionInfoEntityManager(); ProcessDefinitionInfoEntity definitionInfoEntity = definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId); if (definitionInfoEntity == null) { definitionInfoEntity = definitionInfoEntityManager.create(); definitionInfoEntity.setProcessDefinitionId(processDefinitionId); commandContext.getProcessDefinitionInfoEntityManager().insertProcessDefinitionInfo(definitionInfoEntity); } if (infoNode != null) { try { ObjectWriter writer = commandContext.getProcessEngineConfiguration().getObjectMapper().writer(); commandContext.getProcessDefinitionInfoEntityManager().updateInfoJson(definitionInfoEntity.getId(), writer.writeValueAsBytes(infoNode)); } catch (Exception e) { throw new ActivitiException("Unable to serialize info node " + infoNode); } } return null; }
Example #23
Source File: AbstractJacksonLayout.java From logging-log4j2 with Apache License 2.0 | 5 votes |
protected AbstractJacksonLayout(final Configuration config, final ObjectWriter objectWriter, final Charset charset, final boolean compact, final boolean complete, final boolean eventEol, final Serializer headerSerializer, final Serializer footerSerializer, final boolean includeNullDelimiter, final KeyValuePair[] additionalFields) { this(config, objectWriter, charset, compact, complete, eventEol, null, headerSerializer, footerSerializer, includeNullDelimiter, additionalFields); }
Example #24
Source File: AbstractJacksonLayout.java From logging-log4j2 with Apache License 2.0 | 5 votes |
protected AbstractJacksonLayout(final Configuration config, final ObjectWriter objectWriter, final Charset charset, final boolean compact, final boolean complete, final boolean eventEol, final String endOfLine, final Serializer headerSerializer, final Serializer footerSerializer, final boolean includeNullDelimiter, final KeyValuePair[] additionalFields) { super(config, charset, headerSerializer, footerSerializer); this.objectWriter = objectWriter; this.compact = compact; this.complete = complete; this.eol = endOfLine != null ? endOfLine : compact && !eventEol ? COMPACT_EOL : DEFAULT_EOL; this.includeNullDelimiter = includeNullDelimiter; this.additionalFields = prepareAdditionalFields(config, additionalFields); }
Example #25
Source File: DocumentTest.java From crnk-framework with Apache License 2.0 | 5 votes |
@Test public void checkJsonApiServerInfoNotSerializedIfNull() throws JsonProcessingException { Document document = new Document(); document.setJsonapi(null); Assert.assertNull(document.getJsonapi()); ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.writerFor(Document.class); String json = writer.writeValueAsString(document); Assert.assertEquals("{}", json); }
Example #26
Source File: ProtobufMapperWrapper.java From caravan with Apache License 2.0 | 5 votes |
protected ObjectWriter getWriter(Class<?> clazz) { ObjectWriter writer = _classObjectWriterMap.get(clazz); if (writer == null) { ProtobufSchema schema = getSchema(clazz); writer = _mapper.writerFor(clazz).with(schema); _classObjectWriterMap.put(clazz, writer); } return writer; }
Example #27
Source File: JsonChecker.java From immutables with Apache License 2.0 | 5 votes |
private void assertSameJson(JsonNode expected) throws JsonProcessingException { Objects.requireNonNull(expected, "expected"); if (!actual.equals(expected)) { ObjectWriter writer = MAPPER.writerWithDefaultPrettyPrinter(); String expectedPretty = writer.writeValueAsString(expected); String actualPretty = writer.writeValueAsString(actual); Assertions.assertEquals(expectedPretty, actualPretty); } }
Example #28
Source File: SaveProcessDefinitionInfoCmd.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public Void execute(CommandContext commandContext) { if (processDefinitionId == null) { throw new ActivitiIllegalArgumentException("process definition id is null"); } if (infoNode == null) { throw new ActivitiIllegalArgumentException("process definition info node is null"); } ProcessDefinitionInfoEntityManager definitionInfoEntityManager = commandContext.getProcessDefinitionInfoEntityManager(); ProcessDefinitionInfoEntity definitionInfoEntity = definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId); if (definitionInfoEntity == null) { definitionInfoEntity = new ProcessDefinitionInfoEntity(); definitionInfoEntity.setProcessDefinitionId(processDefinitionId); commandContext.getProcessDefinitionInfoEntityManager().insertProcessDefinitionInfo(definitionInfoEntity); } else { commandContext.getProcessDefinitionInfoEntityManager().updateProcessDefinitionInfo(definitionInfoEntity); } try { ObjectWriter writer = commandContext.getProcessEngineConfiguration().getObjectMapper().writer(); commandContext.getProcessDefinitionInfoEntityManager().updateInfoJson(definitionInfoEntity.getId(), writer.writeValueAsBytes(infoNode)); } catch (Exception e) { throw new ActivitiException("Unable to serialize info node " + infoNode, e); } return null; }
Example #29
Source File: MonetaryAmountSerializerTest.java From jackson-datatype-money with MIT License | 5 votes |
@ParameterizedTest @MethodSource("amounts") void shouldSerializeWithCustomName(final MonetaryAmount amount) throws IOException { final ObjectMapper unit = unit(module().withDefaultFormatting() .withAmountFieldName("value") .withCurrencyFieldName("unit") .withFormattedFieldName("pretty")); final String expected = "{\"value\":29.95,\"unit\":\"EUR\",\"pretty\":\"29,95 EUR\"}"; final ObjectWriter writer = unit.writer().with(Locale.GERMANY); final String actual = writer.writeValueAsString(amount); assertThat(actual, is(expected)); }
Example #30
Source File: SaveProcessDefinitionInfoCmd.java From flowable-engine with Apache License 2.0 | 5 votes |
@Override public Void execute(CommandContext commandContext) { if (processDefinitionId == null) { throw new FlowableIllegalArgumentException("process definition id is null"); } if (infoNode == null) { throw new FlowableIllegalArgumentException("process definition info node is null"); } ProcessDefinitionInfoEntityManager definitionInfoEntityManager = CommandContextUtil.getProcessDefinitionInfoEntityManager(commandContext); ProcessDefinitionInfoEntity definitionInfoEntity = definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId); if (definitionInfoEntity == null) { definitionInfoEntity = definitionInfoEntityManager.create(); definitionInfoEntity.setProcessDefinitionId(processDefinitionId); CommandContextUtil.getProcessDefinitionInfoEntityManager().insertProcessDefinitionInfo(definitionInfoEntity); } try { ObjectWriter writer = CommandContextUtil.getProcessEngineConfiguration(commandContext).getObjectMapper().writer(); CommandContextUtil.getProcessDefinitionInfoEntityManager().updateInfoJson(definitionInfoEntity.getId(), writer.writeValueAsBytes(infoNode)); } catch (Exception e) { throw new FlowableException("Unable to serialize info node " + infoNode, e); } return null; }