com.fasterxml.jackson.databind.node.ObjectNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileWatchResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/get-events")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getEvent(@QueryParam("path") String path) throws Exception {
    final Exchange exchange = consumerTemplate.receiveNoWait("file-watch://" + path);
    if (exchange == null) {
        return Response.noContent().build();
    } else {
        final Message message = exchange.getMessage();
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode node = mapper.createObjectNode();
        node.put("type", message.getHeader(FileWatchComponent.EVENT_TYPE_HEADER, FileEventEnum.class).toString());
        node.put("path", message.getHeader("CamelFileAbsolutePath", String.class));
        return Response
                .ok()
                .entity(node)
                .build();
    }
}
 
Example #2
Source File: ProxyInvocationHandler.java    From beam with Apache License 2.0 6 votes vote down vote up
@Override
public PipelineOptions deserialize(JsonParser jp, DeserializationContext ctxt)
    throws IOException, JsonProcessingException {
  ObjectNode objectNode = jp.readValueAsTree();
  JsonNode rawOptionsNode = objectNode.get("options");

  Map<String, JsonNode> fields = Maps.newHashMap();
  if (rawOptionsNode != null && !rawOptionsNode.isNull()) {
    ObjectNode optionsNode = (ObjectNode) rawOptionsNode;
    for (Iterator<Map.Entry<String, JsonNode>> iterator = optionsNode.fields();
        iterator != null && iterator.hasNext(); ) {
      Map.Entry<String, JsonNode> field = iterator.next();
      fields.put(field.getKey(), field.getValue());
    }
  }

  PipelineOptions options =
      new ProxyInvocationHandler(Maps.newHashMap(), fields).as(PipelineOptions.class);
  ValueProvider.RuntimeValueProvider.setRuntimeOptions(options);
  return options;
}
 
Example #3
Source File: MaterializerServiceEndpoints.java    From tasmo with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes ("application/json")
@Path ("/writtenEvents")
public Response writtenEvents(List<ObjectNode> events) {
    try {
        LOG.startTimer("writeEvents");
        LOG.inc("ingressed>total", events.size());
        for (ObjectNode event : events) {
            // TODO ensure doneYet tracking is disabled.
        }
        ingressWrittenEvents.callback(events);
        LOG.inc("ingressed>success", events.size());
        return ResponseHelper.INSTANCE.jsonResponse("success");
    } catch (Exception x) {
        LOG.inc("ingressed>errors");
        LOG.error("failed to ingress because:", x);
        return ResponseHelper.INSTANCE.errorResponse(null, x);
    } finally {
        LOG.stopTimer("writeEvents");
    }
}
 
Example #4
Source File: K8sIpamWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Requests for allocating a unique IP address of the given network ID.
 *
 * @param netId     network identifier
 * @return 200 OK with the serialized IPAM JSON string
 * @onos.rsModel K8sIpam
 */
@GET
@Path("{netId}")
@Produces(MediaType.APPLICATION_JSON)
public Response allocateIp(@PathParam("netId") String netId) {
    log.trace("Received IP allocation request of network " + netId);

    K8sNetwork network =
            nullIsNotFound(networkService.network(netId), NETWORK_ID_NOT_FOUND);

    IpAddress ip =
            nullIsNotFound(ipamService.allocateIp(network.networkId()), IP_NOT_ALLOCATED);

    ObjectNode root = mapper().createObjectNode();
    String ipamId = network.networkId() + "-" + ip.toString();
    K8sIpam ipam = new DefaultK8sIpam(ipamId, ip, network.networkId());
    root.set(IPAM, codec(K8sIpam.class).encode(ipam, this));

    return ok(root).build();
}
 
Example #5
Source File: VirtualNetworkWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the virtual network host from the JSON input stream.
 *
 * @param networkId network identifier
 * @param stream    virtual host JSON stream
 * @return 204 NO CONTENT
 * @onos.rsModel VirtualHost
 */
@DELETE
@Path("{networkId}/hosts")
@Consumes(MediaType.APPLICATION_JSON)
public Response removeVirtualHost(@PathParam("networkId") long networkId,
                                  InputStream stream) {
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        JsonNode specifiedNetworkId = jsonTree.get("networkId");
        if (specifiedNetworkId != null &&
                specifiedNetworkId.asLong() != (networkId)) {
            throw new IllegalArgumentException(INVALID_FIELD + "networkId");
        }
        final VirtualHost vhostReq = codec(VirtualHost.class).decode(jsonTree, this);
        vnetAdminService.removeVirtualHost(vhostReq.networkId(), vhostReq.id());
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    return Response.noContent().build();
}
 
