List of usage examples for com.fasterxml.jackson.core JsonFactory createGenerator
public JsonGenerator createGenerator(Writer out) throws IOException
From source file:org.eclipse.winery.repository.resources.servicetemplates.plans.PlansResourceData.java
/** * Data object for the JSP//from www . jav a 2s . co m * * @param plans the plans this resource manages */ public PlansResourceData(List<TPlan> plans) { if (plans.isEmpty()) { this.embeddedPlansTableData = "[]"; this.linkedPlansTableData = "[]"; return; } JsonFactory jsonFactory = new JsonFactory(); StringWriter embeddedPlansTableDataSW = new StringWriter(); StringWriter linkedPlansTableDataSW = new StringWriter(); try { JsonGenerator jGeneratorEmbedded = jsonFactory.createGenerator(embeddedPlansTableDataSW); JsonGenerator jGeneratorLinked = jsonFactory.createGenerator(linkedPlansTableDataSW); jGeneratorEmbedded.writeStartArray(); jGeneratorLinked.writeStartArray(); for (TPlan plan : plans) { String name = plan.getName(); if (name == null) { // name defaults to id name = plan.getId(); } String type = PlanTypesManager.INSTANCE.getShortName(plan.getPlanType()); String language = PlanLanguagesManager.INSTANCE.getShortName(plan.getPlanLanguage()); PlanModelReference planModelReference = plan.getPlanModelReference(); String reference = planModelReference != null ? planModelReference.getReference() : null; JsonGenerator gen; boolean writeReference; if (reference == null) { gen = jGeneratorEmbedded; writeReference = false; } else if (reference.startsWith("../")) { gen = jGeneratorEmbedded; writeReference = false; } else { gen = jGeneratorLinked; writeReference = true; } gen.writeStartArray(); gen.writeString(plan.getId()); gen.writeString(""); // precondition gen.writeString(name); gen.writeString(type); gen.writeString(language); if (writeReference) { gen.writeString(reference); } gen.writeEndArray(); } jGeneratorEmbedded.writeEndArray(); jGeneratorLinked.writeEndArray(); jGeneratorEmbedded.close(); embeddedPlansTableDataSW.close(); jGeneratorLinked.close(); linkedPlansTableDataSW.close(); } catch (JsonGenerationException e) { PlansResourceData.LOGGER.error(e.getMessage(), e); this.embeddedPlansTableData = "[]"; this.linkedPlansTableData = "[]"; return; } catch (IOException e) { PlansResourceData.LOGGER.error("", e); this.embeddedPlansTableData = "[]"; this.linkedPlansTableData = "[]"; return; } this.embeddedPlansTableData = embeddedPlansTableDataSW.toString(); this.linkedPlansTableData = linkedPlansTableDataSW.toString(); }
From source file:TDS.Shared.Messages.MessageJson.java
public String create() throws ReturnStatusException { StringWriter sw = new StringWriter(); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jsonWriter;/*www.j ava2 s.c o m*/ try { if (_messageSystem == null) return "{}"; jsonWriter = jsonFactory.createGenerator(sw); jsonWriter.writeStartObject(); jsonWriter.writeStringField("c_l", _language); // "c_l": _language jsonWriter.writeFieldName("c_a"); // "c_a" : jsonWriter.writeStartArray(); // [ // get all the message contexts across all the context types List<MessageContext> messageContexts = new ArrayList<MessageContext>(); for (MessageContextType contextType : _messageSystem.getContextTypes()) { messageContexts.addAll(contextType.getContexts()); } for (MessageContext messageContext : messageContexts) { writeContextElement(messageContext, jsonWriter); } jsonWriter.writeEndArray(); // ] jsonWriter.writeEndObject(); // } jsonWriter.close(); sw.close(); } catch (IOException e) { ReturnStatus rs = new ReturnStatus("failed", "Serialization failed: " + e.getMessage()); throw new ReturnStatusException(rs); } return sw.getBuffer().toString(); }
From source file:com.ntsync.shared.ContactGroup.java
/** * Serialize this ContactGroup for transporting to a server * /*from w ww . j av a2 s. co m*/ * @param secret * @param pwdSaltBase64 * @return null if serializing failed. */ public byte[] toDTO(Key secret, String pwdSaltBase64) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(DEFAULT_BYTEARRAY_SIZE); AEADBlockCipher ecipher = CryptoHelper.getCipher(); byte[] iv = new byte[CryptoHelper.IV_LEN]; SecureRandom random = new SecureRandom(); StringBuilder hashValue = new StringBuilder(); hashValue.append(pwdSaltBase64); hashValue.append(title); out.write(GroupConstants.ROWID); byte[] rowId = String.valueOf(rawId).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME); SyncDataHelper.writeInt(out, rowId.length); out.write(rowId); JsonFactory json = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator g = json.createGenerator(writer); g.writeStartObject(); writeField(g, GroupConstants.TITLE, title); writeField(g, GroupConstants.NOTES, notes); g.writeEndObject(); g.close(); String textData = writer.toString(); CryptoHelper.writeValue(secret, out, ecipher, iv, random, GroupConstants.TEXTDATA, textData); if (lastModified != null) { writeRawValue(out, GroupConstants.MODIFIED, String.valueOf(lastModified.getTime()).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } if (deleted) { writeRawValue(out, GroupConstants.DELETED, "1".getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } if (sourceId != null) { writeRawValue(out, GroupConstants.SERVERROW_ID, sourceId.getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(hashValue.toString().getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); byte[] hash = md.digest(); writeRawValue(out, GroupConstants.HASH, hash); return out.toByteArray(); } catch (final Exception ex) { LOG.error("Error converting ContactGroup to ByteStream: " + ex.toString(), ex); } return null; }
From source file:org.eclipse.winery.repository.resources.AbstractComponentsResource.java
/** * Used by org.eclipse.winery.repository.repository.client and by the * artifactcreationdialog.tag. Especially the "name" field is used there at * the UI// ww w . ja v a 2 s. co m * * @return A list of all ids of all instances of this component type. If the * "name" attribute is required, that name is used as id <br /> * Format: * <code>[({"namespace": "<namespace>", "id": "<id>"},)* ]</code>. A * <code>name<code> field is added if the model allows an additional name attribute */ @GET @Produces(MediaType.APPLICATION_JSON) public String getListOfAllIds() { Class<? extends TOSCAComponentId> idClass = Utils.getComponentIdClassForComponentContainer(this.getClass()); boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass); SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = Repository.INSTANCE .getAllTOSCAComponentIds(idClass); JsonFactory jsonFactory = new JsonFactory(); StringWriter sw = new StringWriter(); try { JsonGenerator jg = jsonFactory.createGenerator(sw); // We produce org.eclipse.winery.repository.client.WineryRepositoryClient.NamespaceAndId by hand here // Refactoring could move this class to common and fill it here jg.writeStartArray(); for (TOSCAComponentId id : allTOSCAcomponentIds) { jg.writeStartObject(); jg.writeStringField("namespace", id.getNamespace().getDecoded()); jg.writeStringField("id", id.getXmlId().getDecoded()); if (supportsNameAttribute) { AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource .getComponentInstaceResource(id); String name = ((IHasName) componentInstaceResource).getName(); jg.writeStringField("name", name); } jg.writeEndObject(); } jg.writeEndArray(); jg.close(); } catch (Exception e) { AbstractComponentsResource.logger.error(e.getMessage(), e); return "[]"; } return sw.toString(); }
From source file:org.eclipse.winery.repository.resources.servicetemplates.plans.PlansResource.java
@POST @RestDoc(methodDescription = "<p>Linked plans are currently not supported. Existing plans with the same id are overwritten</p> <p>@return JSON with .tableData: Array with row data for dataTable</p>") @Consumes({ MediaType.MULTIPART_FORM_DATA }) @Produces(MediaType.APPLICATION_JSON)/*from w w w. j a v a2 s .c o m*/ // the supertype consumes JSON and XML at org.eclipse.winery.repository.resources._support.collections.EntityCollectionResource.addNewElement(EntityT) // @formatter:off public Response onPost(@FormDataParam("planName") String name, @FormDataParam("planType") String type, @FormDataParam("planLanguage") @RestDocParam(description = "the plan language (e..g, BPMN or BPEL). Full URL.") String language, @FormDataParam("file") @RestDocParam(description = "(optional in the case of BPMN4TOSCA) file containing the plan.") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("file") FormDataBodyPart body) { // @formatter:on if (StringUtils.isEmpty(name)) { return Response.status(Status.BAD_REQUEST).entity("planName must be given").build(); } if (StringUtils.isEmpty(type)) { return Response.status(Status.BAD_REQUEST).entity("planType must be given").build(); } if (StringUtils.isEmpty(language)) { return Response.status(Status.BAD_REQUEST).entity("planLanguage must be given").build(); } boolean bpmn4toscaMode = org.eclipse.winery.common.constants.Namespaces.URI_BPMN4TOSCA_20.equals(language); if (!bpmn4toscaMode) { if (uploadedInputStream == null) { return Response.status(Status.BAD_REQUEST).entity("file must be given").build(); } } // A plan carries both a name and an ID // To be user-friendly, we create the ID based on the name // the drawback is, that we do not allow two plans with the same name // during creation, but allow renaming plans to the same name (as we do // not allow ID renaming) String xmlId = Utils.createXMLidAsString(name); // BEGIN: Store plan file // Determine Id PlansId plansId = new PlansId((ServiceTemplateId) ((ServiceTemplateResource) this.res).getId()); PlanId planId = new PlanId(plansId, new XMLId(xmlId, false)); // Ensure overwriting if (Repository.INSTANCE.exists(planId)) { try { Repository.INSTANCE.forceDelete(planId); // Quick hack to remove the deleted plan from the plans element ((ServiceTemplateResource) this.res).synchronizeReferences(); } catch (IOException e) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } } String fileName; if (bpmn4toscaMode) { fileName = xmlId + Constants.SUFFIX_BPMN4TOSCA; RepositoryFileReference ref = new RepositoryFileReference(planId, fileName); try { Repository.INSTANCE.putContentToFile(ref, "{}", MediaType.APPLICATION_JSON_TYPE); } catch (IOException e1) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Could not create empty plan. " + e1.getMessage()).build(); } } else { // We use the filename also as local file name. Alternatively, we could use the xml id // With URL encoding, this should not be an issue fileName = Util.URLencode(fileDetail.getFileName()); // Really store it RepositoryFileReference ref = new RepositoryFileReference(planId, fileName); try { Repository.INSTANCE.putContentToFile(ref, uploadedInputStream, body.getMediaType()); } catch (IOException e1) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Could not store plan. " + e1.getMessage()).build(); } } // END: Store plan file TPlan plan = new TPlan(); plan.setId(xmlId); plan.setName(name); plan.setPlanType(type); plan.setPlanLanguage(language); PlansResource.setPlanModelReference(plan, planId, fileName); this.list.add(plan); // prepare result JsonFactory jsonFactory = new JsonFactory(); StringWriter sw = new StringWriter(); try { JsonGenerator jGenerator = jsonFactory.createGenerator(sw); jGenerator.writeStartObject(); jGenerator.writeFieldName("tableData"); jGenerator.writeStartArray(); jGenerator.writeString(xmlId); jGenerator.writeString(""); // precondition jGenerator.writeString(name); jGenerator.writeString(PlanTypesManager.INSTANCE.getShortName(type)); jGenerator.writeString(PlanLanguagesManager.INSTANCE.getShortName(language)); jGenerator.writeEndArray(); jGenerator.writeEndObject(); jGenerator.close(); sw.close(); } catch (JsonGenerationException e) { PlansResource.logger.error(e.getMessage(), e); return Response.serverError().build(); } catch (IOException e) { PlansResource.logger.error(e.getMessage(), e); return Response.serverError().build(); } Response res = BackendUtils.persist(this.res); if (res.getStatus() == 204) { // everything OK, return created return Response.created(Utils.createURI(Util.URLencode(xmlId))).entity(sw.toString()).build(); } else { return res; } }
From source file:tds.student.web.backing.TestShellScriptsBacking.java
private void addTestConfig() throws JsonGenerationException, IOException { // get test configp[ TestConfig testConfig = _testOpportunity.getTestConfig(); // get json config StringWriter sw = new StringWriter(); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator writer = jsonFactory.createGenerator(sw); // create test config json writer.writeStartObject();// { // writer.writeObjectField ("type", "object"); // properties writer.writeStringField("urlBase", UrlHelper.getBase()); writer.writeNumberField("reviewPage", getViewPageNumber()); writer.writeBooleanField("hasAudio", _testProps.getRequirements().isHasAudio()); writer.writeBooleanField("autoMute", shouldAutoMuteVolume()); // test config (DB) writer.writeStringField("testName", _testProps.getDisplayName()); writer.writeNumberField("testLength", testConfig.getTestLength()); writer.writeNumberField("startPosition", testConfig.getStartPosition()); writer.writeNumberField("contentLoadTimeout", testConfig.getContentLoadTimeout()); writer.writeNumberField("requestInterfaceTimeout", testConfig.getRequestInterfaceTimeout()); writer.writeNumberField("oppRestartMins", testConfig.getOppRestartMins()); writer.writeNumberField("interfaceTimeout", testConfig.getInterfaceTimeout()); // app settings (DB or settings.config) writer.writeNumberField("interfaceTimeoutDialog", TestShellSettings.getTimeoutDialog().getValue()); writer.writeNumberField("autoSaveInterval", TestShellSettings.getAutoSaveInterval().getValue()); writer.writeNumberField("forbiddenAppsInterval", TestShellSettings.getForbiddenAppsInterval().getValue()); writer.writeBooleanField("disableSaveWhenInactive", TestShellSettings.isDisableSaveWhenInactive().getValue()); writer.writeBooleanField("disableSaveWhenForbiddenApps", TestShellSettings.isDisableSaveWhenForbiddenApps().getValue()); writer.writeBooleanField("allowSkipAudio", TestShellSettings.isAllowSkipAudio().getValue()); writer.writeBooleanField("showSegmentLabels", TestShellSettings.isShowSegmentLabels().getValue()); writer.writeNumberField("audioTimeout", TestShellSettings.getAudioTimeout().getValue()); writer.writeBooleanField("enableLogging", TestShellSettings.isEnableLogging().getValue()); writer.writeEndObject(); // } writer.close();/*from w w w . ja va2 s .co m*/ // write out javascript StringBuilder javascript = new StringBuilder(); javascript.append("var tdsTestConfig = "); javascript.append(sw.toString()); javascript.append("; "); this.getClientScript().addToJsCode(javascript.toString()); }
From source file:com.cinnober.msgcodec.json.JsonCodec.java
@Override public void encode(Object group, OutputStream out) throws IOException { if (group == null) { out.write(NULL_BYTES);//from www.ja va 2s . c om } else { JsonFactory f = new JsonFactory(); JsonGenerator g = f.createGenerator(out); dynamicGroupHandler.writeValue(group, g); g.flush(); } }
From source file:com.cinnober.msgcodec.json.JsonCodec.java
@Override public void encode(Object group, ByteSink out) throws IOException { if (group == null) { out.write(NULL_BYTES);//from w w w. j ava 2 s . c o m } else { JsonFactory f = new JsonFactory(); JsonGenerator g = f.createGenerator(new ByteSinkOutputStream(out)); dynamicGroupHandler.writeValue(group, g); g.flush(); } }
From source file:org.canova.api.conf.Configuration.java
/** * Writes out all the parameters and their properties (final and resource) to * the given {@link Writer}/*ww w. jav a 2s . c om*/ * The format of the output would be * { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2, * key2.isFinal,key2.resource}... ] } * It does not output the parameters of the configuration object which is * loaded from an input stream. * @param out the Writer to write to * @throws IOException */ public static void dumpConfiguration(Configuration conf, Writer out) throws IOException { Configuration config = new Configuration(conf, true); config.reloadConfiguration(); JsonFactory dumpFactory = new JsonFactory(); JsonGenerator dumpGenerator = dumpFactory.createGenerator(out); dumpGenerator.writeStartObject(); dumpGenerator.writeFieldName("properties"); dumpGenerator.writeStartArray(); dumpGenerator.flush(); for (Map.Entry<Object, Object> item : config.getProps().entrySet()) { dumpGenerator.writeStartObject(); dumpGenerator.writeStringField("key", (String) item.getKey()); dumpGenerator.writeStringField("value", config.get((String) item.getKey())); dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey())); dumpGenerator.writeStringField("resource", config.updatingResource.get(item.getKey())); dumpGenerator.writeEndObject(); } dumpGenerator.writeEndArray(); dumpGenerator.writeEndObject(); dumpGenerator.flush(); }