Java Code Examples for org.apache.camel.util.StringHelper

The following examples show how to use org.apache.camel.util.StringHelper. These examples are extracted from open source projects. 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
private CamelCloudServiceFilter createServiceFilter(CamelCloudConfigurationProperties.ServiceFilterConfiguration configuration) {
    BlacklistServiceFilter blacklist = new BlacklistServiceFilter();

    Map<String, List<String>> services = configuration.getBlacklist();
    for (Map.Entry<String, List<String>> entry : services.entrySet()) {
        for (String part : entry.getValue()) {
            String host = StringHelper.before(part, ":");
            String port = StringHelper.after(part, ":");

            if (ObjectHelper.isNotEmpty(host) && ObjectHelper.isNotEmpty(port)) {
                blacklist.addServer(
                    DefaultServiceDefinition.builder()
                        .withName(entry.getKey())
                        .withHost(host)
                        .withPort(Integer.parseInt(port))
                        .build()
                );
            }
        }
    }

    return new CamelCloudServiceFilter(Arrays.asList(new HealthyServiceFilter(), blacklist));
}
 
Example 2
@Override
public String apply(String remainder) {
    final String defaultValue = StringHelper.after(remainder, ":");

    if (this.root == null) {
        return defaultValue;
    }

    final String name = StringHelper.before(remainder, "/");
    final String property = StringHelper.after(remainder, "/");

    if (name == null || property == null) {
        return defaultValue;
    }

    Path file = this.root.resolve(name.toLowerCase()).resolve(property);
    if (Files.exists(file) && !Files.isDirectory(file)) {
        try {
            return Files.readString(file, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    return defaultValue;
}
 
Example 3
Source Project: camel-k-runtime   Source File: HotDeploymentProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
List<HotDeploymentWatchedFileBuildItem> routes() {
    final Config config = ConfigProvider.getConfig();
    final Optional<String> value = config.getOptionalValue(Constants.PROPERTY_CAMEL_K_ROUTES, String.class);

    List<HotDeploymentWatchedFileBuildItem> items = new ArrayList<>();

    if (value.isPresent()) {
        for (String source : value.get().split(",", -1)) {
            String path = StringHelper.after(source, ":");
            if (path == null) {
                path = source;
            }

            Path p = Paths.get(path);
            if (Files.exists(p)) {
                LOGGER.info("Register source for hot deployment: {}", p.toAbsolutePath());
                items.add(new HotDeploymentWatchedFileBuildItem(p.toAbsolutePath().toString()));
            }
        }
    }

    return items;
}
 
Example 4
Source Project: syndesis   Source File: ComponentProxyComponent.java    License: Apache License 2.0 6 votes vote down vote up
public ComponentProxyComponent(String componentId, String componentScheme, String componentClass, CamelCatalog catalog) {
    this.componentId = StringHelper.notEmpty(componentId, "componentId");
    this.componentScheme = StringHelper.notEmpty(componentScheme, "componentScheme");
    this.componentSchemeAlias = Optional.empty();
    this.configuredOptions = new HashMap<>();
    this.remainingOptions = new HashMap<>();
    this.catalog = ObjectHelper.notNull(catalog, "catalog");

    if (ObjectHelper.isNotEmpty(componentClass)) {
        this.catalog.addComponent(componentScheme, componentClass);
    }

    try {
        this.definition = ComponentDefinition.forScheme(catalog, componentScheme);
    } catch (IOException e) {
        throw RuntimeCamelException.wrapRuntimeCamelException(e);
    }

    registerExtension(this::getComponentVerifierExtension);
}
 
Example 5
@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 6
Source Project: syndesis   Source File: TracingInterceptStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Processor wrapProcessorInInterceptors(CamelContext context, NamedNode definition, Processor target, Processor nextTarget) throws Exception {
    if (definition instanceof PipelineDefinition) {
        final String id = definition.getId();
        if (ObjectHelper.isEmpty(id)) {
            return target;
        }

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

        return new EventProcessor(target, stepId);
    }
    return target;
}
 
Example 7
@Test
public void shouldRemoveUnwantedSecurity() throws IOException {
    final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer();
    final String spec = RestSwaggerConnectorIntegrationTest.readSpecification("apikey.json");
    final String specUpdated = RestSwaggerConnectorIntegrationTest.readSpecification("apikey-security-updated.json");

    final Map<String, Object> options = new HashMap<>();
    options.put("specification", spec);
    options.put("authenticationType", "apiKey: api-key-header");

    customizer.customize(NOT_USED, options);

    assertThat(options).containsKey("specificationUri");
    assertThat(options).doesNotContainKey("specification");
    assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent(specUpdated);
}
 
Example 8
Source Project: syndesis   Source File: HttpConnectorFactories.java    License: Apache License 2.0 6 votes vote down vote up
public static String computeHttpUri(String scheme, Map<String, Object> options) {
    String baseUrl = (String)options.remove("baseUrl");

    if (ObjectHelper.isEmpty(baseUrl)) {
        throw new IllegalArgumentException("baseUrl si mandatory");
    }

    String uriScheme = StringHelper.before(baseUrl, "://");
    if (ObjectHelper.isNotEmpty(uriScheme) && !ObjectHelper.equal(scheme, uriScheme)) {
        throw new IllegalArgumentException("Unsupported scheme: " + uriScheme);
    }

    if (ObjectHelper.isNotEmpty(uriScheme)) {
        baseUrl = StringHelper.after(baseUrl, "://");
    }

    String path = (String)options.remove("path");
    if (StringUtils.isNotEmpty(path)) {
        return StringUtils.removeEnd(baseUrl, "/") + "/" + StringUtils.removeStart(path, "/");
    } else {
        return baseUrl;
    }
}
 
Example 9
Source Project: camelinaction2   Source File: OrderServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateAndGetOrder() throws Exception {
    String json = "{\"partName\":\"motor\",\"amount\":1,\"customerName\":\"honda\"}";

    log.info("Sending order using json payload: {}", json);

    // use http component to send the order
    String id = template.requestBody("http://localhost:8080/orders", json, String.class);
    assertNotNull(id);

    log.info("Created new order with id " + id);

    // should create a new order with id 3 (json format so its enclosed in quotes)
    assertEquals("\"3\"", id);

    // remove quoutes
    id = StringHelper.removeQuotes(id);

    // use http component to get the order
    String response = template.requestBody("http://localhost:8080/orders/" + id, null, String.class);
    log.info("Response: {}", response);
}
 
Example 10
Source Project: camelinaction2   Source File: SpringOrderServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateAndGetOrder() throws Exception {
    String json = "{\"partName\":\"motor\",\"amount\":1,\"customerName\":\"honda\"}";

    log.info("Sending order using json payload: {}", json);

    // use http component to send the order
    String id = template.requestBody("http://localhost:8080/orders", json, String.class);
    assertNotNull(id);

    log.info("Created new order with id " + id);

    // should create a new order with id 3 (json format so its enclosed in quotes)
    assertEquals("\"3\"", id);

    // remove quoutes
    id = StringHelper.removeQuotes(id);

    // use http component to get the order
    String response = template.requestBody("http://localhost:8080/orders/" + id, null, String.class);
    log.info("Response: {}", response);
}
 
Example 11
Source Project: camel-k-runtime   Source File: KnativeComponent.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    if (ObjectHelper.isEmpty(remaining)) {
        throw new IllegalArgumentException("Expecting URI in the form of: 'knative:type/name', got '" + uri + "'");
    }

    final String type = ObjectHelper.supplyIfEmpty(StringHelper.before(remaining, "/"), () -> remaining);
    final String name = StringHelper.after(remaining, "/");
    final KnativeConfiguration conf = getKnativeConfiguration();

    conf.getFilters().putAll(
        PropertiesHelper.extractProperties(parameters, "filter.", true)
    );
    conf.getTransportOptions().putAll(
        PropertiesHelper.extractProperties(parameters, "transport.", true)
    );
    conf.getCeOverride().putAll(
        PropertiesHelper.extractProperties(parameters, "ce.override.", true)
    );

    // set properties from the endpoint uri
    PropertyBindingSupport.bindProperties(getCamelContext(), conf, parameters);

    if (ObjectHelper.isEmpty(conf.getServiceName())) {
        conf.setServiceName(name);
    }

    return new KnativeEndpoint(uri, this, Knative.Type.valueOf(type), name, conf);
}
 
Example 12
Source Project: syndesis-extensions   Source File: ScriptAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ProcessorDefinition<?>> configure(CamelContext context, ProcessorDefinition<?> route, Map<String, Object> parameters) {
    ObjectHelper.notNull(route, "route");
    ObjectHelper.notNull(engine, "engine");
    ObjectHelper.notNull(language, "language");
    StringHelper.notEmpty(script, "script");

    return Optional.of(route.process(this::process));
}
 
Example 13
Source Project: syndesis-extensions   Source File: TelegramBotAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ProcessorDefinition<?>> configure(CamelContext context, ProcessorDefinition<?> route, Map<String, Object> parameters) {
    ObjectHelper.notNull(route, "route");
    ObjectHelper.notNull(engine, "engine");
    StringHelper.notEmpty(commandname, "commandname");
    StringHelper.notEmpty(commandimpl, "commandimpl");

    return Optional.of(route.process(this::process));
}
 
Example 14
@Test
public void shouldStoreSpecificationInTemporaryDirectory() {
    final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer();

    final Map<String, Object> options = new HashMap<>();
    options.put("specification", "the specification is here");

    customizer.customize(NOT_USED, options);

    assertThat(options).containsKey("specificationUri");
    assertThat(options).doesNotContainKey("specification");
    assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent("the specification is here");
}
 
Example 15
@Test
public void shouldNotUpdateSpecificationOnMissingSecurityDefinitionName() throws IOException {
    final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer();
    final String spec = RestSwaggerConnectorIntegrationTest.readSpecification("apikey.json");

    final Map<String, Object> options = new HashMap<>();
    options.put("specification", spec);
    options.put("authenticationType", "apiKey");

    customizer.customize(NOT_USED, options);

    assertThat(options).containsKey("specificationUri");
    assertThat(options).doesNotContainKey("specification");
    assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent(spec);
}
 
Example 16
@Test
public void shouldNotUpdateSpecificationOnNullSecurityDefinitionName() throws IOException {
    final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer();
    final String spec = RestSwaggerConnectorIntegrationTest.readSpecification("apikey.json");

    final Map<String, Object> options = new HashMap<>();
    options.put("specification", spec);

    customizer.customize(NOT_USED, options);

    assertThat(options).containsKey("specificationUri");
    assertThat(options).doesNotContainKey("specification");
    assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent(spec);
}
 
Example 17
Source Project: camelinaction2   Source File: MirandaJava8Test.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("jetty://http://localhost:9080/service/order")
                .transform().message(m -> "ID=" + m.getHeader("id"))
                .to("mock:miranda")
                .transform().body(String.class, b -> StringHelper.after(b, "STATUS="));
        }
    };
}
 
