org.apache.camel.util.IOHelper Java Examples

The following examples show how to use org.apache.camel.util.IOHelper. 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: TarfileTest.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    final String encoding = "utf-8";

    byte[] body;

    ExtractableResponse response = RestAssured.given() //
            .contentType(ContentType.TEXT + "; charset=" + encoding).body("Hello World").post("/tarfile/post") //
            .then().extract();

    body = response.body().asByteArray();
    Assertions.assertNotNull(body);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ByteArrayInputStream bis = new ByteArrayInputStream(body);
    TarArchiveInputStream tis = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream(ArchiveStreamFactory.TAR, bis);

    TarArchiveEntry entry = tis.getNextTarEntry();
    if (entry != null) {
        IOHelper.copy(tis, bos);
    }

    String str = bos.toString(encoding);
    Assertions.assertEquals("Hello World", str);
}
 
Example #2
Source File: FastCamelContext.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public String getEipParameterJsonSchema(String eipName) throws IOException {
    // the eip json schema may be in some of the sub-packages so look until
    // we find it
    String[] subPackages = new String[] { "", "/config", "/dataformat", "/language", "/loadbalancer", "/rest" };
    for (String sub : subPackages) {
        String path = CamelContextHelper.MODEL_DOCUMENTATION_PREFIX + sub + "/" + eipName + ".json";
        InputStream inputStream = getClassResolver().loadResourceAsStream(path);
        if (inputStream != null) {
            try {
                return IOHelper.loadText(inputStream);
            } finally {
                IOHelper.close(inputStream);
            }
        }
    }
    return null;
}
 
Example #3
Source File: JavaSourceLoader.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public Result load(Runtime runtime, Source source) throws Exception {
    try (InputStream is = source.resolveAsInputStream(runtime.getCamelContext())) {
        final String content = IOHelper.loadText(is);
        final String name = determineQualifiedName(source, content);
        final Reflect compiled = Reflect.compile(name, content);
        final Object instance = compiled.create().get();

        // The given source may contains additional nested classes which are unknown to Camel
        // as they are associated to the ClassLoader used to compile the source thus we need
        // to add it to the ApplicationContextClassLoader.
        final ClassLoader loader = runtime.getCamelContext().getApplicationContextClassLoader();
        if (loader instanceof CompositeClassloader) {
            ((CompositeClassloader) loader).addClassLoader(instance.getClass().getClassLoader());
        }

        return Result.on(instance);
    }
}
 
Example #4
Source File: ExtensionTest.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadRoutes() throws IOException {
    String code;

    try (InputStream is = ExtensionTest.class.getResourceAsStream("/routes.js")) {
        code = IOHelper.loadText(is);
    }

    JsonPath p = RestAssured.given()
        .contentType(MediaType.TEXT_PLAIN)
        .accept(MediaType.APPLICATION_JSON)
        .body(code)
        .post("/test/load-routes/MyRoute")
        .then()
            .statusCode(200)
        .extract()
            .body()
            .jsonPath();

    assertThat(p.getList("components", String.class)).contains("direct", "log");
    assertThat(p.getList("routes", String.class)).contains("js");
    assertThat(p.getList("endpoints", String.class)).contains("direct://js", "log://js");
}
 
Example #5
Source File: ExtensionTest.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadRoutes() throws IOException {
    String code;

    try (InputStream is = ExtensionTest.class.getResourceAsStream("/routes.yaml")) {
        code = IOHelper.loadText(is);
    }

    JsonPath p = RestAssured.given()
        .contentType(MediaType.TEXT_PLAIN)
        .accept(MediaType.APPLICATION_JSON)
        .body(code)
        .post("/test/load-routes/MyRoute")
        .then()
            .statusCode(200)
        .extract()
            .body()
            .jsonPath();

    assertThat(p.getList("components", String.class)).contains("direct", "log");
    assertThat(p.getList("routes", String.class)).contains("yaml");
    assertThat(p.getList("endpoints", String.class)).contains("direct://yaml", "log://yaml");
}
 
Example #6
Source File: ExtensionTest.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadRoutes() throws IOException {
    String code;

    try (InputStream is = ExtensionTest.class.getResourceAsStream("/routes.xml")) {
        code = IOHelper.loadText(is);
    }

    JsonPath p = RestAssured.given()
        .contentType(MediaType.TEXT_PLAIN)
        .accept(MediaType.APPLICATION_JSON)
        .body(code)
        .post("/test/load-routes/MyRoute")
        .then()
            .statusCode(200)
        .extract()
            .body()
            .jsonPath();

    assertThat(p.getList("components", String.class)).contains("direct", "log");
    assertThat(p.getList("routes", String.class)).contains("xml");
    assertThat(p.getList("endpoints", String.class)).contains("direct://xml", "log://xml");
}
 
