org.apache.camel.component.servicenow.ServiceNowConstants Java Examples

The following examples show how to use org.apache.camel.component.servicenow.ServiceNowConstants. 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: ServiceNowMetadataRetrieval.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
protected SyndesisMetadata adapt(CamelContext context, String componentId, String actionId, Map<String, Object> properties, MetaDataExtension.MetaData metadata) {
    if (metadata.getPayload() != null) {
        final String objectType = ConnectorOptions.extractOption(properties, OBJECT_TYPE);
        final String metaType = ConnectorOptions.extractOption(properties, "metaType");

        if (ServiceNowConstants.RESOURCE_TABLE.equalsIgnoreCase(objectType) && "definition".equals(metaType)) {
            return adaptTableDefinitionMetadata(actionId, properties, metadata);
        }
        if (ServiceNowConstants.RESOURCE_TABLE.equalsIgnoreCase(objectType) && "list".equals(metaType)) {
            return adaptTableListMetadata(metadata);
        }
        if (ServiceNowConstants.RESOURCE_IMPORT.equalsIgnoreCase(objectType) && "list".equals(metaType)) {
            return adaptTableListMetadata(metadata);
        }
    }

    return SyndesisMetadata.EMPTY;
}
 
Example #2
Source File: ServiceNowMetadataRetrieval.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private static SyndesisMetadata adaptTableListMetadata(MetaDataExtension.MetaData metadata) {
    try {
        final JsonNode payload = metadata.getPayload(JsonNode.class);
        final List<PropertyPair> tables = new ArrayList<>();
        final Iterator<Map.Entry<String, JsonNode>> it = payload.fields();

        while (it.hasNext()) {
            final Map.Entry<String, JsonNode> entry = it.next();
            final String name = entry.getKey();
            final String displayName = entry.getValue().asText(name);

            tables.add(new PropertyPair(name, displayName));
        }

        return SyndesisMetadata.of(
            Collections.singletonMap(ServiceNowConstants.RESOURCE_TABLE, tables)
        );
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #3
Source File: ServiceNowTableGetCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private void beforeProducer(final Exchange exchange) {
    exchange.getIn().setHeader(ServiceNowConstants.RESOURCE, ServiceNowConstants.RESOURCE_TABLE);
    exchange.getIn().setHeader(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE);
    exchange.getIn().setHeader(ServiceNowConstants.RESPONSE_MODEL, JsonNode.class);

    // set the maximum number of item that can be include in a page
    //
    // TODO: we need to discuss how to handle pagination.
    if (limit != null) {
        exchange.getIn().setHeader(ServiceNowParams.SYSPARM_LIMIT.getHeader(), limit);
    }

    // set the query used to filter out record sets, the query is
    // expected to be encoded.
    if (query != null) {
        try {
            final String key = ServiceNowParams.SYSPARM_QUERY.getHeader();
            final String val = URLEncoder.encode(query, StandardCharsets.UTF_8.name());

            exchange.getIn().setHeader(key, val);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example #4
Source File: ServicenowResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/post")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response post(String message) throws Exception {
    Map<String, Object> headers = new HashMap<>();
    headers.put(ServiceNowConstants.RESOURCE, ServiceNowConstants.RESOURCE_TABLE);
    headers.put(ServiceNowConstants.API_VERSION, "v1");
    headers.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_CREATE);
    headers.put(ServiceNowConstants.REQUEST_MODEL, Incident.class);
    headers.put(ServiceNowConstants.RESPONSE_MODEL, JsonNode.class);
    headers.put(ServiceNowParams.PARAM_TABLE_NAME.getHeader(), "incident");

    Incident incident = new Incident();
    incident.setDescription(message);
    incident.setImpact(1);
    incident.setSeverity(1);

    LOG.infof("Sending to servicenow: %s", message);
    final JsonNode response = producerTemplate.requestBodyAndHeaders(
            "servicenow:" + instance, incident, headers, JsonNode.class);

    String number = response.findPath("number").textValue();

    LOG.infof("Got response from servicenow: %s", response);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(number)
            .build();
}
 
Example #5
Source File: ServiceNowImportSetCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void beforeProducer(final Exchange exchange) {
    exchange.getIn().setHeader(ServiceNowConstants.RESOURCE, ServiceNowConstants.RESOURCE_IMPORT);
    exchange.getIn().setHeader(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_CREATE);
    exchange.getIn().setHeader(ServiceNowConstants.RETRIEVE_TARGET_RECORD, false);
    exchange.getIn().setHeader(ServiceNowConstants.REQUEST_MODEL, String.class);
    exchange.getIn().setHeader(ServiceNowConstants.RESPONSE_MODEL, ImportSetResult.class);
}
 
Example #6
Source File: ServiceNowMetaDataExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private void loadProperties(MetaContext context) throws Exception {
    if (!properties.isEmpty()) {
        return;
    }

    String offset = "0";

    while (true) {
        Response response = context.getClient().reset()
            .types(MediaType.APPLICATION_JSON_TYPE)
            .path(NOW)
            .path(context.getConfiguration().getApiVersion())
            .path(TABLE)
            .path("sys_properties")
            .query(SYSPARM_EXCLUDE_REFERENCE_LINK, "true")
            .query(SYSPARM_FIELDS, "name%2Cvalue")
            .query("sysparm_offset", offset)
            .query(SYSPARM_QUERY, "name=glide.sys.date_format^ORname=glide.sys.time_format")
            .invoke(HttpMethod.GET);

        findResultNode(response).ifPresent(node -> processResult(node, n -> {
            if (n.hasNonNull("name") && n.hasNonNull("value")) {
                properties.putIfAbsent(
                    n.findValue("name").asText(),
                    n.findValue("value").asText()
                );
            }
        }));

        Optional<String> next = ServiceNowHelper.findOffset(response, ServiceNowConstants.LINK_NEXT);
        if (next.isPresent()) {
            offset = next.get();
        } else {
            break;
        }
    }
}
 
Example #7
Source File: ServiceNowMetaDataExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private static void loadDictionary(MetaContext context, String name, ObjectNode root) throws Exception {
    String offset = "0";

    while (true) {
        Response response = context.getClient().reset()
            .types(MediaType.APPLICATION_JSON_TYPE)
            .path(NOW)
            .path(context.getConfiguration().getApiVersion())
            .path(TABLE)
            .path("sys_dictionary")
            .query("sysparm_display_value", "false")
            .queryF(SYSPARM_QUERY, "name=%s", name)
            .query("sysparm_offset", offset)
            .invoke(HttpMethod.GET);

        findResultNode(response).ifPresent(node -> processResult(node, n -> {
            processDictionaryNode(context, root, n);
        }));

        Optional<String> next = ServiceNowHelper.findOffset(response, ServiceNowConstants.LINK_NEXT);
        if (next.isPresent()) {
            offset = next.get();
        } else {
            break;
        }
    }
}
 
Example #8
Source File: ServiceNowMetaDataExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
MetaContext(Map<String, Object> parameters) {
    this.parameters = parameters;
    this.configuration = new ServiceNowConfiguration();
    this.stack = new ArrayDeque<>();

    try {
        PropertyBindingSupport.bindProperties(getCamelContext(), configuration, new HashMap<>(parameters));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    this.instanceName = ConnectorOptions.extractOption(parameters, "instanceName");
    this.objectType = ConnectorOptions.extractOption(parameters, OBJECT_TYPE, ServiceNowConstants.RESOURCE_TABLE);
    this.objectName = ConnectorOptions.extractOption(parameters, OBJECT_NAME, configuration.getTable());

    ObjectHelper.notNull(instanceName, "instanceName");

    // Configure Api and OAuthToken ULRs using instanceName
    if (!configuration.hasApiUrl()) {
        configuration.setApiUrl(String.format("https://%s.service-now.com/api", instanceName));
    }
    if (!configuration.hasOauthTokenUrl()) {
        configuration.setOauthTokenUrl(String.format("https://%s.service-now.com/oauth_token.do", instanceName));
    }

    this.client = new ServiceNowClient(getCamelContext(), configuration);
}
 
Example #9
Source File: ServiceNowIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testSearchIncidents() throws Exception {
    Map<String, Object> serviceNowOptions = createServiceNowOptions();

    Assume.assumeTrue("[#1674] Enable ServiceNow testing in Jenkins",
            serviceNowOptions.size() == ServiceNowIntegrationTest.ServiceNowOption.values().length);

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("servicenow:{{env:SERVICENOW_INSTANCE}}"
                + "?userName={{env:SERVICENOW_USERNAME}}"
                + "&password={{env:SERVICENOW_PASSWORD}}"
                + "&oauthClientId={{env:SERVICENOW_CLIENT_ID}}"
                + "&oauthClientSecret={{env:SERVICENOW_CLIENT_SECRET}}"
                + "&release={{env:SERVICENOW_RELEASE}}"
                + "&model.incident=org.wildfly.camel.test.servicenow.subA.Incident");
        }
    });

    camelctx.start();
    try {
        Map<String, Object> headers = new HashMap<>();
        headers.put(ServiceNowConstants.RESOURCE, "table");
        headers.put(ServiceNowConstants.ACTION, ServiceNowConstants.ACTION_RETRIEVE);
        headers.put(ServiceNowParams.PARAM_TABLE_NAME.getHeader(), "incident");

        ProducerTemplate producer = camelctx.createProducerTemplate();
        List<Incident> result = producer.requestBodyAndHeaders("direct:start", null, headers, List.class);

        Assert.assertNotNull(result);
        Assert.assertTrue(result.size() > 0);
    } finally {
        camelctx.close();
    }
}
 
Example #10
Source File: ServiceNowMetaDataExtension.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private Optional<MetaData> tableList(MetaContext context) throws Exception {
    Optional<JsonNode> response = context.getClient().reset()
        .types(MediaType.APPLICATION_JSON_TYPE)
        .path(NOW)
        .path(context.getConfiguration().getApiVersion())
        .path(TABLE)
        .path(SYS_DB_OBJECT)
        .query(SYSPARM_EXCLUDE_REFERENCE_LINK, "true")
        .query(SYSPARM_FIELDS, "name%2Csys_id")
        .query(SYSPARM_QUERY, "name=sys_import_set_row")
        .trasform(HttpMethod.GET, ServiceNowMetaDataExtension::findResultNode);

    if (response.isPresent()) {
        final JsonNode node = response.get();
        final JsonNode sysId = node.findValue("sys_id");

        response = context.getClient().reset()
            .types(MediaType.APPLICATION_JSON_TYPE)
            .path(NOW)
            .path(context.getConfiguration().getApiVersion())
            .path(TABLE)
            .path(SYS_DB_OBJECT)
            .query(SYSPARM_EXCLUDE_REFERENCE_LINK, "true")
            .query(SYSPARM_FIELDS, "name%2Csys_name%2Csuper_class")
            .trasform(HttpMethod.GET, ServiceNowMetaDataExtension::findResultNode);

        if (response.isPresent()) {
            final ObjectNode root = context.getConfiguration().getOrCreateMapper().createObjectNode();

            processResult(response.get(), n -> {
                final JsonNode superClass = n.findValue("super_class");
                final JsonNode name = n.findValue("name");
                final JsonNode label = n.findValue("sys_name");

                if (superClass != null) {
                    final String impId = sysId != null ? sysId.textValue() : null;
                    final String superId = superClass.textValue();

                    if (impId != null && superId != null && ObjectHelper.equal(impId, superId)) {
                        LOGGER.debug("skip table: name={}, label={} because it refers to an import set", name, label);
                        return;
                    }
                }

                if (name != null && label != null) {
                    String key = name.textValue();
                    String val = label.textValue();

                    if (ObjectHelper.isEmpty(val)) {
                        val = key;
                    }

                    root.put(key, val);
                }
            });

            return Optional.of(
                MetaDataBuilder.on(getCamelContext())
                    .withAttribute(MetaData.CONTENT_TYPE, "application/json")
                    .withAttribute(MetaData.JAVA_TYPE, JsonNode.class)
                    .withAttribute("Meta-Context", ServiceNowConstants.RESOURCE_IMPORT)
                    .withPayload(root)
                    .build()
            );
        }
    }

    return Optional.empty();
}