Example #6
Source File: DefaultProcessDefinitionLocalizationManager.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void localize(ProcessDefinition processDefinition, String locale, boolean withLocalizationFallback) {
    ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) processDefinition;
    processDefinitionEntity.setLocalizedName(null);
    processDefinitionEntity.setLocalizedDescription(null);

    if (locale != null) {
        ObjectNode languageNode = BpmnOverrideContext.getLocalizationElementProperties(locale, processDefinitionEntity.getKey(), processDefinition.getId(), withLocalizationFallback);
        if (languageNode != null) {
            JsonNode languageNameNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_NAME);
            if (languageNameNode != null && !languageNameNode.isNull()) {
                processDefinitionEntity.setLocalizedName(languageNameNode.asText());
            }

            JsonNode languageDescriptionNode = languageNode.get(DynamicBpmnConstants.LOCALIZATION_DESCRIPTION);
            if (languageDescriptionNode != null && !languageDescriptionNode.isNull()) {
                processDefinitionEntity.setLocalizedDescription(languageDescriptionNode.asText());
            }
        }
    }
}
 
Example #7
Source File: JdbcComponentTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSchema_wrongSql() throws java.io.IOException {
    // given

    UiSpecsPropertiesDto datasetConnectionInfo = new UiSpecsPropertiesDto();
    datasetConnectionInfo.setProperties(mapper.readValue(
            getClass().getResourceAsStream("jdbc_data_set_properties_no_schema_wrong_table_name.json"), ObjectNode.class));
    datasetConnectionInfo.setDependencies(singletonList(getJdbcDataStoreProperties()));

    // when
    final Response responseApiError = given().body(datasetConnectionInfo)
                                 .contentType(APPLICATION_JSON_UTF8_VALUE) //
                                 .accept(APPLICATION_JSON_UTF8_VALUE)
                                 .post(getVersionPrefix() + "/runtimes/schema");
    responseApiError.then().statusCode(400).log().ifValidationFails();
    ApiError response = responseApiError.as(ApiError.class);

    // then
    assertEquals("TCOMP_JDBC_SQL_SYNTAX_ERROR", response.getCode());
    assertEquals("Table/View 'TOTO' does not exist.", response.getMessage());
}
 
Example #8
Source File: ModelEditorResource.java    From plumdo-work with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "/models/{modelId}/editor", name = "模型设计器保存模型")
@ResponseStatus(value = HttpStatus.OK)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void saveModelEditor(@PathVariable String modelId, @RequestBody ModelEditorJsonRequest values) {
    Model model = getModel(modelId, values.isNewVersion());
    if (!model.getKey().equals(values.getKey())) {
        checkModelKeyExists(values.getKey());
        managementService.executeCommand(new UpdateModelKeyCmd(modelId, values.getKey()));
    }
    try {
        ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
        modelJson.put("name", values.getName());
        modelJson.put("description", values.getDescription());
        model.setMetaInfo(modelJson.toString());
        model.setName(values.getName());
        model.setKey(values.getKey());
        repositoryService.saveModel(model);
        managementService.executeCommand(new SaveModelEditorCmd(model.getId(), values.getJsonXml()));
    } catch (Exception e) {
        logger.error("保存模型设计信息异常", e);
        exceptionFactory.throwDefinedException(ErrorConstant.MODEL_GET_EDITOR_ERROR, e.getMessage());
    }
}
 
Example #9
Source File: SinglePointToMultiPointIntentCodec.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public ObjectNode encode(SinglePointToMultiPointIntent intent, CodecContext context) {
    checkNotNull(intent, "Single Point to Multi Point intent cannot be null");

    final JsonCodec<ConnectivityIntent> connectivityIntentCodec =
            context.codec(ConnectivityIntent.class);
    final ObjectNode result = connectivityIntentCodec.encode(intent, context);

    final JsonCodec<ConnectPoint> connectPointCodec =
            context.codec(ConnectPoint.class);
    final ObjectNode ingress =
            connectPointCodec.encode(intent.ingressPoint(), context);

    final ArrayNode jsonconnectPoints = context.mapper().createArrayNode();

    if (intent.egressPoints() != null) {
        for (final ConnectPoint cp : intent.egressPoints()) {
            jsonconnectPoints.add(connectPointCodec.encode(cp, context));
        }
        result.set(EGRESS_POINT, jsonconnectPoints);
    }
    result.set(INGRESS_POINT, ingress);

    return result;
}
 
