Java Code Examples for org.apache.camel.util.ObjectHelper#isEmpty()

The following examples show how to use org.apache.camel.util.ObjectHelper#isEmpty() . 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: JsonPathIntegrationCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Integration apply(Integration integration) {
    if (ObjectHelper.isEmpty(expression)) {
        return integration;
    }

    try {
        final Configuration configuration = Configuration.builder()
                .jsonProvider(new JacksonJsonProvider(JsonUtils.copyObjectMapperConfiguration()))
                .mappingProvider(new JacksonMappingProvider(JsonUtils.copyObjectMapperConfiguration()))
                .build();

        DocumentContext json = JsonPath.using(configuration).parse(JsonUtils.writer().forType(Integration.class).writeValueAsString(integration));

        if (ObjectHelper.isEmpty(key)) {
            json.set(expression, value);
        } else {
            json.put(expression, key, value);
        }

        return JsonUtils.reader().forType(Integration.class).readValue(json.jsonString());
    } catch (IOException e) {
        throw new IllegalStateException("Failed to evaluate json path expression on integration object", e);
    }
}
 
Example 2
Source File: ResponseCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
static boolean isUnifiedDataShape(final DataShape dataShape) {
    if (dataShape == null || dataShape.getKind() != DataShapeKinds.JSON_SCHEMA) {
        return false;
    }

    final String specification = dataShape.getSpecification();
    if (ObjectHelper.isEmpty(specification)) {
        return false;
    }

    final JsonNode jsonSchema;
    try {
        jsonSchema = PayloadConverterBase.MAPPER.readTree(specification);
    } catch (final IOException e) {
        LOG.warn("Unable to parse data shape as a JSON: {}", e.getMessage());
        LOG.debug("Failed parsing JSON datashape: `{}`", specification, e);
        return false;
    }

    final JsonNode id = jsonSchema.get("$id");

    return !isNullNode(id) && "io:syndesis:wrapped".equals(id.asText());
}
 
Example 3
Source File: ActivityTrackingInterceptStrategy.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Processor wrapProcessorInInterceptors(CamelContext context, NamedNode definition, Processor target, Processor nextTarget) {
    if (this.tracker == null) {
        return target;
    }

    if (shouldTrack(definition)) {
        final String id = definition.getId();
        if (ObjectHelper.isEmpty(id)) {
            return target;
        }

        final String stepId = StringHelper.after(id, "step:");
        if (ObjectHelper.isEmpty(stepId)) {
            return target;
        }

        if (shouldTrackDoneEvent(definition)) {
            return new TrackDoneEventProcessor(target, stepId);
        }

        return new TrackStartEventProcessor(target, stepId);
    }

    return target;
}
 
Example 4
Source File: ODataVerifierExtension.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
protected Result verifyParameters(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS)
            .error(ResultErrorHelper.requiresOption(SERVICE_URI, parameters));

    Object userName = ConnectorOptions.extractOption(parameters, BASIC_USER_NAME);
    Object password = ConnectorOptions.extractOption(parameters, BASIC_PASSWORD);

    if (
            // Basic authentication requires both user name and password
            (ObjectHelper.isEmpty(userName) && ObjectHelper.isNotEmpty(password))
            ||
            (ObjectHelper.isNotEmpty(userName) && ObjectHelper.isEmpty(password)))
    {
        builder.error(ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.MISSING_PARAMETER,
            "Basic authentication requires both a user name and password").
                      parameterKey(BASIC_USER_NAME).parameterKey(BASIC_PASSWORD).build());
    }

    return builder.build();
}
 
Example 5
Source File: TracingActivityTrackingPolicy.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void onExchangeBegin(Route route, Exchange exchange) {
    if (tracer == null) {
        return;
    }
    String activityId = ActivityTracker.getActivityId(exchange);
    if (ObjectHelper.isEmpty(activityId)) {
        ActivityTracker.initializeTracking(exchange);
        activityId = ActivityTracker.getActivityId(exchange);
    }

    Span span = tracer
        .buildSpan(flowId)
        .withTag(Tags.SPAN_KIND.getKey(), "activity")
        .withTag("exchange", activityId)
        .start();
    exchange.setProperty(IntegrationLoggingConstants.ACTIVITY_SPAN, span);
}
 
Example 6
Source File: ODataMetaDataExtension.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private static void extractEdmMetadata(ODataMetadata odataMetadata, Edm edm, String resourcePath) {
    if (ObjectHelper.isEmpty(resourcePath)) {
        LOG.warn("No method name with which to query OData service.");
        return;
    }

    EdmEntityContainer entityContainer = edm.getEntityContainer();
    EdmEntitySet entitySet = entityContainer.getEntitySet(resourcePath);
    if (ObjectHelper.isEmpty(entitySet)) {
        LOG.warn("No entity set associated with the selected api name: {}.", resourcePath);
        return;
    }

    EdmTypeConvertor visitor = new EdmTypeConvertor();
    EdmEntityType entityType = entitySet.getEntityType();
    Set<PropertyMetadata> properties = visitor.visit(entityType);
    odataMetadata.setEntityProperties(properties);
}
 
