List of usage examples for com.fasterxml.jackson.core JsonGenerator writeEndArray
public abstract void writeEndArray() throws IOException, JsonGenerationException;
From source file:org.n52.tamis.core.json.serialize.processes.execute.ExtendedExecuteHttpPostBodySerializer.java
@Override public void serialize(Execute_HttpPostBody executeBody_short, JsonGenerator jsonGenerator, SerializerProvider serProvider) throws IOException, JsonProcessingException { logger.info("Start serialization of execute HTTP POST input body \"{}\"", executeBody_short); /*//www . ja v a 2s. c o m * the structure of the target JSON body looks like: * * { "Execute": { "Identifier": "org.n52.tamis.algorithm.interpolation", "Input": [ { "Input": [ { "Reference": { "_href": "http://fluggs.wupperverband.de/sos2/service?service=SOS&request=GetObservation&version=2.0.0&offering=Zeitreihen_2m_Tiefe&observedProperty=Grundwasserstand&responseFormat=http%3A//www.opengis.net/om/2.0", "_mimeType": "application/om+xml; version=2.0", "_schema": "http://schemas.opengis.net/om/2.0/observation.xsd" }, "_id": "gw1" }, { "Reference": { "_href": "http://fluggs.wupperverband.de/sos2/service?service=SOS&request=GetObservation&version=2.0.0&offering=Zeitreihen_2m_Tiefe&observedProperty=Sohlenwasserdruck&responseFormat=http%3A//www.opengis.net/om/2.0", "_mimeType": "application/om+xml; version=2.0", "_schema": "http://schemas.opengis.net/om/2.0/observation.xsd" }, "_id": "swd1" } ], "_id": "input-variables" }, { "Data": { "_mimeType": "text/xml", "_schema": "http://schemas.opengis.net/gml/3.2.1/base/feature.xsd", "__text": "<wfs:FeatureCollection xmlns:testbed11="http://opengeospatial.org" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wml2="http://www.opengis.net/waterml/2.0" xmlns:sf="http://www.opengis.net/sampling/2.0" xmlns:sams="http://www.opengis.net/samplingSpatial/2.0" numberOfFeatures="1" timeStamp="2016-02-15T16:24:55.640Z" xsi:schemaLocation="http://www.opengis.net/wfs http://geoprocessing.demo.52north.org:8080/geoserver/schemas/wfs/1.1.0/wfs.xsd"> <gml:featureMembers> <wml2:MonitoringPoint gml:id="xyz.1"> <gml:identifier codeSpace="http://www.opengis.net/def/nil/OGC/0/unknown">xyz</gml:identifier> <gml:name codeSpace="http://www.opengis.net/def/nil/OGC/0/unknown">xyz</gml:name> <sf:sampledFeature xlink:href="urn:ogc:def:nil:OGC:unknown" /> <sams:shape> <ns:Point xmlns:ns="http://www.opengis.net/gml/3.2" ns:id="point_xyz"> <ns:pos srsName="http://www.opengis.net/def/crs/EPSG/0/31466">5668202.8356 2595842.8958</ns:pos> </ns:Point> </sams:shape> </wml2:MonitoringPoint> </gml:featureMembers> </wfs:FeatureCollection>" }, "_id": "target-variable-point" } ], "output": { "_mimeType": "application/om+xml; version=2.0", "_schema": "http://schemas.opengis.net/om/2.0/observation.xsd", "_id": "estimated-values", "_transmission": "value" }, "_service": "WPS", "_version": "2.0.0"} } */ jsonGenerator.writeStartObject(); jsonGenerator.writeObjectFieldStart("Execute"); jsonGenerator.writeStringField("Identifier", executeBody_short.getProcessId()); jsonGenerator.writeArrayFieldStart("Input"); List<ExecuteInput> inputs = executeBody_short.getInputs(); for (ExecuteInput executeInput : inputs) { jsonGenerator.writeObject(executeInput); } jsonGenerator.writeEndArray(); /** * TODO is it really correct, that "output" starts with a small "o"? */ jsonGenerator.writeArrayFieldStart("output"); List<ExecuteOutput> outputs = executeBody_short.getOutputs(); for (ExecuteOutput executeOutput : outputs) { jsonGenerator.writeObject(executeOutput); } jsonGenerator.writeEndArray(); jsonGenerator.writeStringField("_service", Execute_HttpPostBody.service); jsonGenerator.writeStringField("_version", executeBody_short.getVersion()); jsonGenerator.writeEndObject(); jsonGenerator.writeEndObject(); logger.info("Serialization of execute HTTP POST input body ended."); }
From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java
private void writePossiblePropertyValues(JsonGenerator jgen, String currentVocab, ActionInputParameter actionInputParameter, @SuppressWarnings("unused") Object[] possiblePropertyValues) throws IOException { // Enable the following to list possible values. // Problem: how to express individuals only for certain hydra:options // not all hydra:options should be taken as uris, sometimes they might be just literals // how to make that clear to the client? // maybe we must write them out for options // if (possiblePropertyValues.length > 0) { // jgen.writeArrayFieldStart("hydra:option"); ///*from w w w . ja v a 2s . c om*/ // for (Object possibleValue : possiblePropertyValues) { // // TODO: apply "hydra:option" : { "@type": "@vocab"} to context for enums // writeScalarValue(jgen, possibleValue, rootParameter.getParameterType()); // } // jgen.writeEndArray(); // } if (actionInputParameter.isArrayOrCollection()) { jgen.writeBooleanField(getPropertyOrClassNameInVocab(currentVocab, "multipleValues", LdContextFactory.HTTP_SCHEMA_ORG, "schema:"), true); } // valueRequired (hard to say, using @Access on Event is for all update requests - or make // specific request beans for different // purposes rather than always passing an instance of e.g. Event?) // -> update is a different use case than create - or maybe have an @Requires("eventStatus") // annotation alongside requestBody to tell which attributes are required or writable, and use // Requires over // bean structure, where ctor with least length of args is required and setters are supported // but optional? The bean structure does say what is writable for updates, but not what is required // for creation. Right now setters are supportedProperties. For creation we would have to add constructor // arguments as supportedProperties. // (/) defaultValue (pre-filled value, e.g. list of selected items for option) // valueName (for iri templates only) // (/) readonlyValue (true for final public field or absence of setter, send fixed value like hidden field?) // -> use hydra:readable, hydra:writable // (/) multipleValues // (/) valueMinLength // (/) valueMaxLength // (/) valuePattern // minValue (DateTime support) // maxValue (DateTime support) // (/) stepValue final Map<String, Object> inputConstraints = actionInputParameter.getInputConstraints(); if (actionInputParameter.hasValue()) { if (actionInputParameter.isArrayOrCollection()) { Object[] callValues = actionInputParameter.getValues(); Class<?> componentType = callValues.getClass().getComponentType(); // only write defaultValue for array of scalars if (DataType.isSingleValueType(componentType)) { jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue", LdContextFactory.HTTP_SCHEMA_ORG, "schema:")); jgen.writeStartArray(); for (Object callValue : callValues) { writeScalarValue(jgen, callValue, componentType); } jgen.writeEndArray(); } } else { jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue", LdContextFactory.HTTP_SCHEMA_ORG, "schema:")); writeScalarValue(jgen, actionInputParameter.getValue(), actionInputParameter.getParameterType()); } } if (!inputConstraints.isEmpty()) { final List<String> keysToAppendValue = Arrays.asList(Input.MAX, Input.MIN, Input.STEP); for (String keyToAppendValue : keysToAppendValue) { final Object constraint = inputConstraints.get(keyToAppendValue); if (constraint != null) { jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, keyToAppendValue + "Value", LdContextFactory.HTTP_SCHEMA_ORG, "schema:")); jgen.writeNumber(constraint.toString()); } } final List<String> keysToPrependValue = Arrays.asList(Input.MAX_LENGTH, Input.MIN_LENGTH, Input.PATTERN); for (String keyToPrependValue : keysToPrependValue) { final Object constraint = inputConstraints.get(keyToPrependValue); if (constraint != null) { jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "value" + StringUtils.capitalize(keyToPrependValue), LdContextFactory.HTTP_SCHEMA_ORG, "schema:")); if (Input.PATTERN.equals(keyToPrependValue)) { jgen.writeString(constraint.toString()); } else { jgen.writeNumber(constraint.toString()); } } } } }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
protected void marshallNode(FlowNode node, Map<String, Object> properties, String stencil, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset) throws JsonGenerationException, IOException { if (properties == null) { properties = new LinkedHashMap<String, Object>(); }// w w w . ja va 2 s .c o m if (node.getDocumentation() != null && node.getDocumentation().size() > 0) { properties.put("documentation", node.getDocumentation().get(0).getText()); } if (node.getName() != null) { properties.put("name", unescapeXml(node.getName())); } else { if (node instanceof TextAnnotation) { if (((TextAnnotation) node).getText() != null) { properties.put("name", ((TextAnnotation) node).getText()); } else { properties.put("name", ""); } } else { properties.put("name", ""); } } // overwrite name if elementname extension element is present String elementName = Utils.getMetaDataValue(node.getExtensionValues(), "elementname"); if (elementName != null) { properties.put("name", elementName); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", stencil); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (SequenceFlow outgoing : node.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } // we need to also add associations as outgoing elements Process process = (Process) plane.getBpmnElement(); writeAssociations(process, node.getId(), generator); // and boundary events for activities List<BoundaryEvent> boundaryEvents = new ArrayList<BoundaryEvent>(); findBoundaryEvents(process, boundaryEvents); for (BoundaryEvent be : boundaryEvents) { if (be.getAttachedToRef().getId().equals(node.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", be.getId()); generator.writeEndObject(); } } generator.writeEndArray(); // boundary events have a docker if (node instanceof BoundaryEvent) { Iterator<FeatureMap.Entry> iter = node.getAnyAttribute().iterator(); boolean foundDockerInfo = false; while (iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if (entry.getEStructuralFeature().getName().equals("dockerinfo")) { foundDockerInfo = true; String dockerInfoStr = String.valueOf(entry.getValue()); if (dockerInfoStr != null && dockerInfoStr.length() > 0) { if (dockerInfoStr.endsWith("|")) { dockerInfoStr = dockerInfoStr.substring(0, dockerInfoStr.length() - 1); String[] dockerInfoParts = dockerInfoStr.split("\\|"); String infoPartsToUse = dockerInfoParts[0]; String[] infoPartsToUseParts = infoPartsToUse.split("\\^"); if (infoPartsToUseParts != null && infoPartsToUseParts.length > 0) { generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", Double.valueOf(infoPartsToUseParts[0])); generator.writeObjectField("y", Double.valueOf(infoPartsToUseParts[1])); generator.writeEndObject(); generator.writeEndArray(); } } } } } // backwards compatibility to older versions -- BZ 1196259 if (!foundDockerInfo) { // find the edge associated with this boundary event for (DiagramElement element : plane.getPlaneElement()) { if (element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == node) { List<Point> waypoints = ((BPMNEdge) element).getWaypoint(); if (waypoints != null && waypoints.size() > 0) { // one per boundary event Point p = waypoints.get(0); if (p != null) { generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", p.getX()); generator.writeObjectField("y", p.getY()); generator.writeEndObject(); generator.writeEndArray(); } } } } } } BPMNShape shape = (BPMNShape) findDiagramElement(plane, node); Bounds bounds = shape.getBounds(); correctEventNodeSize(shape); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); }
From source file:tds.student.web.backing.TestShellScriptsBacking.java
private void addTestSegments() throws IOException, ReturnStatusException { TestSession testSession = StudentContext.getSession(); // _studentSettings = FacesContextHelper.getBean ("studentSettings", // StudentSettings.class); OpportunitySegments oppSegments = null; // load opp segments only if there are any test segments if (_testProps.getSegments().size() > 0) { oppSegments = this._iOpportunityService.getSegments(this._testOpportunity.getOppInstance(), !this._studentSettings.isReadOnly()); }/* www .jav a 2 s . c o m*/ StringWriter sw = new StringWriter(); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator writer = jsonFactory.createGenerator(sw); writer.writeStartArray(); // [ for (final TestSegment testSegment : _testProps.getSegments()) { OpportunitySegment oppSegment = null; // find opportunity segment if (oppSegments != null) { oppSegment = (OpportunitySegment) CollectionUtils.find(oppSegments, new Predicate() { @Override public boolean evaluate(Object arg0) { if (StringUtils.equals(((OpportunitySegment) arg0).getId(), testSegment.getId())) return true; return false; } }); } // figure out segment permeability int isPermeable = testSegment.getIsPermeable(); int updatePermeable = isPermeable; // these are local override rules (reviewed with Larry) if (oppSegment != null) { /* * if -1, use the defined value for the segment as returned by * IB_GetSegments if not -1, then the local value defines the temporary * segment permeability */ if (oppSegment.getIsPermeable() != -1) { isPermeable = oppSegment.getIsPermeable(); /* * The default permeability is restored when the student leaves the * segment while testing. Assuming the segment is impermeable, this * allows the student one entry into the segment during the sitting. * When the student leaves the segment, is membrane is enforced by the * student app. The database will restore the default value of the * segment membrane when the test is paused. */ if (oppSegment.getRestorePermOn() != "segment") { updatePermeable = oppSegment.getIsPermeable(); } } // NOTE: When student enters segment, set isPermeable = updatePermeable } // if read only mode is enabled then we should let user have access if (_studentSettings.isReadOnly()) { isPermeable = 1; updatePermeable = 1; } // figure out segment approval int entryApproval = testSegment.getEntryApproval(); int exitApproval = testSegment.getExitApproval(); // NOTE: If proctorless test then don't require entry/exit approval // (nobody to approve it) if (testSession.isProctorless() || _studentSettings.isReadOnly()) { entryApproval = 0; exitApproval = 0; } // BUG #22642: Entry and Exit approvals are not needed from Test level // review screen when approval = 2 else if (getViewPageNumber() > 0) { if (testSegment.getEntryApproval() == 2) entryApproval = 0; if (testSegment.getExitApproval() == 2) exitApproval = 0; } // write segment json writer.writeStartObject(); writer.writeStringField("type", "object"); // { writer.writeStringField("id", testSegment.getId()); writer.writeNumberField("position", testSegment.getPosition()); writer.writeStringField("label", testSegment.getLabel()); writer.writeBooleanField("itemReview", testSegment.isItemReview()); writer.writeNumberField("isPermeable", isPermeable); writer.writeNumberField("updatePermeable", updatePermeable); writer.writeNumberField("entryApproval", entryApproval); writer.writeNumberField("exitApproval", exitApproval); // Looks like we don't use this variable in javascript (removed for 2012) // Test adaptiveSegment = // TestOpportunity.AdaptiveTest.GetSegmentTest(testSegment.ID); // writer.WriteObject("length", (adaptiveSegment != null) ? // adaptiveSegment.TotalMinLength : 0); writer.writeEndObject(); // } } writer.writeEndArray(); // ] writer.close(); // write out javascript StringBuilder javascript = new StringBuilder(); javascript.append("var tdsSegments = "); javascript.append(sw.toString()); javascript.append("; "); this.getClientScript().addToJsCode(javascript.toString()); }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
protected void marshallProcess(Process process, Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException { BPMNPlane plane = null;/*from w w w .ja v a 2 s . co m*/ for (BPMNDiagram d : def.getDiagrams()) { if (d != null) { BPMNPlane p = d.getPlane(); if (p != null) { if (p.getBpmnElement() == process) { plane = p; break; } } } } if (plane == null) { throw new IllegalArgumentException("Could not find BPMNDI information"); } generator.writeArrayFieldStart("childShapes"); List<String> laneFlowElementsIds = new ArrayList<String>(); for (LaneSet laneSet : process.getLaneSets()) { for (Lane lane : laneSet.getLanes()) { // we only want to marshall lanes if we have the bpmndi info for them! if (findDiagramElement(plane, lane) != null) { laneFlowElementsIds.addAll(marshallLanes(lane, plane, generator, 0, 0, preProcessingData, def)); } } } for (FlowElement flowElement : process.getFlowElements()) { if (!laneFlowElementsIds.contains(flowElement.getId())) { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } for (Artifact artifact : process.getArtifacts()) { marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def); } generator.writeEndArray(); }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
protected void marshallAssociation(Association association, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(); Iterator<FeatureMap.Entry> iter = association.getAnyAttribute().iterator(); boolean foundBrColor = false; while (iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if (entry.getEStructuralFeature().getName().equals("type")) { properties.put("type", entry.getValue()); }/* w w w. ja va 2 s . com*/ if (entry.getEStructuralFeature().getName().equals("bordercolor")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } } if (!foundBrColor) { properties.put("bordercolor", defaultSequenceflowColor); } if (association.getDocumentation() != null && association.getDocumentation().size() > 0) { properties.put("documentation", association.getDocumentation().get(0).getText()); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); if (association.getAssociationDirection().equals(AssociationDirection.ONE)) { generator.writeObjectField("id", "Association_Unidirectional"); } else if (association.getAssociationDirection().equals(AssociationDirection.BOTH)) { generator.writeObjectField("id", "Association_Bidirectional"); } else { generator.writeObjectField("id", "Association_Undirected"); } generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeStartObject(); generator.writeObjectField("resourceId", association.getTargetRef().getId()); generator.writeEndObject(); generator.writeEndArray(); Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, association.getSourceRef())).getBounds(); Bounds targetBounds = null; float tbx = 0; float tby = 0; if (findDiagramElement(plane, association.getTargetRef()) instanceof BPMNShape) { targetBounds = ((BPMNShape) findDiagramElement(plane, association.getTargetRef())).getBounds(); } else if (findDiagramElement(plane, association.getTargetRef()) instanceof BPMNEdge) { // connect it to first waypoint on edge List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association.getTargetRef())) .getWaypoint(); if (waypoints != null && waypoints.size() > 0) { tbx = waypoints.get(0).getX(); tby = waypoints.get(0).getY(); } } generator.writeArrayFieldStart("dockers"); generator.writeStartObject(); generator.writeObjectField("x", sourceBounds.getWidth() / 2); generator.writeObjectField("y", sourceBounds.getHeight() / 2); generator.writeEndObject(); List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association)).getWaypoint(); for (int i = 1; i < waypoints.size() - 1; i++) { Point waypoint = waypoints.get(i); generator.writeStartObject(); generator.writeObjectField("x", waypoint.getX()); generator.writeObjectField("y", waypoint.getY()); generator.writeEndObject(); } if (targetBounds != null) { generator.writeStartObject(); // text annotations have to be treated specia if (association.getTargetRef() instanceof TextAnnotation) { generator.writeObjectField("x", 1); generator.writeObjectField("y", targetBounds.getHeight() / 2); } else { generator.writeObjectField("x", targetBounds.getWidth() / 2); generator.writeObjectField("y", targetBounds.getHeight() / 2); } generator.writeEndObject(); generator.writeEndArray(); } else { generator.writeStartObject(); generator.writeObjectField("x", tbx); generator.writeObjectField("y", tby); generator.writeEndObject(); generator.writeEndArray(); } }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
protected void marshallDataObject(DataObject dataObject, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); if (dataObject.getDocumentation() != null && dataObject.getDocumentation().size() > 0) { properties.put("documentation", dataObject.getDocumentation().get(0).getText()); }//from w ww . j a v a2s. com if (dataObject.getName() != null && dataObject.getName().length() > 0) { properties.put("name", unescapeXml(dataObject.getName())); } else { // we need a name, use id instead properties.put("name", dataObject.getId()); } // overwrite name if elementname extension element is present String elementName = Utils.getMetaDataValue(dataObject.getExtensionValues(), "elementname"); if (elementName != null) { properties.put("name", elementName); } if (dataObject.getItemSubjectRef().getStructureRef() != null && dataObject.getItemSubjectRef().getStructureRef().length() > 0) { if (defaultTypesList.contains(dataObject.getItemSubjectRef().getStructureRef())) { properties.put("standardtype", dataObject.getItemSubjectRef().getStructureRef()); } else { properties.put("customtype", dataObject.getItemSubjectRef().getStructureRef()); } } Association outgoingAssociaton = findOutgoingAssociation(plane, dataObject); Association incomingAssociation = null; Process process = (Process) plane.getBpmnElement(); for (Artifact artifact : process.getArtifacts()) { if (artifact instanceof Association) { Association association = (Association) artifact; if (association.getTargetRef() == dataObject) { incomingAssociation = association; } } } if (outgoingAssociaton != null && incomingAssociation == null) { properties.put("input_output", "Input"); } if (outgoingAssociaton == null && incomingAssociation != null) { properties.put("input_output", "Output"); } marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "DataObject"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); List<Association> associations = findOutgoingAssociations(plane, dataObject); if (associations != null) { for (Association as : associations) { generator.writeStartObject(); generator.writeObjectField("resourceId", as.getId()); generator.writeEndObject(); } } generator.writeEndArray(); Bounds bounds = ((BPMNShape) findDiagramElement(plane, dataObject)).getBounds(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); }
From source file:org.openiot.security.oauth.OAuth20PermissionController.java
@Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String clientId = request.getParameter(OAuthConstants.CLIENT_ID); log.debug("clientId : {}", clientId); final String accessToken = request.getParameter(OAuthConstants.ACCESS_TOKEN); log.debug("accessToken : {}", accessToken); final String callerClientId = request.getParameter("caller_client_id"); log.debug("callerClientId : {}", callerClientId); final String callerAccessToken = request.getParameter("caller_access_token"); log.debug("callerAccessToken : {}", callerAccessToken); final JsonFactory jsonFactory = new JsonFactory(); final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(response.getWriter()); response.setContentType("application/json"); // accessToken is required if (StringUtils.isBlank(accessToken)) { log.error("missing accessToken"); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", OAuthConstants.MISSING_ACCESS_TOKEN); jsonGenerator.writeEndObject();/*w ww. j a v a 2 s . com*/ jsonGenerator.close(); response.flushBuffer(); return null; } // caller accessToken is required if (StringUtils.isBlank(callerAccessToken)) { log.error("missing caller accessToken"); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", "missing_callerAccessToken"); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; } // clientId is required if (StringUtils.isBlank(clientId)) { log.error("missing clientId"); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", MISSING_CLIENT_ID); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; } // caller clientId is required if (StringUtils.isBlank(callerClientId)) { log.error("missing clientId"); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", "missing_callerClientId"); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; } // get ticket granting ticket final TicketGrantingTicket ticketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry .getTicket(accessToken); if (ticketGrantingTicket == null || ticketGrantingTicket.isExpired()) { log.error("expired accessToken : {}", accessToken); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", OAuthConstants.EXPIRED_ACCESS_TOKEN); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; } // get ticket granting ticket for the caller final TicketGrantingTicket callerTicketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry .getTicket(callerAccessToken); if (callerTicketGrantingTicket == null || callerTicketGrantingTicket.isExpired()) { log.error("expired accessToken : {}", callerAccessToken); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", OAuthConstants.EXPIRED_ACCESS_TOKEN + "_for_caller"); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; } // name of the CAS service final Collection<RegisteredService> services = servicesManager.getAllServices(); RegisteredService service = null; for (final RegisteredService aService : services) { if (StringUtils.equals(aService.getName(), clientId)) { service = aService; break; } } if (service == null) { log.error("nonexistent clientId : {}", clientId); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", NONEXISTENT_CLIENT_ID); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; } // TODO: check if the TGT is granted to the client?! // final TicketGrantingTicket rawTicket = ((AbstractDistributedTicketRegistry.TicketGrantingTicketDelegator)ticketGrantingTicket).getTicket(); // final Field servicesField = rawTicket.getClass().getDeclaredField("services"); // servicesField.setAccessible(true); // HashMap<String, Service> servicesMap = new HashMap<String, Service>(); // servicesMap = (HashMap<String, Service>) servicesField.get(rawTicket); // log.error("ServiceMaps is empty ? {}", servicesMap.isEmpty()); // for(Map.Entry<String, Service> entry : servicesMap.entrySet()){ // AbstractWebApplicationService webAppService = (AbstractWebApplicationService) entry.getValue(); // log.error("Service for ticket {} is {}", rawTicket.getId(), webAppService.getId()); // } // if (!servicesMap.containsKey(service.getId()) || !servicesMap.get(service.getId()).equals(service)) { // log.error("Ticket is not granted to client : {}", clientId); // jsonGenerator.writeStartObject(); // jsonGenerator.writeStringField("error", TICKET_NOT_GRANTED); // jsonGenerator.writeEndObject(); // jsonGenerator.close(); // response.flushBuffer(); // return null; // } // name of the CAS service for caller RegisteredService callerService = null; for (final RegisteredService aService : services) { if (StringUtils.equals(aService.getName(), callerClientId)) { callerService = aService; break; } } if (callerService == null) { log.error("nonexistent caller clientId : {}", callerClientId); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", NONEXISTENT_CLIENT_ID + "for_caller"); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; } final Principal principal = ticketGrantingTicket.getAuthentication().getPrincipal(); final Map<String, Set<String>> permissions = extractPermissions(callerService.getId(), principal.getId()); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField(CasWrapperProfile.ID, principal.getId()); jsonGenerator.writeArrayFieldStart("role_permissions"); for (final String roleName : permissions.keySet()) { jsonGenerator.writeStartObject(); jsonGenerator.writeArrayFieldStart(roleName); for (final String permission : permissions.get(roleName)) jsonGenerator.writeString(permission); jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); jsonGenerator.close(); response.flushBuffer(); return null; }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
private List<String> marshallLanes(Lane lane, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException { Bounds bounds = ((BPMNShape) findDiagramElement(plane, lane)).getBounds(); List<String> nodeRefIds = new ArrayList<String>(); if (bounds != null) { generator.writeStartObject();/*from ww w . java 2 s.c o m*/ generator.writeObjectField("resourceId", lane.getId()); Map<String, Object> laneProperties = new LinkedHashMap<String, Object>(); if (lane.getName() != null) { laneProperties.put("name", unescapeXml(lane.getName())); } else { laneProperties.put("name", ""); } // overwrite name if elementname extension element is present String elementName = Utils.getMetaDataValue(lane.getExtensionValues(), "elementname"); if (elementName != null) { laneProperties.put("name", elementName); } Documentation doc = getDocumentation(lane); if (doc != null) { laneProperties.put("documentation", doc.getText()); } Iterator<FeatureMap.Entry> iter = lane.getAnyAttribute().iterator(); boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; while (iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if (entry.getEStructuralFeature().getName().equals("background-color") || entry.getEStructuralFeature().getName().equals("bgcolor")) { laneProperties.put("bgcolor", entry.getValue()); foundBgColor = true; } if (entry.getEStructuralFeature().getName().equals("border-color") || entry.getEStructuralFeature().getName().equals("bordercolor")) { laneProperties.put("bordercolor", entry.getValue()); foundBrColor = true; } if (entry.getEStructuralFeature().getName().equals("fontsize")) { laneProperties.put("fontsize", entry.getValue()); foundBrColor = true; } if (entry.getEStructuralFeature().getName().equals("color") || entry.getEStructuralFeature().getName().equals("fontcolor")) { laneProperties.put("fontcolor", entry.getValue()); foundFontColor = true; } if (entry.getEStructuralFeature().getName().equals("selectable")) { laneProperties.put("isselectable", entry.getValue()); foundSelectable = true; } } if (!foundBgColor) { laneProperties.put("bgcolor", defaultBgColor_Swimlanes); } if (!foundBrColor) { laneProperties.put("bordercolor", defaultBrColor); } if (!foundFontColor) { laneProperties.put("fontcolor", defaultFontColor); } if (!foundSelectable) { laneProperties.put("isselectable", "true"); } marshallProperties(laneProperties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "Lane"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); for (FlowElement flowElement : lane.getFlowNodeRefs()) { nodeRefIds.add(flowElement.getId()); if (coordianteManipulation) { marshallFlowElement(flowElement, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); Process process = (Process) plane.getBpmnElement(); writeAssociations(process, lane.getId(), generator); generator.writeEndArray(); generator.writeObjectFieldStart("bounds"); generator.writeObjectFieldStart("lowerRight"); generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset); generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset); generator.writeEndObject(); generator.writeObjectFieldStart("upperLeft"); generator.writeObjectField("x", bounds.getX() - xOffset); generator.writeObjectField("y", bounds.getY() - yOffset); generator.writeEndObject(); generator.writeEndObject(); generator.writeEndObject(); } else { // dont marshall the lane unless it has BPMNDI info (eclipse editor does not generate it for lanes currently. for (FlowElement flowElement : lane.getFlowNodeRefs()) { nodeRefIds.add(flowElement.getId()); // we dont want an offset here! marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } return nodeRefIds; }
From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java
@Override public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider) throws IOException { try {//from w w w . j a v a 2s. c o m Collection<Link> simpleLinks = new ArrayList<Link>(); Collection<Affordance> affordances = new ArrayList<Affordance>(); Collection<Link> templatedLinks = new ArrayList<Link>(); Collection<Affordance> collectionAffordances = new ArrayList<Affordance>(); Link selfRel = null; for (Link link : links) { if (link instanceof Affordance) { final Affordance affordance = (Affordance) link; final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors(); if (!actionDescriptors.isEmpty()) { // TODO: consider to use Link href for template even if it is not compatible if (affordance.getUriTemplateComponents().hasVariables()) { // TODO resolve rel against context if ("hydra:search".equals(affordance.getRel()) || Cardinality.SINGLE == affordance.getCardinality()) { templatedLinks.add(affordance); } else { collectionAffordances.add(affordance); } } else { // if all required variables are satisfied, the url can be used as identifier // by stripping optional variables if (!affordance.isSelfRel() && Cardinality.COLLECTION == affordance.getCardinality()) { collectionAffordances.add(affordance); } else { affordances.add(affordance); } } } else { if (affordance.isTemplated()) { templatedLinks.add(affordance); } else { simpleLinks.add(affordance); } } } else if (link.isTemplated()) { templatedLinks.add(link); } else { simpleLinks.add(link); } if ("self".equals(link.getRel())) { selfRel = link; } } for (Link templatedLink : templatedLinks) { // templated affordance might turn out to have all variables satisfied or // only optional unsatisfied variables ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet(templatedLink); // TODO handle rev here String rel = templatedLink.getRel(); writeIriTemplate(rel, templatedLink.getHref(), templatedLink.getVariableNames(), actionDescriptorForHttpGet, jgen); } @SuppressWarnings("unchecked") Deque<LdContext> contextStack = (Deque<LdContext>) serializerProvider .getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT); String currentVocab = (contextStack != null && !contextStack.isEmpty()) ? contextStack.peek().vocab : null; // related collections if (!collectionAffordances.isEmpty()) { jgen.writeArrayFieldStart("hydra:collection"); for (Affordance collectionAffordance : collectionAffordances) { jgen.writeStartObject(); jgen.writeStringField(JsonLdKeywords.AT_TYPE, "hydra:Collection"); PartialUriTemplateComponents templateComponents = collectionAffordance .getUriTemplateComponents(); if (!collectionAffordance.isBaseUriTemplated() && !collectionAffordance.hasUnsatisfiedRequiredVariables()) { String collectionUri = templateComponents.getBaseUri() + templateComponents.getQueryHead(); jgen.writeStringField(JsonLdKeywords.AT_ID, collectionUri); } if (templateComponents.hasVariables()) { ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet( collectionAffordance); writeIriTemplate("hydra:search", templateComponents.toString(), templateComponents.getVariableNames(), actionDescriptorForHttpGet, jgen); } jgen.writeObjectFieldStart("hydra:manages"); // do we have a collection holder which is not owner of the affordance? TypedResource collectionHolder = collectionAffordance.getCollectionHolder(); if (collectionAffordance.getRev() != null) { jgen.writeStringField("hydra:property", collectionAffordance.getRev()); if (collectionHolder != null) { // can't use writeObjectField, it won't inherit the context stack writeCollectionHolder("hydra:object", collectionHolder, jgen); } else if (selfRel != null) { jgen.writeStringField("hydra:object", selfRel.getHref()); } } else if (collectionAffordance.getRel() != null) { jgen.writeStringField("hydra:property", collectionAffordance.getRel()); if (collectionHolder != null) { // can't use writeObjectField, it won't inherit the context stack writeCollectionHolder("hydra:subject", collectionHolder, jgen); } else if (selfRel != null) { jgen.writeStringField("hydra:subject", selfRel.getHref()); } } jgen.writeEndObject(); // end manages List<ActionDescriptor> actionDescriptors = collectionAffordance.getActionDescriptors(); if (!actionDescriptors.isEmpty()) { jgen.writeArrayFieldStart("hydra:operation"); } writeActionDescriptors(jgen, currentVocab, actionDescriptors); if (!actionDescriptors.isEmpty()) { jgen.writeEndArray(); // end hydra:operation } jgen.writeEndObject(); // end collection } jgen.writeEndArray(); } for (Affordance affordance : affordances) { final String rel = affordance.getRel(); List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors(); if (!actionDescriptors.isEmpty()) { if (!Link.REL_SELF.equals(rel)) { jgen.writeObjectFieldStart(rel); // begin rel } jgen.writeStringField(JsonLdKeywords.AT_ID, affordance.getHref()); jgen.writeArrayFieldStart("hydra:operation"); } writeActionDescriptors(jgen, currentVocab, actionDescriptors); if (!actionDescriptors.isEmpty()) { jgen.writeEndArray(); // end hydra:operation if (!Link.REL_SELF.equals(rel)) { jgen.writeEndObject(); // end rel } } } for (Link simpleLink : simpleLinks) { final String rel = simpleLink.getRel(); if (Link.REL_SELF.equals(rel)) { jgen.writeStringField("@id", simpleLink.getHref()); } else { String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel; jgen.writeObjectFieldStart(linkAttributeName); jgen.writeStringField("@id", simpleLink.getHref()); jgen.writeEndObject(); } } } catch (IntrospectionException e) { throw new RuntimeException(e); } }