Example #10
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 5 votes vote down vote up
private void genCatalog(File dstDirectory, ObjectNode root) {
    File swaggerCfg = new File(dstDirectory, JSON_FILE);
    if (dstDirectory.exists() || dstDirectory.mkdirs()) {
        try (FileWriter fw = new FileWriter(swaggerCfg);
             PrintWriter pw = new PrintWriter(fw)) {
            pw.println(root.toString());
        } catch (IOException e) {
            throw new RuntimeException("Unable to write " + JSON_FILE, e);
        }
    } else {
        throw new RuntimeException("Unable to create " + dstDirectory);
    }
}
 
Example #11
Source File: VersionMigratorChain.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apiman.manager.api.migrator.IVersionMigrator#migrateRole(com.fasterxml.jackson.databind.node.ObjectNode)
 */
@Override
public void migrateRole(ObjectNode node) {
    for (IVersionMigrator migrator : migrators) {
        migrator.migrateRole(node);
    }
}
 
Example #12
Source File: TokenAuthenticator.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a SubjectAccessReview object used to request if a user has a certain permission or not.
 *
 * @param namespace the namespace
 * @param verb      the requested permission
 *
 * @return JSON text representation of the SubjectAccessReview object
 */
private String generateSubjectAccessReview(String namespace, String verb, String resource) {
    ObjectNode objectNode = objectMapper.createObjectNode();
    objectNode.put("apiVersion", "v1");
    objectNode.put("kind", KIND);
    objectNode.put("resource", resource);
    objectNode.put("verb", verb);
    objectNode.put("namespace", namespace);
    return objectNode.toString();
}
 
Example #13
Source File: FileTemplateServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void checkPropertiesTemplateValue(CandidateDTO dto) {

    Map<String, ObjectNode> nameDetailMapping = Maps.newHashMap();
    Map<String, String> nameTypeMapping = Maps.newHashMap();
    parseJsonTemp(dto.getTemplateDetail(), nameTypeMapping, nameDetailMapping);
    if (!Strings.isNullOrEmpty(dto.getInheritGroupId()) && !Strings.isNullOrEmpty(dto.getInheritDataId())
            && !Strings.isNullOrEmpty(dto.getInheritProfile())) {//继承文件模板校验
        ConfigMeta parentMeta = new ConfigMeta(dto.getInheritGroupId(), dto.getInheritDataId(),
                dto.getInheritProfile());
        Optional<String> parentTempDetail = getPropertiesTemplate(parentMeta);
        Map<String, ObjectNode> parentNameDetailMapping = Maps.newHashMap();
        Map<String, String> parentNameTypeMapping = Maps.newHashMap();
        parentTempDetail.ifPresent(s -> FileTemplateServiceImpl.this.parseJsonTemp(s, parentNameTypeMapping, parentNameDetailMapping));
        templateCheckerService.checkInheritConstraint(dto.getData(), parentNameDetailMapping, parentNameTypeMapping);
        if (parentTempDetail.isPresent() && !parentNameDetailMapping.isEmpty() && !parentNameTypeMapping.isEmpty()) {
            if (!notHasPropertiesTemplate(dto) || !notHasPropertiesTemplate(dto.getInheritDataId(), parentTempDetail.get())) {
                templateCheckerService.checkInheritableProperties(dto.getData(), nameDetailMapping, nameTypeMapping, parentNameDetailMapping, parentNameTypeMapping);// 父模板优先级高
            }
        } else {
            templateCheckerService.checkProperties(dto.getData(), nameDetailMapping, nameTypeMapping);
        }
    } else {
        if (!notHasPropertiesTemplate(dto)) {
            templateCheckerService.checkProperties(dto.getData(), nameDetailMapping, nameTypeMapping);
        }
    }
}
 
Example #14
Source File: HostLocationCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectNode encode(HostLocation hostLocation, CodecContext context) {
    checkNotNull(hostLocation, "Host location cannot be null");
    return context.mapper().createObjectNode()
            .put(ELEMENT_ID, hostLocation.elementId().toString())
            .put(PORT, hostLocation.port().toString());
}
 