Example 7
Source File: PathFilter.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public Predicate<Path> asPathPredicate() {
    if (ObjectHelper.isEmpty(excludePatterns) && ObjectHelper.isEmpty(includePatterns)) {
        return path -> true;
    } else {
        return path -> stringPredicate.test(sanitize(path.toString()));
    }
}
 
Example 8
Source File: GoogleCalendarEventModel.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static String or(String first, String second) {
    if (ObjectHelper.isEmpty(first)) {
        return second;
    }

    return first;
}
 
Example 9
Source File: AbstractEMailVerifier.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected void secureProtocol(Map<String, Object> parameters) {
    Protocol protocol = ConnectorOptions.extractOptionAndMap(parameters,
        PROTOCOL, Protocol::getValueOf, null);
    if (ObjectHelper.isEmpty(protocol)) {
        return;
    }

    SecureType secureType = ConnectorOptions.extractOptionAndMap(parameters,
        SECURE_TYPE, SecureType::secureTypeFromId, null);
    if (ObjectHelper.isEmpty(secureType) || protocol.isSecure()) {
        return;
    }

    switch (secureType) {
        case STARTTLS:
            Properties properties = new Properties();
            properties.put(MAIL_PREFIX + protocol + ".starttls.enable", "true");
            properties.put(MAIL_PREFIX + protocol + ".starttls.required", "true");
            parameters.put(ADDITIONAL_MAIL_PROPERTIES, properties);
            break;
        case SSL_TLS:
            parameters.put(PROTOCOL, protocol.toSecureProtocol().id());
            break;
        default:
            // Nothing required
    }
}
 
Example 10
Source File: GoogleCalendarUtils.java    From syndesis with Apache License 2.0 5 votes vote down vote up
static List<EventAttendee> parseAtendees(final String attendeesString) {
    if (ObjectHelper.isEmpty(attendeesString)) {
        return Collections.emptyList();
    }

    return Splitter.on(',').trimResults().splitToList(attendeesString)
        .stream()
        .map(GoogleCalendarUtils::attendee)
        .collect(Collectors.toList());
}
 
Example 11
Source File: ActiveMQConnector.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private SjmsComponent lookupComponent() {
    final CamelContext context = getCamelContext();
    final List<String> names = context.getComponentNames();

    if (ObjectHelper.isEmpty(names)) {
        return null;
    }

    // Try to check if a component with same set-up has already been
    // configured, if so reuse it.
    for (String name : names) {
        Component cmp = context.getComponent(name, false, false);
        if (!(cmp instanceof SjmsComponent)) {
            continue;
        }

        ConnectionFactory factory = ((SjmsComponent) cmp).getConnectionFactory();
        if (factory instanceof ActiveMQConnectionFactory) {
            ActiveMQConnectionFactory amqFactory = (ActiveMQConnectionFactory) factory;

            if (!Objects.equals(brokerUrl, amqFactory.getBrokerURL())) {
                continue;
            }
            if (!Objects.equals(username, amqFactory.getUserName())) {
                continue;
            }
            if (!Objects.equals(password, amqFactory.getPassword())) {
                continue;
            }

            return (SjmsComponent) cmp;
        }
    }

    return null;
}
 
Example 12
Source File: ODataReadToCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected void beforeProducer(Exchange exchange) throws IOException {
    Message in = exchange.getIn();

    String body = in.getBody(String.class);
    JsonNode node = OBJECT_MAPPER.readTree(body);
    JsonNode keyPredicateNode = node.get(KEY_PREDICATE);

    if (! ObjectHelper.isEmpty(keyPredicateNode)) {
        String keyPredicate = keyPredicateNode.asText();

        //
        // Change the resource path instead as there is a bug in using the
        // keyPredicate header (adds brackets around regardless of a subpredicate
        // being present). When that's fixed we can revert back to using keyPredicate
        // header instead.
        //
        in.setHeader(OLINGO4_PROPERTY_PREFIX + RESOURCE_PATH,
                     resourcePath + ODataUtil.formatKeyPredicate(keyPredicate, true));
    } else {
        //
        // Necessary to have a key predicate. Otherwise, read will try returning
        // all results which could very be painful for the running integration.
        //
        throw new RuntimeCamelException("Key Predicate value was empty");
    }

    in.setBody(EMPTY_STRING);
}
 