Example 18
Source Project: camel-quarkus   Source File: BuildTimeUriResolver.java    License: Apache License 2.0 4 votes vote down vote up
private String toTransletName(final String compacted) {
    final String fileName = FileUtil.stripPath(compacted);
    final String name = FileUtil.stripExt(fileName, true);
    return StringHelper.capitalize(name, true);
}
 
Example 19
Source Project: camel-quarkus   Source File: BuildTimeUriResolver.java    License: Apache License 2.0 4 votes vote down vote up
private static String compact(String href, String scheme) {
    final String afterScheme = scheme != null ? StringHelper.after(href, scheme) : href;
    final String compacted = FileUtil.compactPath(afterScheme, '/');
    return compacted;
}
 
Example 20
Source Project: camel-k-runtime   Source File: StringSupport.java    License: Apache License 2.0 4 votes vote down vote up
public static String substringAfter(final String str, final String separator) {
    String answer = StringHelper.after(str, separator);
    return answer != null ? answer : "";
}
 
Example 21
Source Project: syndesis   Source File: GoogleCalendarEventModel.java    License: Apache License 2.0 4 votes vote down vote up
public static GoogleCalendarEventModel newFrom(final Event event) {
    final GoogleCalendarEventModel model = new GoogleCalendarEventModel();

    if (event == null) {
        return model;
    }

    model.title = StringHelper.trimToNull(event.getSummary());

    model.description = StringHelper.trimToNull(event.getDescription());

    model.attendees = formatAtendees(event.getAttendees());

    model.setStart(event.getStart());

    model.setEnd(event.getEnd());

    model.location = StringHelper.trimToNull(event.getLocation());

    model.eventId = StringHelper.trimToNull(event.getId());

    return model;
}
 
Example 22
Source Project: syndesis   Source File: HttpConnectorVerifierExtension.java    License: 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 23
Source Project: camelinaction2   Source File: MirandaTest.java    License: Apache License 2.0 4 votes vote down vote up
public void process(Exchange exchange) throws Exception {
    String body = exchange.getIn().getBody(String.class);
    String reply = StringHelper.after(body, "STATUS=");
    exchange.getIn().setBody(reply);
}