Example #15
Source File: RemoteMepEntryCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes the RemoteMepEntry entity into JSON.
 *
 * @param remoteMepEntry  RemoteMepEntry to encode
 * @param context encoding context
 * @return JSON node
 * @throws java.lang.UnsupportedOperationException if the codec does not
 *                                                 support encode operations
 */
@Override
public ObjectNode encode(RemoteMepEntry remoteMepEntry, CodecContext context) {
    checkNotNull(remoteMepEntry, "Mep cannot be null");
    ObjectNode result = context.mapper().createObjectNode()
            .put("remoteMepId", remoteMepEntry.remoteMepId().toString())
            .put("remoteMepState", remoteMepEntry.state().name())
            .put("rdi", remoteMepEntry.rdi());

    if (remoteMepEntry.failedOrOkTime() != null) {
        result = result.put("failedOrOkTime",
                remoteMepEntry.failedOrOkTime().toString());
    }

    if (remoteMepEntry.macAddress() != null) {
        result = result.put("macAddress", remoteMepEntry.macAddress().toString());
    }

    if (remoteMepEntry.portStatusTlvType() != null) {
        result = result.put("portStatusTlvType",
                remoteMepEntry.portStatusTlvType().name());
    }
    if (remoteMepEntry.interfaceStatusTlvType() != null) {
        result = result.put("interfaceStatusTlvType",
                remoteMepEntry.interfaceStatusTlvType().name());
    }
    if (remoteMepEntry.senderIdTlvType() != null) {
        result = result.put("senderIdTlvType",
                remoteMepEntry.senderIdTlvType().name());
    }

    return result;
}
 
Example #16
Source File: AbstractActivityParser.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
protected ObjectNode parseAndAddOutputPortDefinition(
			ActivityPortDefinitionBean portBean, Configuration configuration,
			Activity activity) {
		ObjectNode configResource = (ObjectNode) configuration.getJson();
		OutputActivityPort outputPort = new OutputActivityPort();

		outputPort.setName(getPortElement(portBean, "name", String.class));
		outputPort.setParent(activity);

		BigInteger depth = getPortElement(portBean, "depth", BigInteger.class);
		if (depth != null)
			outputPort.setDepth(depth.intValue());
		
		BigInteger granularDepth = getPortElement(portBean, "granularDepth",
				BigInteger.class);
		if (granularDepth != null)
			outputPort.setGranularDepth(granularDepth.intValue());
		
		ObjectNode portConfig = configResource.objectNode();
//		PropertyResource portConfig = configResource.addPropertyAsNewResource(
//				Scufl2Tools.PORT_DEFINITION.resolve("#outputPortDefinition"),
//				Scufl2Tools.PORT_DEFINITION.resolve("#OutputPortDefinition"));

		@SuppressWarnings("unused")
		URI portUri = new URITools().relativeUriForBean(outputPort, configuration);
//		portConfig.addPropertyReference(Scufl2Tools.PORT_DEFINITION.resolve("#definesOutputPort"), portUri);

	      // Legacy duplication of port details for XMLSplitter activities
        portConfig.put("name", outputPort.getName());
        portConfig.put("depth", outputPort.getDepth());
        portConfig.put("granularDepth", outputPort.getDepth());
		
		parseMimeTypes(portBean, portConfig);
		return portConfig;
	}
 
Example #17
Source File: SchemaTypeUtil.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public static Schema createSchemaByType(ObjectNode node){
    if(node == null) {
        return new Schema();
    }
    final String type = getNodeValue(node, TYPE);
    if(StringUtils.isBlank(type)) {
        return new Schema();
    }
    final String format = getNodeValue(node, FORMAT);

    return createSchema(type, format);
}
 
Example #18
Source File: WebServiceTaskTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
@Deployment
public void testJsonBeanWithArrayVariableMultiInstanceLoop() throws Exception {

    assertThat(webServiceMock.getCount()).isEqualTo(-1);

    processEngineConfiguration.addWsEndpointAddress(
            new QName("http://webservice.impl.engine.flowable.org/", "CounterImplPort"),
            new URL(WEBSERVICE_MOCK_ADDRESS));

    final ObjectMapper mapper = this.processEngineConfiguration.getObjectMapper();
    final ObjectNode valuesObj = mapper.createObjectNode();
    final ArrayNode values = valuesObj.putArray("values");
    values.add(12);
    values.add(23);
    values.add(34);

    final Map<String, Object> initVariables = new HashMap<String, Object>();
    initVariables.put("bean", valuesObj);
    ProcessInstance processInstance = runtimeService
            .startProcessInstanceByKey("jsonBeanWithArrayVariableMultiInstanceLoop", initVariables);
    waitForJobExecutorToProcessAllJobs(10000L, 250L);

    // -1 (initial value of counter) + 12 + 23 + 34 = 68
    assertThat(webServiceMock.getCount()).isEqualTo(68);
    assertThat(processInstance.isEnded()).isTrue();
}
 