Example 13
Source File: RoutesConfigurer.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
protected void load(Runtime runtime, String[] routes) {
    for (String route: routes) {
        if (ObjectHelper.isEmpty(route)) {
            continue;
        }

        try {
            load(runtime, Sources.fromURI(route));
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }

        LOGGER.info("Loading routes from: {}", route);
    }
}
 
Example 14
Source File: RoutesConfigurer.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void accept(Runtime runtime) {
    String routes = System.getProperty(Constants.PROPERTY_CAMEL_K_ROUTES);

    if (ObjectHelper.isEmpty(routes)) {
        routes = System.getenv(Constants.ENV_CAMEL_K_ROUTES);
    }

    if (ObjectHelper.isEmpty(routes)) {
        LOGGER.warn("No routes found in {} environment variable", Constants.ENV_CAMEL_K_ROUTES);
        return;
    }

    load(runtime, routes.split(",", -1));
}
 
Example 15
Source File: Sources.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
private URI(String uri) throws Exception {
    final String location = StringSupport.substringBefore(uri, "?");

    if (!location.startsWith(Constants.SCHEME_PREFIX_CLASSPATH) && !location.startsWith(Constants.SCHEME_PREFIX_FILE)) {
        throw new IllegalArgumentException("No valid resource format, expected scheme:path, found " + uri);
    }

    final String query = StringSupport.substringAfter(uri, "?");
    final Map<String, Object> params = URISupport.parseQuery(query);
    final String languageName = (String) params.get("language");
    final String compression = (String) params.get("compression");
    final String loader = (String) params.get("loader");
    final String interceptors = (String) params.get("interceptors");

    String language = languageName;
    if (ObjectHelper.isEmpty(language)) {
        language = StringSupport.substringAfterLast(location, ":");
        language = StringSupport.substringAfterLast(language, ".");
    }
    if (ObjectHelper.isEmpty(language)) {
        throw new IllegalArgumentException("Unknown language " + language);
    }

    String name = (String) params.get("name");
    if (name == null) {
        name = StringSupport.substringAfter(location, ":");
        name = StringSupport.substringBeforeLast(name, ".");

        if (name.contains("/")) {
            name = StringSupport.substringAfterLast(name, "/");
        }
    }

    this.location = location;
    this.name = name;
    this.language = language;
    this.loader = loader;
    this.interceptors = interceptors != null ? Arrays.asList(interceptors.split(",", -1)) : Collections.emptyList();
    this.compressed = Boolean.parseBoolean(compression);
}
 
Example 16
Source File: HttpConnectorVerifierExtension.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public Result verify(Scope scope, Map<String, Object> parameters) {
    final Map<String, Object> options = new HashMap<>(parameters);

    String baseUrl = (String) options.remove("baseUrl");
    String uriScheme = StringHelper.before(baseUrl, "://");

    if (ObjectHelper.isNotEmpty(uriScheme) && !ObjectHelper.equal(supportedScheme, uriScheme)) {
        return ResultBuilder.withScope(scope).error(
            ResultErrorBuilder.withCode("unsupported_scheme")
                .description("Unsupported scheme: " + uriScheme)
                .parameterKey("baseUrl")
                .build()
        ).build();
    }

    if (ObjectHelper.isEmpty(uriScheme)) {
        baseUrl = new StringBuilder(supportedScheme).append("://").append(baseUrl).toString();
    }

    String path = (String) options.remove("path");
    if (ObjectHelper.isNotEmpty(path)) {
        final String uri = StringUtils.removeEnd(baseUrl, "/") + "/" + StringUtils.removeStart(path, "/");

        options.put("httpUri", uri);
    } else {
        options.put("httpUri", baseUrl);
    }

    Component component = getCamelContext().getComponent(this.componentScheme);
    if (component == null) {
        return ResultBuilder.withScope(scope).error(
            ResultErrorBuilder.withCode(VerificationError.StandardCode.UNSUPPORTED_COMPONENT)
                .description("Unsupported component " + this.componentScheme)
                .build()
        ).build();
    }

    return component.getExtension(ComponentVerifierExtension.class)
        .map(extension -> extension.verify(scope, options))
        .orElseGet(() -> ResultBuilder.unsupported().build());
}
 