Example #7
Source File: TelegramRoutes.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
private static void load(String path, Exchange exchange) {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream(IOHelper.DEFAULT_BUFFER_SIZE);
            InputStream in = ResourceHelper.resolveMandatoryResourceAsInputStream(exchange.getContext(), path)) {
        IOHelper.copy(in, out, IOHelper.DEFAULT_BUFFER_SIZE);

        final byte[] bytes = out.toByteArray();
        exchange.getMessage().setBody(bytes);
        exchange.getMessage().setHeader("Content-Length", bytes.length);
        exchange.getMessage().setHeader("Content-Type", "application/json; charset=UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: FastCamelContext.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
private String getJsonSchema(String packageName, String name) throws IOException {
    String path = packageName.replace('.', '/') + "/" + name + ".json";
    InputStream inputStream = getClassResolver().loadResourceAsStream(path);

    if (inputStream != null) {
        try {
            return IOHelper.loadText(inputStream);
        } finally {
            IOHelper.close(inputStream);
        }
    }

    return null;
}
 
Example #9
Source File: EmbeddedZookeeper.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private static String send4LetterWord(String hp, String cmd) throws IOException {
    String split[] = hp.split(":");
    String host = split[0];
    int port;
    try {
        port = Integer.parseInt(split[1]);
    } catch (RuntimeException e) {
        throw new RuntimeException("Problem parsing " + hp + e.toString());
    }

    Socket sock = new Socket(host, port);
    BufferedReader reader = null;
    try {
        OutputStream outstream = sock.getOutputStream();
        outstream.write(cmd.getBytes());
        outstream.flush();

        reader = IOHelper.buffered(new InputStreamReader(sock.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        return sb.toString();
    } finally {
        sock.close();
        if (reader != null) {
            reader.close();
        }
    }
}
 
Example #10
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #11
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #12
Source File: patched.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #13
Source File: original.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #14
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}
 
Example #15
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 4 votes vote down vote up
/**
 * Common work which must be done when we are done multicasting.
 * <p/>
 * This logic applies for both running synchronous and asynchronous as there are multiple exist points
 * when using the asynchronous routing engine. And therefore we want the logic in one method instead
 * of being scattered.
 *
 * @param original     the original exchange
 * @param subExchange  the current sub exchange, can be <tt>null</tt> for the synchronous part
 * @param pairs        the pairs with the exchanges to process
 * @param callback     the callback
 * @param doneSync     the <tt>doneSync</tt> parameter to call on callback
 * @param forceExhaust whether or not error handling is exhausted
 */
protected void doDone(Exchange original, Exchange subExchange, final Iterable<ProcessorExchangePair> pairs,
                      AsyncCallback callback, boolean doneSync, boolean forceExhaust) {

    // we are done so close the pairs iterator
    if (pairs != null && pairs instanceof Closeable) {
        IOHelper.close((Closeable) pairs, "pairs", LOG);
    }

    AggregationStrategy strategy = getAggregationStrategy(subExchange);
    // invoke the on completion callback
    if (strategy instanceof CompletionAwareAggregationStrategy) {
        ((CompletionAwareAggregationStrategy) strategy).onCompletion(subExchange);
    }

    // cleanup any per exchange aggregation strategy
    removeAggregationStrategyFromExchange(original);

    // we need to know if there was an exception, and if the stopOnException option was enabled
    // also we would need to know if any error handler has attempted redelivery and exhausted
    boolean stoppedOnException = false;
    boolean exception = false;
    boolean exhaust = forceExhaust || subExchange != null && (subExchange.getException() != null || ExchangeHelper.isRedeliveryExhausted(subExchange));
    if (original.getException() != null || subExchange != null && subExchange.getException() != null) {
        // there was an exception and we stopped
        stoppedOnException = isStopOnException();
        exception = true;
    }

    // must copy results at this point
    if (subExchange != null) {
        if (stoppedOnException) {
            // if we stopped due an exception then only propagte the exception
            original.setException(subExchange.getException());
        } else {
            // copy the current result to original so it will contain this result of this eip
            ExchangeHelper.copyResults(original, subExchange);
        }
    }

    // .. and then if there was an exception we need to configure the redelivery exhaust
    // for example the noErrorHandler will not cause redelivery exhaust so if this error
    // handled has been in use, then the exhaust would be false (if not forced)
    if (exception) {
        // multicast uses error handling on its output processors and they have tried to redeliver
        // so we shall signal back to the other error handlers that we are exhausted and they should not
        // also try to redeliver as we will then do that twice
        original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust);
    }

    callback.done(doneSync);
}