Example #19
Source File: KVStoreUtil.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
public static KVStoreCollection readFromJsonArray(final ArrayNode list) {
	KVStoreCollection col = new KVStoreCollection();
	for (JsonNode node : list) {
		col.add(readObjectNodeToKVStore((ObjectNode) node));
	}
	return col;
}
 
Example #20
Source File: ModelerController.java    From lemon with Apache License 2.0 5 votes vote down vote up
@RequestMapping("xml2json")
public String xml2json(
        @RequestParam("processDefinitionId") String processDefinitionId)
        throws Exception {
    RepositoryService repositoryService = processEngine
            .getRepositoryService();

    ProcessDefinition processDefinition = repositoryService
            .getProcessDefinition(processDefinitionId);

    Model model = repositoryService.newModel();
    model.setName(processDefinition.getName());
    model.setDeploymentId(processDefinition.getDeploymentId());
    repositoryService.saveModel(model);

    BpmnModel bpmnModel = repositoryService
            .getBpmnModel(processDefinitionId);
    ObjectNode objectNode = new BpmnJsonConverter()
            .convertToJson(bpmnModel);

    String json = objectNode.toString();

    repositoryService.addModelEditorSource(model.getId(),
            json.getBytes("utf-8"));

    return "redirect:/modeler/modeler-list.do";
}
 
Example #21
Source File: MetricsWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Gets stats information of all metrics. Returns array of all information for
 * all metrics.
 *
 * @return 200 OK with metric information as array
 * @onos.rsModel Metrics
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllMetrics() {
    ArrayNode metricsNode = root.putArray("metrics");
    service.getMetrics().forEach((name, metric) -> {
        ObjectNode item = mapper().createObjectNode();
        item.put("name", name);
        item.set("metric", codec(Metric.class).encode(metric, this));
        metricsNode.add(item);
    });

    return ok(root).build();
}
 
Example #22
Source File: FieldDecoderTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void testCountRangeWithValue()
        throws DecodingException {
    ObjectNode json = createField().put(JSONConstants.TYPE, JSONConstants.COUNT_RANGE_TYPE);
    json.putArray(JSONConstants.VALUE).add(COUNT_VALUE_START).add(COUNT_VALUE_END);
    SweField field = checkCommon(json, true);
    assertThat(field.getElement(), is(instanceOf(SweCountRange.class)));
    SweCountRange swe = (SweCountRange) field.getElement();
    assertThat(swe.getValue(), is(notNullValue()));
    assertThat(swe.getValue().getRangeStart(), is(COUNT_VALUE_START));
    assertThat(swe.getValue().getRangeEnd(), is(COUNT_VALUE_END));
}
 
Example #23
Source File: SimpleHttpProvider.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public StreamsResultSet readCurrent() {
  StreamsResultSet current;

  uriBuilder = uriBuilder.setPath(
      String.join("/", uriBuilder.getPath(), configuration.getResource(), configuration.getResourcePostfix())
  );

  URI uri;
  try {
    uri = uriBuilder.build();
  } catch (URISyntaxException ex) {
    uri = null;
  }

  List<ObjectNode> results = execute(uri);

  lock.writeLock().lock();

  for ( ObjectNode item : results ) {
    providerQueue.add(newDatum(item));
  }

  LOGGER.debug("Creating new result set for {} items", providerQueue.size());
  current = new StreamsResultSet(providerQueue);

  return current;
}
 
Example #24
Source File: ImrWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Get the statistics of the monitored intent of a specific application
 * Shows for each intent all the flow entries.
 *
 * @onos.rsModel intentStatsGet
 * @param id Application ID
 * @param name Application Name
 * @return 200 OK
 */
@GET
@Path("intentStats/{id}/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Response getIntentsStats(@PathParam("id") short id, @PathParam("name") String name) {
    ObjectNode root = mapper.createObjectNode();
    imrService = get(IntentMonitorAndRerouteService.class);
    ApplicationId appId = new DefaultApplicationId(id, name);
    root.putArray(ROOT_FIELD_STATISTICS_NAME).addAll(
            getJsonNodesIntentStats(imrService.getStats(appId)));
    return ok(root).build();
}
 
