List of usage examples for com.fasterxml.jackson.core JsonGenerator writeArrayFieldStart
public final void writeArrayFieldStart(String fieldName) throws IOException, JsonGenerationException
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()); }//from ww w. j av a 2s. c o m 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 w w . j a v a 2 s .c o m 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();//from w w w . j ava 2 s .co m 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 w w w . j a va2 s. c om*/ 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
/** * Writes bean description recursively.// w ww.j a va 2 s . c o m * * @param jgen * to write to * @param currentVocab * in context * @param valueType * class of value * @param allRootParameters * of the method that receives the request body * @param rootParameter * the request body * @param currentCallValue * the value at the current recursion level * @param propertyPath * of the current recursion level * @throws IntrospectionException * @throws IOException */ private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType, ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue, String propertyPath) throws IntrospectionException, IOException { Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>(); // collect supported properties from ctor Constructor[] constructors = valueType.getConstructors(); // find default ctor Constructor constructor = PropertyUtils.findDefaultCtor(constructors); // find ctor with JsonCreator ann if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } if (constructor == null) { // TODO this can be a generic collection, find a way to describe it LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type " + valueType.getName()); return; } int parameterCount = constructor.getParameterTypes().length; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; // TODO use required attribute of JsonProperty String paramName = jsonProperty.value(); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName); ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter( new MethodParameter(constructor, paramIndex), propertyValue); // TODO collect ctor params, setter params and process // TODO then handle single, collection and bean for both properties.put(paramName, constructorParamInputParameter); paramIndex++; // increase for each @JsonProperty } } } Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator " + constructor.getName() + " are annotated with @JsonProperty"); } // collect supported properties from setters // TODO support Option provider by other method args? final BeanInfo beanInfo = Introspector.getBeanInfo(valueType); final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); // TODO collection and map // TODO distinguish which properties should be printed as supported - now just setters for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { final Method writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod == null) { continue; } // TODO: the property name must be a valid URI - need to check context for terms? String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyDescriptor.getName()); MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0); ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter, propertyValue); properties.put(propertyName, propertySetterInputParameter); } // write all supported properties // TODO we are using the annotatedParameter.parameterName but should use the key of properties here: for (ActionInputParameter annotatedParameter : properties.values()) { String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName() : propertyPath + '.' + annotatedParameter.getParameterName(); if (DataType.isSingleValueType(annotatedParameter.getParameterType())) { final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters); if (rootParameter.isIncluded(nextPropertyPathLevel) && !rootParameter.isExcluded(nextPropertyPathLevel)) { writeSupportedProperty(jgen, currentVocab, annotatedParameter, annotatedParameter.getParameterName(), possiblePropertyValues); } // TODO collections? // } else if (DataType.isArrayOrCollection(parameterType)) { // Object[] callValues = rootParameter.getValues(); // int items = callValues.length; // for (int i = 0; i < items; i++) { // Object value; // if (i < callValues.length) { // value = callValues[i]; // } else { // value = null; // } // recurseSupportedProperties(jgen, currentVocab, rootParameter // .getParameterType(), // allRootParameters, rootParameter, value); // } } else { jgen.writeStartObject(); jgen.writeStringField("hydra:property", annotatedParameter.getParameterName()); // TODO: is the property required -> for bean props we need the Access annotation to express that jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes", LdContextFactory.HTTP_SCHEMA_ORG, "schema:")); Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class); String subClass; if (expose != null) { subClass = expose.value(); } else { subClass = annotatedParameter.getParameterType().getSimpleName(); } jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf", "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass); jgen.writeArrayFieldStart("hydra:supportedProperty"); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, annotatedParameter.getParameterName()); recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(), allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel); jgen.writeEndArray(); jgen.writeEndObject(); jgen.writeEndObject(); } } }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
protected void marshallSequenceFlow(SequenceFlow sequenceFlow, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset) throws JsonGenerationException, IOException { // dont marshal "dangling" sequence flow..better to just omit than fail if (sequenceFlow.getSourceRef() == null || sequenceFlow.getTargetRef() == null) { return;/*from w w w . j a v a 2s .c o m*/ } Map<String, Object> properties = new LinkedHashMap<String, Object>(); // check null for sequence flow name if (sequenceFlow.getName() != null && !"".equals(sequenceFlow.getName())) { properties.put("name", unescapeXml(sequenceFlow.getName())); } else { properties.put("name", ""); } // overwrite name if elementname extension element is present String elementName = Utils.getMetaDataValue(sequenceFlow.getExtensionValues(), "elementname"); if (elementName != null) { properties.put("name", elementName); } if (sequenceFlow.getDocumentation() != null && sequenceFlow.getDocumentation().size() > 0) { properties.put("documentation", sequenceFlow.getDocumentation().get(0).getText()); } if (sequenceFlow.isIsImmediate()) { properties.put("isimmediate", "true"); } else { properties.put("isimmediate", "false"); } Expression conditionExpression = sequenceFlow.getConditionExpression(); try { if (conditionExpression instanceof FormalExpression) { if (((FormalExpression) conditionExpression).getBody() != null) { properties.put("conditionexpression", ((FormalExpression) conditionExpression).getBody().replaceAll("\n", "\\\\n")); } if (((FormalExpression) conditionExpression).getLanguage() != null) { String cd = ((FormalExpression) conditionExpression).getLanguage(); String cdStr = getScriptLanguageFormat(cd, "mvel"); properties.put("conditionexpressionlanguage", cdStr); } } } catch (Exception e) { _logger.info("Could not find conditionexpression for : " + conditionExpression); } boolean foundBgColor = false; boolean foundBrColor = false; boolean foundFontColor = false; boolean foundSelectable = false; Iterator<FeatureMap.Entry> iter = sequenceFlow.getAnyAttribute().iterator(); while (iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if (entry.getEStructuralFeature().getName().equals("priority")) { String priorityStr = String.valueOf(entry.getValue()); if (priorityStr != null) { try { Integer priorityInt = Integer.parseInt(priorityStr); if (priorityInt >= 1) { properties.put("priority", entry.getValue()); } else { _logger.error("Priority must be equal or greater than 1."); } } catch (NumberFormatException e) { _logger.error("Priority must be a number."); } } } if (entry.getEStructuralFeature().getName().equals("background-color") || entry.getEStructuralFeature().getName().equals("bgcolor")) { properties.put("bgcolor", entry.getValue()); foundBgColor = true; } if (entry.getEStructuralFeature().getName().equals("border-color") || entry.getEStructuralFeature().getName().equals("bordercolor")) { properties.put("bordercolor", entry.getValue()); foundBrColor = true; } if (entry.getEStructuralFeature().getName().equals("fontsize")) { properties.put("fontsize", entry.getValue()); foundBrColor = true; } if (entry.getEStructuralFeature().getName().equals("color") || entry.getEStructuralFeature().getName().equals("fontcolor")) { properties.put("fontcolor", entry.getValue()); foundFontColor = true; } if (entry.getEStructuralFeature().getName().equals("selectable")) { properties.put("isselectable", entry.getValue()); foundSelectable = true; } } if (!foundBgColor) { properties.put("bgcolor", defaultSequenceflowColor); } if (!foundBrColor) { properties.put("bordercolor", defaultSequenceflowColor); } if (!foundFontColor) { properties.put("fontcolor", defaultSequenceflowColor); } if (!foundSelectable) { properties.put("isselectable", "true"); } // simulation properties setSimulationProperties(sequenceFlow.getId(), properties); marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); generator.writeObjectField("id", "SequenceFlow"); generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); generator.writeStartObject(); generator.writeObjectField("resourceId", sequenceFlow.getTargetRef().getId()); generator.writeEndObject(); generator.writeEndArray(); Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getSourceRef())).getBounds(); Bounds targetBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getTargetRef())).getBounds(); 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, sequenceFlow)).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(); } generator.writeStartObject(); generator.writeObjectField("x", targetBounds.getWidth() / 2); generator.writeObjectField("y", targetBounds.getHeight() / 2); generator.writeEndObject(); generator.writeEndArray(); }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
protected void marshallSubProcess(SubProcess subProcess, BPMNPlane plane, JsonGenerator generator, float xOffset, float yOffset, String preProcessingData, Definitions def, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException { Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties); if (subProcess.getName() != null) { properties.put("name", unescapeXml(subProcess.getName())); } else {/*from w ww.j ava 2 s. c om*/ properties.put("name", ""); } // overwrite name if elementname extension element is present String elementName = Utils.getMetaDataValue(subProcess.getExtensionValues(), "elementname"); if (elementName != null) { properties.put("name", elementName); } if (subProcess.getDocumentation() != null && subProcess.getDocumentation().size() > 0) { properties.put("documentation", subProcess.getDocumentation().get(0).getText()); } if (subProcess instanceof AdHocSubProcess) { AdHocSubProcess ahsp = (AdHocSubProcess) subProcess; if (ahsp.getOrdering().equals(AdHocOrdering.PARALLEL)) { properties.put("adhocordering", "Parallel"); } else if (ahsp.getOrdering().equals(AdHocOrdering.SEQUENTIAL)) { properties.put("adhocordering", "Sequential"); } else { // default to parallel properties.put("adhocordering", "Parallel"); } if (ahsp.getCompletionCondition() != null) { try { FormalExpression completionExpression = (FormalExpression) ahsp.getCompletionCondition(); if (completionExpression != null) { properties.put("adhoccompletioncondition", completionExpression.getBody().replaceAll("\n", "\\\\n")); if (completionExpression.getLanguage() != null) { String completionLanguage = getScriptLanguageFormat(completionExpression.getLanguage()); properties.put("script_language", completionLanguage); } } } catch (Exception e) { _logger.info("Could not find adhoccompletioncondition for: " + ahsp); } } final String customActivationCondition = Utils.getMetaDataValue(ahsp.getExtensionValues(), "customActivationCondition"); if (customActivationCondition != null && customActivationCondition.length() > 0) { properties.put("adhocactivationcondition", customActivationCondition); } } // custom async String customAsyncMetaData = Utils.getMetaDataValue(subProcess.getExtensionValues(), "customAsync"); String customAsync = (customAsyncMetaData != null && customAsyncMetaData.length() > 0) ? customAsyncMetaData : "false"; properties.put("isasync", customAsync); // custom SLA due date marshalCustomSLADueDateMetadata(subProcess, properties); // data inputs marshallDataInputSet(subProcess, properties); // data outputs marshallDataOutputSet(subProcess, properties); // assignments StringBuilder associationBuff = new StringBuilder(); List<DataInputAssociation> inputAssociations = subProcess.getDataInputAssociations(); List<DataOutputAssociation> outputAssociations = subProcess.getDataOutputAssociations(); marshallDataInputAssociations(associationBuff, inputAssociations); marshallDataOutputAssociations(associationBuff, outputAssociations); String assignmentString = associationBuff.toString(); if (assignmentString.endsWith(",")) { assignmentString = assignmentString.substring(0, assignmentString.length() - 1); } properties.put("assignments", assignmentString); // on-entry and on-exit actions marshallEntryExitActions(subProcess, properties); // loop characteristics boolean haveValidLoopCharacteristics = false; if (subProcess.getLoopCharacteristics() != null && subProcess.getLoopCharacteristics() instanceof MultiInstanceLoopCharacteristics) { haveValidLoopCharacteristics = true; properties.put("mitrigger", "true"); MultiInstanceLoopCharacteristics taskmi = (MultiInstanceLoopCharacteristics) subProcess .getLoopCharacteristics(); if (taskmi.getLoopDataInputRef() != null) { ItemAwareElement iedatainput = taskmi.getLoopDataInputRef(); List<DataInputAssociation> taskInputAssociations = subProcess.getDataInputAssociations(); for (DataInputAssociation dia : taskInputAssociations) { if (dia.getTargetRef().equals(iedatainput)) { properties.put("multipleinstancecollectioninput", dia.getSourceRef().get(0).getId()); break; } } } if (taskmi.getLoopDataOutputRef() != null) { ItemAwareElement iedataoutput = taskmi.getLoopDataOutputRef(); List<DataOutputAssociation> taskOutputAssociations = subProcess.getDataOutputAssociations(); for (DataOutputAssociation dout : taskOutputAssociations) { if (dout.getSourceRef().get(0).equals(iedataoutput)) { properties.put("multipleinstancecollectionoutput", dout.getTargetRef().getId()); break; } } } if (taskmi.getInputDataItem() != null) { List<DataInput> taskDataInputs = subProcess.getIoSpecification().getDataInputs(); for (DataInput din : taskDataInputs) { if (din.getItemSubjectRef() == null) { // for backward compatibility as the where only input supported properties.put("multipleinstancedatainput", taskmi.getInputDataItem().getId()); } if (din.getItemSubjectRef() != null && din.getItemSubjectRef().getId() .equals(taskmi.getInputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedatainput", din.getName()); break; } } } if (taskmi.getOutputDataItem() != null) { List<DataOutput> taskDataOutputs = subProcess.getIoSpecification().getDataOutputs(); for (DataOutput dout : taskDataOutputs) { if (dout.getItemSubjectRef() == null) { properties.put("multipleinstancedataoutput", taskmi.getOutputDataItem().getId()); break; } if (dout.getItemSubjectRef() != null && dout.getItemSubjectRef().getId() .equals(taskmi.getOutputDataItem().getItemSubjectRef().getId())) { properties.put("multipleinstancedataoutput", dout.getName()); break; } } } if (taskmi.getCompletionCondition() != null) { try { if (taskmi.getCompletionCondition() instanceof FormalExpression) { properties.put("multipleinstancecompletioncondition", ((FormalExpression) taskmi.getCompletionCondition()).getBody()); } } catch (Exception e) { _logger.info("Could not find multipleinstancecompletioncondition for : " + taskmi); } } } // properties List<Property> processProperties = subProcess.getProperties(); if (processProperties != null && processProperties.size() > 0) { String propVal = ""; for (int i = 0; i < processProperties.size(); i++) { Property p = processProperties.get(i); String pKPI = Utils.getMetaDataValue(p.getExtensionValues(), "customKPI"); propVal += p.getId(); // check the structureRef value if (p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) { propVal += ":" + p.getItemSubjectRef().getStructureRef(); } if (pKPI != null && pKPI.length() > 0) { propVal += ":" + pKPI; } if (i != processProperties.size() - 1) { propVal += ","; } } properties.put("vardefs", propVal); } // simulation properties setSimulationProperties(subProcess.getId(), properties); marshallProperties(properties, generator); generator.writeObjectFieldStart("stencil"); if (subProcess instanceof AdHocSubProcess) { generator.writeObjectField("id", "AdHocSubprocess"); } else { if (subProcess.isTriggeredByEvent()) { generator.writeObjectField("id", "EventSubprocess"); } else { if (haveValidLoopCharacteristics) { generator.writeObjectField("id", "MultipleInstanceSubprocess"); } else { generator.writeObjectField("id", "Subprocess"); } } } generator.writeEndObject(); generator.writeArrayFieldStart("childShapes"); Bounds bounds = ((BPMNShape) findDiagramElement(plane, subProcess)).getBounds(); for (FlowElement flowElement : subProcess.getFlowElements()) { if (coordianteManipulation) { marshallFlowElement(flowElement, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def); } } for (Artifact artifact : subProcess.getArtifacts()) { if (coordianteManipulation) { marshallArtifact(artifact, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def); } else { marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def); } } generator.writeEndArray(); generator.writeArrayFieldStart("outgoing"); for (BoundaryEvent boundaryEvent : subProcess.getBoundaryEventRefs()) { generator.writeStartObject(); generator.writeObjectField("resourceId", boundaryEvent.getId()); generator.writeEndObject(); } for (SequenceFlow outgoing : subProcess.getOutgoing()) { generator.writeStartObject(); generator.writeObjectField("resourceId", outgoing.getId()); generator.writeEndObject(); } Process process = (Process) plane.getBpmnElement(); writeAssociations(process, subProcess.getId(), generator); // subprocess boundary events List<BoundaryEvent> boundaryEvents = new ArrayList<BoundaryEvent>(); findBoundaryEvents(process, boundaryEvents); for (BoundaryEvent be : boundaryEvents) { if (be.getAttachedToRef().getId().equals(subProcess.getId())) { generator.writeStartObject(); generator.writeObjectField("resourceId", be.getId()); generator.writeEndObject(); } } 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(); }
From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java
protected void marshallDefinitions(Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException { try {//from w w w .j av a 2s . c om generator.writeStartObject(); generator.writeObjectField("resourceId", def.getId()); /** * "properties":{"name":"", * "documentation":"", * "auditing":"", * "monitoring":"", * "executable":"true", * "package":"com.sample", * "vardefs":"a,b,c,d", * "lanes" : "a,b,c", * "id":"", * "version":"", * "author":"", * "language":"", * "namespaces":"", * "targetnamespace":"", * "expressionlanguage":"", * "typelanguage":"", * "creationdate":"", * "modificationdate":"" * } */ Map<String, Object> props = new LinkedHashMap<String, Object>(); props.put("namespaces", ""); //props.put("targetnamespace", def.getTargetNamespace()); props.put("targetnamespace", "http://www.omg.org/bpmn20"); props.put("typelanguage", def.getTypeLanguage()); props.put("name", unescapeXml(def.getName())); props.put("id", def.getId()); props.put("expressionlanguage", def.getExpressionLanguage()); props.put("exporter", StringUtils.isNotEmpty(def.getExporter()) ? def.getExporter() : ""); props.put("exporterversion", StringUtils.isNotEmpty(def.getExporterVersion()) ? def.getExporterVersion() : ""); // backwards compat for BZ 1048191 if (def.getDocumentation() != null && def.getDocumentation().size() > 0) { props.put("documentation", def.getDocumentation().get(0).getText()); } for (RootElement rootElement : def.getRootElements()) { if (rootElement instanceof Process) { // have to wait for process node to finish properties and stencil marshalling props.put("executable", ((Process) rootElement).isIsExecutable() + ""); props.put("id", rootElement.getId()); if (rootElement.getDocumentation() != null && rootElement.getDocumentation().size() > 0) { props.put("documentation", rootElement.getDocumentation().get(0).getText()); } Process pr = (Process) rootElement; if (pr.getName() != null && pr.getName().length() > 0) { props.put("processn", unescapeXml(((Process) rootElement).getName())); } List<Property> processProperties = ((Process) rootElement).getProperties(); if (processProperties != null && processProperties.size() > 0) { String propVal = ""; for (int i = 0; i < processProperties.size(); i++) { Property p = processProperties.get(i); String pKPI = Utils.getMetaDataValue(p.getExtensionValues(), "customKPI"); propVal += p.getId(); // check the structureRef value if (p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) { propVal += ":" + p.getItemSubjectRef().getStructureRef(); } if (pKPI != null && pKPI.length() > 0) { propVal += ":" + pKPI; } if (i != processProperties.size() - 1) { propVal += ","; } } props.put("vardefs", propVal); } // packageName and version and adHoc are jbpm-specific extension attribute Iterator<FeatureMap.Entry> iter = ((Process) rootElement).getAnyAttribute().iterator(); while (iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if (entry.getEStructuralFeature().getName().equals("packageName")) { props.put("package", entry.getValue()); } if (entry.getEStructuralFeature().getName().equals("version")) { props.put("version", entry.getValue()); } if (entry.getEStructuralFeature().getName().equals("adHoc")) { props.put("adhocprocess", entry.getValue()); } } // process imports, custom description and globals extension elements String allImports = ""; if ((rootElement).getExtensionValues() != null && (rootElement).getExtensionValues().size() > 0) { String importsStr = ""; String globalsStr = ""; for (ExtensionAttributeValue extattrval : rootElement.getExtensionValues()) { FeatureMap extensionElements = extattrval.getValue(); @SuppressWarnings("unchecked") List<ImportType> importExtensions = (List<ImportType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__IMPORT, true); @SuppressWarnings("unchecked") List<GlobalType> globalExtensions = (List<GlobalType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__GLOBAL, true); List<MetaDataType> metadataExtensions = (List<MetaDataType>) extensionElements .get(DroolsPackage.Literals.DOCUMENT_ROOT__META_DATA, true); for (ImportType importType : importExtensions) { importsStr += importType.getName(); importsStr += "|default,"; } for (GlobalType globalType : globalExtensions) { globalsStr += (globalType.getIdentifier() + ":" + globalType.getType()); globalsStr += ","; } for (MetaDataType metaType : metadataExtensions) { if (metaType.getName().equals("customDescription")) { props.put("customdescription", metaType.getMetaValue()); } else if (metaType.getName().equals("customCaseIdPrefix")) { props.put("customcaseidprefix", metaType.getMetaValue()); } else if (metaType.getName().equals("customCaseRoles")) { props.put("customcaseroles", metaType.getMetaValue()); } else if (metaType.getName().equals("customSLADueDate")) { props.put("customsladuedate", metaType.getMetaValue()); } else { props.put(metaType.getName(), metaType.getMetaValue()); } } } allImports += importsStr; if (globalsStr.length() > 0) { if (globalsStr.endsWith(",")) { globalsStr = globalsStr.substring(0, globalsStr.length() - 1); } props.put("globals", globalsStr); } } // definitions imports (wsdl) List<org.eclipse.bpmn2.Import> wsdlImports = def.getImports(); if (wsdlImports != null) { for (org.eclipse.bpmn2.Import imp : wsdlImports) { allImports += imp.getLocation() + "|" + imp.getNamespace() + "|wsdl,"; } } if (allImports.endsWith(",")) { allImports = allImports.substring(0, allImports.length() - 1); } props.put("imports", allImports); // simulation if (_simulationScenario != null && _simulationScenario.getScenarioParameters() != null) { props.put("currency", _simulationScenario.getScenarioParameters().getBaseCurrencyUnit() == null ? "" : _simulationScenario.getScenarioParameters().getBaseCurrencyUnit()); props.put("timeunit", _simulationScenario.getScenarioParameters().getBaseTimeUnit().getName()); } marshallProperties(props, generator); marshallStencil("BPMNDiagram", generator); linkSequenceFlows(((Process) rootElement).getFlowElements()); marshallProcess((Process) rootElement, def, generator, preProcessingData); } else if (rootElement instanceof Interface) { // TODO } else if (rootElement instanceof ItemDefinition) { // TODO } else if (rootElement instanceof Resource) { // TODO } else if (rootElement instanceof Error) { // TODO } else if (rootElement instanceof Message) { // TODO } else if (rootElement instanceof Signal) { // TODO } else if (rootElement instanceof Escalation) { // TODO } else if (rootElement instanceof Collaboration) { } else { _logger.warn("Unknown root element " + rootElement + ". This element will not be parsed."); } } generator.writeObjectFieldStart("stencilset"); generator.writeObjectField("url", this.profile.getStencilSetURL()); generator.writeObjectField("namespace", this.profile.getStencilSetNamespaceURL()); generator.writeEndObject(); generator.writeArrayFieldStart("ssextensions"); generator.writeObject(this.profile.getStencilSetExtensionURL()); generator.writeEndArray(); generator.writeEndObject(); } finally { _diagramElements.clear(); } }