Example 17
Source File: ODataPatchCustomizer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
protected void beforeProducer(Exchange exchange) throws IOException {
    Message in = exchange.getIn();

    //
    // Expect a json object containing both the keyPredicate and the entity properties
    // to be updated.
    // The keyPredicate has been added to the entity schema in ODataMetaDataRetrieval
    // as a means of specifying which entity to be modified.
    //
    // Upon each message, a new keyPredicate can be provided and will be processed accordingly.
    //
    // Need to find the keyPredicate and add it as a header so the component can find it.
    // Then must remove it from the properties since its not a data property.
    //
    String body = in.getBody(String.class);
    JsonNode node = OBJECT_MAPPER.readTree(body);
    JsonNode keyPredicateNode = node.get(KEY_PREDICATE);

    if (! ObjectHelper.isEmpty(keyPredicateNode)) {
        String keyPredicate = keyPredicateNode.asText();
        //
        // Change the resource path instead as there is a bug in using the
        // keyPredicate header (adds brackets around regardless of a subpredicate
        // being present). When that's fixed we can revert back to using keyPredicate
        // header instead.
        //
        in.setHeader(OLINGO4_PROPERTY_PREFIX + RESOURCE_PATH,
                     resourcePath + ODataUtil.formatKeyPredicate(keyPredicate, true));

        // Remove the key predicate from the body
        ObjectNode objNode = ((ObjectNode) node);
        objNode.remove(KEY_PREDICATE);
        body = OBJECT_MAPPER.writeValueAsString(objNode);
    } else {
        // No key predicate found ... this means trouble!
        throw new CamelExecutionException("No Key Predicate available for OData Patching", exchange);
    }

    if (! ObjectHelper.isEmpty(body)) {
        in.setHeader(OLINGO4_PROPERTY_PREFIX + DATA, body);
    }

    in.setBody(body);
}
 
Example 18
Source File: AMQPConnector.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private AMQPComponent lookupComponent() {
    final CamelContext context = getCamelContext();
    final List<String> names = context.getComponentNames();

    if (ObjectHelper.isEmpty(names)) {
        return null;
    }

    // lookup existing component with same configuration
    for (String name: names) {

        Component cmp = context.getComponent(name, false, false);
        if (cmp instanceof AMQPComponent) {

            final ConnectionFactory factory;
            try {
                factory = ((AMQPComponent)cmp).getConfiguration().getConnectionFactory();
            } catch (IllegalArgumentException e) {
                // ignore components without a connection factory
                continue;
            }

            if (factory instanceof JmsConnectionFactory) {
                JmsConnectionFactory jmsConnectionFactory = (JmsConnectionFactory)factory;

                if (!Objects.equals(connectionUri, jmsConnectionFactory.getRemoteURI())) {
                    continue;
                }
                if (!Objects.equals(username, jmsConnectionFactory.getUsername())) {
                    continue;
                }
                if (!Objects.equals(password, jmsConnectionFactory.getPassword())) {
                    continue;
                }
                if (!Objects.equals(clientId, jmsConnectionFactory.getClientID())) {
                    continue;
                }

                return (AMQPComponent) cmp;
            }
        }
    }

    return null;
}
 
Example 19
Source File: SubstituteInfinispanManager.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
@Substitute
public <K, V> BasicCache<K, V> getCache(String cacheName) {
    return ObjectHelper.isEmpty(cacheName) ? cacheContainer.getCache() : cacheContainer.getCache(cacheName);
}
 
Example 20
Source File: ActiveMQUtil.java    From syndesis with Apache License 2.0 4 votes vote down vote up
public static ActiveMQConnectionFactory createActiveMQConnectionFactory(String brokerUrl, String username, String password, String brokerCertificate, String clientCertificate, boolean skipCertificateCheck) {
    if (brokerUrl.contains("ssl:")) {
        final ActiveMQSslConnectionFactory connectionFactory = createTlsConnectionFactory(brokerUrl, username, password);

        try {
            // create client key manager
            final KeyManager[] keyManagers;
            if (ObjectHelper.isEmpty(clientCertificate)) {
                keyManagers = null;
            } else {
                keyManagers = CertificateUtil.createKeyManagers(clientCertificate, "amq-client");
            }

            // create client trust manager
            final TrustManager[] trustManagers;
            if (ObjectHelper.isEmpty(brokerCertificate)) {
                if (skipCertificateCheck) {
                    // use a trust all TrustManager
                    LOG.warn("Skipping Certificate check for Broker {}", brokerUrl);
                    trustManagers = CertificateUtil.createTrustAllTrustManagers();
                } else {
                    LOG.debug("Using default JVM Trust Manager for Broker {}", brokerUrl);
                    trustManagers = null;
                }
            } else {
                trustManagers = CertificateUtil.createTrustManagers(brokerCertificate, "amq-broker");
            }

            connectionFactory.setKeyAndTrustManagers(keyManagers, trustManagers, new SecureRandom());

            return connectionFactory;
        } catch (GeneralSecurityException | IOException e) {
            throw new IllegalArgumentException("SSL configuration error: " + e.getMessage(), e);
        }
    }

    // non-ssl connection
    return ObjectHelper.isEmpty(username)
        ? new ActiveMQConnectionFactory(brokerUrl)
        : new ActiveMQConnectionFactory(username, password, brokerUrl);
}