Example #25
Source File: LoadCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectNode encode(Load load, CodecContext context) {
    checkNotNull(load, "Load cannot be null");
    return context.mapper().createObjectNode()
            .put(RATE, load.rate())
            .put(LATEST, load.latest())
            .put(VALID, load.isValid())
            .put(TIME, load.time());
}
 
Example #26
Source File: AsyncHistorySession.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void addHistoricData(String type, ObjectNode data, String tenantId) {
    
    // Different engines can call each other and all generate historical data.
    // To make sure the context of where the data is coming from (and thus being able to process it in the right context),
    // the JobService configuration is stored.
    JobServiceConfiguration jobServiceConfiguration = CommandContextUtil.getJobServiceConfiguration();
  
    addHistoricData(jobServiceConfiguration, type, data, tenantId);
}
 
Example #27
Source File: JsonEventConventions.java    From tasmo with Apache License 2.0 5 votes vote down vote up
public EventType getEventType(ObjectNode eventNode) {
    JsonNode got = eventNode.get(ReservedFields.EVENT_TYPE);
    if (got == null || got.isNull()) {
        return EventType.REGULAR;
    }
    try {
        return mapper.convertValue(got, EventType.class);
    } catch (Exception ex) {
        LOG.debug("Failed to get event type for event: " + eventNode, ex);
        return EventType.REGULAR;
    }
}
 
Example #28
Source File: MappingActionCodecTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the encoding of no mapping action.
 */
@Test
public void noActionTest() {
    final NoMappingAction action = MappingActions.noAction();
    final ObjectNode actionJson = actionCodec.encode(action, context);
    assertThat(actionJson, matchesAction(action));
}
 
Example #29
Source File: GenerateBlockchainConfig.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Write the content of the genesis to the output file.
 *
 * @param directory The directory to write the file to.
 * @param fileName The name of the output file.
 * @param genesis The genesis content.
 * @throws IOException If the genesis file cannot be written or accessed.
 */
private void writeGenesisFile(
    final File directory, final String fileName, final ObjectNode genesis) throws IOException {
  LOG.info("Writing genesis file.");
  Files.write(
      directory.toPath().resolve(fileName),
      JsonUtil.getJson(genesis).getBytes(UTF_8),
      StandardOpenOption.CREATE_NEW);
}
 
Example #30
Source File: SchemaGeneratorCustomDefinitionsTest.java    From jsonschema-generator with Apache License 2.0 5 votes vote down vote up
@Test
@Parameters(source = SchemaVersion.class)
public void testGenerateSchema_CustomInlineStandardDefinition(SchemaVersion schemaVersion) throws Exception {
    CustomDefinitionProviderV2 customDefinitionProvider = new CustomDefinitionProviderV2() {
        @Override
        public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
            if (javaType.getErasedType() == Integer.class) {
                // using SchemaGenerationContext.createStandardDefinition() to avoid endless loop with this custom definition
                ObjectNode standardDefinition = context.createStandardDefinition(context.getTypeContext().resolve(Integer.class), this);
                standardDefinition.put("$comment", "custom override of Integer");
                standardDefinition.put(context.getKeyword(SchemaKeyword.TAG_TITLE), "custom title");
                return new CustomDefinition(standardDefinition);
            }
            return null;
        }
    };
    SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
    configBuilder.forTypesInGeneral()
            .withTitleResolver(_scope -> "type title")
            .withDescriptionResolver(_scope -> "type description")
            .withCustomDefinitionProvider(customDefinitionProvider);
    SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
    JsonNode result = generator.generateSchema(Integer.class);
    Assert.assertEquals(4, result.size());
    Assert.assertEquals(SchemaKeyword.TAG_TYPE_INTEGER.forVersion(schemaVersion),
            result.get(SchemaKeyword.TAG_TYPE.forVersion(schemaVersion)).asText());
    Assert.assertEquals("custom override of Integer", result.get("$comment").asText());
    Assert.assertEquals("custom title", result.get(SchemaKeyword.TAG_TITLE.forVersion(schemaVersion)).asText());
    Assert.assertEquals("type description", result.get(SchemaKeyword.TAG_DESCRIPTION.forVersion(schemaVersion)).asText());
}