// Writes wiki example JSON in a streaming fashion private void writeWikiExample(OutputStream os) { try (JsonGenerator gene = Json.createGenerator(os)) { gene.writeStartObject() .write("firstName", "John") .write("lastName", "Smith") .write("age", 25) .writeStartObject("address") .write("streetAddress", "21 2nd Street") .write("city", "New York") .write("state", "NY") .write("postalCode", "10021") .writeEnd() .writeStartArray("phoneNumber") .writeStartObject() .write("type", "home") .write("number", "212 555-1234") .writeEnd() .writeStartObject() .write("type", "fax") .write("number", "646 555-4567") .writeEnd() .writeEnd() .writeEnd(); } }
private void writeDate(JsonGenerator jg, String key, Date date) { if (date != null) { String formattedDate = getFormattedDate(date); jg.write(key, formattedDate); } else { jg.write(key, JsonValue.NULL); } }
private static void writeMatrix(Matrix4d matrix, JsonGenerator jg) { jg.writeStartArray("matrix"); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { jg.write(matrix.getElement(i, j)); } } jg.writeEnd(); }
@GET @Path("version") @Produces(MediaType.APPLICATION_JSON) public String getVersion() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = Json.createGenerator(baos); gen.writeStartObject().write("version", Constants.API_VERSION).writeEnd(); gen.close(); return baos.toString(); }
@POST @Path("session") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public String login(@Context HttpServletRequest request, @FormParam("json") String jsonString) throws IcatException { logger.debug(jsonString); if (jsonString == null) { throw new IcatException(IcatExceptionType.BAD_PARAMETER, "json must not be null"); } String plugin = null; Map<String, String> credentials = new HashMap<>(); try (JsonParser parser = Json.createParser(new ByteArrayInputStream(jsonString.getBytes()))) { String key = null; boolean inCredentials = false; while (parser.hasNext()) { JsonParser.Event event = parser.next(); if (event == Event.KEY_NAME) { key = parser.getString(); } else if (event == Event.VALUE_STRING) { if (inCredentials) { credentials.put(key, parser.getString()); } else { if (key.equals("plugin")) { plugin = parser.getString(); } } } else if (event == Event.START_ARRAY && key.equals("credentials")) { inCredentials = true; } else if (event == Event.END_ARRAY) { inCredentials = false; } } } Authenticator authenticator = authPlugins.get(plugin); if (authenticator == null) { throw new IcatException( IcatException.IcatExceptionType.SESSION, "Authenticator mnemonic " + plugin + " not recognised"); } logger.debug("Using " + plugin + " to authenticate"); String userName = authenticator.authenticate(credentials, request.getRemoteAddr()).getUserName(); String sessionId = beanManager.login(userName, lifetimeMinutes, manager, userTransaction); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = Json.createGenerator(baos); gen.writeStartObject().write("sessionId", sessionId).writeEnd(); gen.close(); return baos.toString(); }
@Override public String encode(JoinMessage joinMessage) throws EncodeException { StringWriter swriter = new StringWriter(); try (JsonGenerator jsonGen = Json.createGenerator(swriter)) { jsonGen .writeStartObject() .write("type", "join") .write("name", joinMessage.getName()) .writeEnd(); } return swriter.toString(); }
/** * Converts query tags list to JSON string and returns it. In case of conversion errors, returns * {@code null}. */ public String getAsJsonString() { StringWriter buffer = new StringWriter(); try (JsonGenerator jgen = Json.createGenerator(buffer)) { jgen.writeStartObject(); tags.forEach(t -> jgen.write(t.getTagText(), t.getTagWeight())); jgen.writeEnd(); jgen.flush(); return buffer.toString(); } catch (Exception e) { logger.log(Level.SEVERE, "Unable to encode URL with list of tags: " + buffer.toString(), e); return null; } }
@GET @Path("session/{sessionId}") @Produces(MediaType.APPLICATION_JSON) public String getSession(@PathParam("sessionId") String sessionId) throws IcatException { String userName = beanManager.getUserName(sessionId, manager); double remainingMinutes = beanManager.getRemainingMinutes(sessionId, manager); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = Json.createGenerator(baos); gen.writeStartObject() .write("userName", userName) .write("remainingMinutes", remainingMinutes) .writeEnd(); gen.close(); return baos.toString(); }
@POST @Path("entityManager") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public String create(@FormParam("sessionId") String sessionId, @FormParam("entities") String json) throws IcatException { List<EntityBaseBean> entities = new ArrayList<>(); try (JsonParser parser = Json.createParser(new ByteArrayInputStream(json.getBytes()))) { EventChecker checker = new EventChecker(parser); checker.get(Event.START_ARRAY); while (true) { Event event = checker.get(Event.START_OBJECT, Event.END_ARRAY); if (event == Event.END_ARRAY) { break; } checker.get(Event.KEY_NAME); String entityName = parser.getString(); checker.get(Event.START_OBJECT); entities.add(parseEntity(checker, entityName)); checker.get(Event.END_OBJECT); } } catch (JsonException e) { throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage()); } String userName = beanManager.getUserName(sessionId, manager); List<CreateResponse> createResponses = beanManager.createMany(userName, entities, manager, userTransaction); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (JsonGenerator gen = Json.createGenerator(baos)) { gen.writeStartArray(); for (CreateResponse createResponse : createResponses) { transmitter.processMessage(createResponse.getNotificationMessage()); gen.write(createResponse.getPk()); } gen.writeEnd(); } catch (JMSException e) { throw new IcatException( IcatException.IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage()); } return baos.toString(); }
public String toJsonString() { assert analysis.hasBeenPerformed; if (jsonString != null) { return jsonString; } if (json == null) { toJson(); // Caches the result in `json`. assert json != null; } StringWriter writer = new StringWriter(); JsonGenerator generator = jsonGeneratorFactory.createGenerator(writer); generator.writeStartArray(); generator.write(json); generator.writeEnd(); generator.close(); return writer.toString(); }
private static void writeAttributes(List<InstanceAttributeDTO> attributes, JsonGenerator jg) { jg.writeStartArray("attributes"); for (InstanceAttributeDTO a : attributes) { jg.writeStartObject(); jg.write("name", a.getName()); jg.write("type", a.getType().toString()); jg.write("value", a.getValue()); jg.writeEnd(); } jg.writeEnd(); }
private static void writeGeometries(List<Geometry> files, JsonGenerator jg) { jg.write("qualities", files.size()); if (!files.isEmpty()) { Geometry geometry = files.get(0); jg.write("xMin", geometry.getxMin()); jg.write("yMin", geometry.getyMin()); jg.write("zMin", geometry.getzMin()); jg.write("xMax", geometry.getxMax()); jg.write("yMax", geometry.getyMax()); jg.write("zMax", geometry.getzMax()); } jg.writeStartArray("files"); for (Geometry g : files) { jg.writeStartObject(); jg.write("fullName", "api/files/" + g.getFullName()); jg.writeEnd(); } jg.writeEnd(); }
@Override protected String getJsonRepresentation(TravelExpenseReport travelExpenseReport) { StringWriter writer = new StringWriter(); JsonGenerator jg = jsonGeneratorFactory.createGenerator(writer); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); jg.writeStartObject() .write("status", travelExpenseReport.getStatus().toString()) .write("employee", "/employees/" + travelExpenseReport.getEmployee().getId()) .write("debitor", "/companies/" + travelExpenseReport.getDebitor().getId()); if (travelExpenseReport.getSubmissionDate() != null) { jg.write("submissionDate", sdf.format(travelExpenseReport.getSubmissionDate())); } if (travelExpenseReport.getProject() != null) { jg.write("project", "/projects/" + travelExpenseReport.getProject().getId()); } if (travelExpenseReport.getId() != null) { jg.write("id", travelExpenseReport.getId()); } jg.writeEnd().close(); return writer.toString(); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String query = req.getParameter("q"); long id = Long.parseLong(req.getParameter("id")); Set<String> tags; try { tags = TagExtractor.findMatching(query, id); } catch (SQLException e) { e.printStackTrace(); return; } try (OutputStream os = resp.getOutputStream()) { try (final JsonGenerator generator = Json.createGenerator(os)) { generator.writeStartArray(); for (String s : tags) { generator.writeStartObject(); generator.write("value", s); generator.writeEnd(); } generator.writeEnd(); } } }
private static void writeLeaf( List<PartLink> currentPath, List<Integer> copyInstanceIds, PartIteration partI, Matrix4d combinedMatrix, JsonGenerator jg) { String partIterationId = partI.toString(); List<InstanceAttributeDTO> attributes = new ArrayList<>(); for (InstanceAttribute attr : partI.getInstanceAttributes()) { attributes.add(mapper.map(attr, InstanceAttributeDTO.class)); } jg.writeStartObject(); jg.write("id", Tools.getPathInstanceAsString(currentPath, copyInstanceIds)); jg.write("partIterationId", partIterationId); jg.write("path", Tools.getPathAsString(currentPath)); writeMatrix(combinedMatrix, jg); writeGeometries(partI.getSortedGeometries(), jg); writeAttributes(attributes, jg); jg.writeEnd(); jg.flush(); }
private void generateJSONResponse(OutputStream outputStream, QueryResult queryResult) throws UnsupportedEncodingException, NamingException { String charSet = "UTF-8"; JsonGenerator jg = Json.createGenerator(new OutputStreamWriter(outputStream, charSet)); jg.writeStartArray(); List<String> selects = queryResult.getQuery().getSelects(); List<String> partIterationSelectedAttributes = getPartIterationSelectedAttributes(selects); List<String> pathDataSelectedAttributes = getPathDataSelectedAttributes(selects); context = new InitialContext(); IProductInstanceManagerLocal productInstanceService = (IProductInstanceManagerLocal) context.lookup( "java:global/docdoku-server-ear/docdoku-server-ejb/ProductInstanceManagerBean"); for (QueryResultRow row : queryResult.getRows()) { QueryContext queryContext = row.getContext(); PartRevision part = row.getPartRevision(); PartIteration lastCheckedInIteration = part.getLastCheckedInIteration(); jg.writeStartObject(); jg.write(QueryField.PART_REVISION_PART_KEY, part.getPartNumber() + '-' + part.getVersion()); // PartMaster data if (selects.contains(QueryField.PART_MASTER_NUMBER)) { jg.write(QueryField.PART_MASTER_NUMBER, part.getPartNumber()); } if (selects.contains(QueryField.PART_MASTER_NAME)) { String sName = part.getPartName(); jg.write(QueryField.PART_MASTER_NAME, sName != null ? sName : ""); } if (selects.contains(QueryField.PART_MASTER_TYPE)) { String sType = part.getType(); jg.write(QueryField.PART_MASTER_TYPE, sType != null ? sType : ""); } // PartRevision data if (selects.contains(QueryField.PART_REVISION_MODIFICATION_DATE)) { PartIteration pi = part.getLastIteration(); if (pi != null) { writeDate(jg, QueryField.PART_REVISION_MODIFICATION_DATE, pi.getModificationDate()); } } if (selects.contains(QueryField.PART_REVISION_CREATION_DATE)) { writeDate(jg, QueryField.PART_REVISION_CREATION_DATE, part.getCreationDate()); } if (selects.contains(QueryField.PART_REVISION_CHECKOUT_DATE)) { writeDate(jg, QueryField.PART_REVISION_CHECKOUT_DATE, part.getCheckOutDate()); } if (selects.contains(QueryField.PART_REVISION_CHECKIN_DATE)) { writeDate( jg, QueryField.PART_REVISION_CHECKIN_DATE, lastCheckedInIteration != null ? lastCheckedInIteration.getCheckInDate() : null); } if (selects.contains(QueryField.PART_REVISION_VERSION)) { String version = part.getVersion(); jg.write(QueryField.PART_REVISION_VERSION, version); } if (selects.contains(QueryField.PART_REVISION_LIFECYCLE_STATE)) { String lifeCycleState = part.getLifeCycleState(); jg.write( QueryField.PART_REVISION_LIFECYCLE_STATE, lifeCycleState != null ? lifeCycleState : ""); } if (selects.contains(QueryField.PART_REVISION_STATUS)) { PartRevision.RevisionStatus status = part.getStatus(); jg.write(QueryField.PART_REVISION_STATUS, status.toString()); } if (selects.contains(QueryField.AUTHOR_LOGIN)) { User user = part.getAuthor(); jg.write(QueryField.AUTHOR_LOGIN, user.getLogin()); } if (selects.contains(QueryField.AUTHOR_NAME)) { User user = part.getAuthor(); jg.write(QueryField.AUTHOR_NAME, user.getName()); } if (selects.contains(QueryField.CTX_DEPTH)) { jg.write(QueryField.CTX_DEPTH, row.getDepth()); } if (selects.contains(QueryField.PART_ITERATION_LINKED_DOCUMENTS)) { StringBuilder sb = new StringBuilder(); if (null != queryContext && null != queryContext.getSerialNumber()) { try { ProductInstanceMaster productInstanceMaster = productInstanceService.getProductInstanceMaster( new ProductInstanceMasterKey( queryContext.getSerialNumber(), queryContext.getWorkspaceId(), queryContext.getConfigurationItemId())); ProductInstanceIteration lastIteration = productInstanceMaster.getLastIteration(); ProductBaseline basedOn = lastIteration.getBasedOn(); PartCollection partCollection = basedOn.getPartCollection(); BaselinedPart baselinedPart = partCollection.getBaselinedPart( new BaselinedPartKey( partCollection.getId(), queryContext.getWorkspaceId(), part.getPartNumber())); PartIteration targetPart = baselinedPart.getTargetPart(); Set<DocumentLink> linkedDocuments = targetPart.getLinkedDocuments(); DocumentCollection documentCollection = basedOn.getDocumentCollection(); for (DocumentLink documentLink : linkedDocuments) { DocumentRevision targetDocument = documentLink.getTargetDocument(); BaselinedDocument baselinedDocument = documentCollection.getBaselinedDocument( new BaselinedDocumentKey( documentCollection.getId(), queryContext.getWorkspaceId(), targetDocument.getDocumentMasterId(), targetDocument.getVersion())); if (null != baselinedDocument) { DocumentIteration targetDocumentIteration = baselinedDocument.getTargetDocument(); sb.append(targetDocumentIteration.toString() + ","); } } } catch (UserNotFoundException | UserNotActiveException | WorkspaceNotFoundException | ProductInstanceMasterNotFoundException e) { LOGGER.log(Level.FINEST, null, e); } } else { if (lastCheckedInIteration != null) { Set<DocumentLink> linkedDocuments = lastCheckedInIteration.getLinkedDocuments(); for (DocumentLink documentLink : linkedDocuments) { DocumentRevision targetDocument = documentLink.getTargetDocument(); DocumentIteration targetDocumentLastCheckedInIteration = targetDocument.getLastCheckedInIteration(); if (targetDocumentLastCheckedInIteration != null) { sb.append(targetDocumentLastCheckedInIteration.toString() + ","); } } } } jg.write(QueryField.PART_ITERATION_LINKED_DOCUMENTS, sb.toString()); } for (String attributeSelect : partIterationSelectedAttributes) { String attributeSelectType = attributeSelect .substring(0, attributeSelect.indexOf(".")) .substring(QueryField.PART_REVISION_ATTRIBUTES_PREFIX.length()); String attributeSelectName = attributeSelect.substring(attributeSelect.indexOf(".") + 1); String attributeValue = ""; PartIteration pi = part.getLastIteration(); if (pi != null) { List<InstanceAttribute> attributes = pi.getInstanceAttributes(); if (attributes != null) { jg.writeStartArray(attributeSelect); for (InstanceAttribute attribute : attributes) { InstanceAttributeDescriptor attributeDescriptor = new InstanceAttributeDescriptor(attribute); if (attributeDescriptor.getName().equals(attributeSelectName) && attributeDescriptor.getStringType().equals(attributeSelectType)) { attributeValue = attribute.getValue() + ""; if (attribute instanceof InstanceDateAttribute) { attributeValue = getFormattedDate(((InstanceDateAttribute) attribute).getDateValue()); } else if (attribute instanceof InstanceListOfValuesAttribute) { attributeValue = ((InstanceListOfValuesAttribute) attribute).getSelectedName(); } jg.write(attributeValue); } } jg.writeEnd(); } else { jg.write(attributeSelect, attributeValue); } } else { // TODO: maybe this line is useless and should be removed jg.write(attributeSelect, attributeValue); } } for (String attributeSelect : pathDataSelectedAttributes) { String attributeSelectType = attributeSelect .substring(0, attributeSelect.indexOf(".")) .substring(QueryField.PATH_DATA_ATTRIBUTES_PREFIX.length()); String attributeSelectName = attributeSelect.substring(attributeSelect.indexOf(".") + 1); String attributeValue = ""; PathDataIteration pdi = row.getPathDataIteration(); if (pdi != null) { List<InstanceAttribute> attributes = pdi.getInstanceAttributes(); if (attributes != null) { jg.writeStartArray(attributeSelect); for (InstanceAttribute attribute : attributes) { InstanceAttributeDescriptor attributeDescriptor = new InstanceAttributeDescriptor(attribute); if (attributeDescriptor.getName().equals(attributeSelectName) && attributeDescriptor.getStringType().equals(attributeSelectType)) { attributeValue = attribute.getValue() + ""; if (attribute instanceof InstanceDateAttribute) { attributeValue = getFormattedDate(((InstanceDateAttribute) attribute).getDateValue()); } else if (attribute instanceof InstanceListOfValuesAttribute) { attributeValue = ((InstanceListOfValuesAttribute) attribute).getSelectedName(); } jg.write(attributeValue); } } jg.writeEnd(); } else { jg.write(attributeSelect, attributeValue); } } } if (selects.contains(QueryField.CTX_PRODUCT_ID)) { String configurationItemId = queryContext != null ? queryContext.getConfigurationItemId() : ""; jg.write(QueryField.CTX_PRODUCT_ID, configurationItemId); } if (selects.contains(QueryField.CTX_SERIAL_NUMBER)) { String serialNumber = queryContext != null ? queryContext.getSerialNumber() : ""; jg.write(QueryField.CTX_SERIAL_NUMBER, serialNumber != null ? serialNumber : ""); } if (selects.contains(QueryField.CTX_AMOUNT)) { String amount = row.getAmount() + ""; jg.write(QueryField.CTX_AMOUNT, amount); } if (selects.contains(QueryField.CTX_P2P_SOURCE)) { Map<String, List<PartLinkList>> sources = row.getSources(); String partLinksAsString = Tools.getPartLinksAsHumanString(sources); jg.write(QueryField.CTX_P2P_SOURCE, partLinksAsString); } if (selects.contains(QueryField.CTX_P2P_TARGET)) { Map<String, List<PartLinkList>> targets = row.getTargets(); String partLinksAsString = Tools.getPartLinksAsHumanString(targets); jg.write(QueryField.CTX_P2P_TARGET, partLinksAsString); } if (selects.contains(QueryField.PART_MASTER_IS_STANDARD)) { boolean isStandard = row.getPartRevision().getPartMaster().isStandardPart(); jg.write(QueryField.PART_MASTER_IS_STANDARD, isStandard); } jg.writeEnd(); } jg.writeEnd(); jg.flush(); }
@GET @Path("entityManager") @Produces(MediaType.APPLICATION_JSON) public String search( @QueryParam("sessionId") String sessionId, @QueryParam("query") String query, @QueryParam("id") Long id) throws IcatException { if (sessionId == null) { throw new IcatException(IcatExceptionType.BAD_PARAMETER, "sessionId is not set"); } if (query == null) { throw new IcatException(IcatExceptionType.BAD_PARAMETER, "query is not set"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = Json.createGenerator(baos); String userName = beanManager.getUserName(sessionId, manager); if (id == null) { gen.writeStartArray(); for (Object result : beanManager.search(userName, query, manager, userTransaction)) { if (result == null) { gen.writeNull(); } else if (result instanceof EntityBaseBean) { gen.writeStartObject(); gen.writeStartObject(result.getClass().getSimpleName()); jsonise((EntityBaseBean) result, gen); gen.writeEnd(); gen.writeEnd(); } else if (result instanceof Long) { gen.write((Long) result); } else if (result instanceof Double) { if (Double.isNaN((double) result)) { gen.writeNull(); } else { gen.write((Double) result); } } else if (result instanceof String) { gen.write((String) result); } else if (result instanceof Boolean) { gen.write((Boolean) result); } else { throw new IcatException( IcatException.IcatExceptionType.INTERNAL, "Don't know how to jsonise " + result.getClass()); } } gen.writeEnd(); } else { EntityBaseBean result = beanManager.get(userName, query, id, manager, userTransaction); gen.writeStartObject(); gen.writeStartObject(result.getClass().getSimpleName()); jsonise(result, gen); gen.writeEnd(); gen.writeEnd(); } gen.close(); return baos.toString(); }
private void jsonise(EntityBaseBean bean, JsonGenerator gen) throws IcatException { gen.write("id", bean.getId()) .write("createId", bean.getCreateId()) .write("createTime", bean.getCreateTime().toString()) .write("modId", bean.getModId()) .write("modTime", bean.getModTime().toString()); Class<? extends EntityBaseBean> klass = bean.getClass(); Map<Field, Method> getters = eiHandler.getGetters(klass); Set<Field> atts = eiHandler.getAttributes(klass); Set<Field> updaters = eiHandler.getSettersForUpdate(klass).keySet(); for (Field field : eiHandler.getFields(klass)) { Object value = null; try { value = getters.get(field).invoke(bean); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage()); } if (value == null) { // Ignore null values } else if (atts.contains(field)) { String type = field.getType().getSimpleName(); if (type.equals("String")) { gen.write(field.getName(), (String) value); } else if (type.equals("Integer")) { gen.write(field.getName(), value.toString()); } else if (type.equals("Double")) { gen.write(field.getName(), value.toString()); } else if (type.equals("Long")) { gen.write(field.getName(), value.toString()); } else if (type.equals("boolean")) { gen.write(field.getName(), value.toString()); } else if (field.getType().isEnum()) { gen.write(field.getName(), value.toString()); } else if (type.equals("Date")) { synchronized (df8601) { gen.write(field.getName(), df8601.format((Date) value)); } } else { throw new IcatException( IcatExceptionType.INTERNAL, "Don't know how to jsonise field of type " + type); } } else if (updaters.contains(field)) { gen.writeStartObject(field.getName()); jsonise((EntityBaseBean) value, gen); gen.writeEnd(); } else { gen.writeStartArray(field.getName()); @SuppressWarnings("unchecked") List<EntityBaseBean> beans = (List<EntityBaseBean>) value; for (EntityBaseBean b : beans) { gen.writeStartObject(); jsonise(b, gen); gen.writeEnd(); } gen.writeEnd(); } } }