Java 类org.apache.camel.util.IOHelper 实例源码

项目:camel-atlasmap    文件:AtlasEndpoint.java   
private synchronized AtlasContextFactory getAtlasContextFactory() throws Exception {
    if (atlasContextFactory == null) {

        Properties properties = new Properties();

        // load the properties from property file which may overrides the default ones
        if (ObjectHelper.isNotEmpty(getPropertiesFile())) {
            InputStream reader = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(),
                    getPropertiesFile());
            try {
                properties.load(reader);
                log.info("Loaded the Atlas properties file " + getPropertiesFile());
            } finally {
                IOHelper.close(reader, getPropertiesFile(), log);
            }
            log.debug("Initializing AtlasContextFactory with properties {}", properties);
            atlasContextFactory = new DefaultAtlasContextFactory(properties);
        } else {
            atlasContextFactory = DefaultAtlasContextFactory.getInstance();
        }
    }
    return atlasContextFactory;
}
项目:Camel    文件:MimeMultipartDataFormatTest.java   
@Test
public void roundtripWithBinaryAttachments() throws IOException {
    String attContentType = "application/binary";
    byte[] attText = {0, 1, 2, 3, 4, 5, 6, 7};
    String attFileName = "Attachment File Name";
    in.setBody("Body text");
    DataSource ds = new ByteArrayDataSource(attText, attContentType);
    in.addAttachment(attFileName, new DataHandler(ds));
    Exchange result = template.send("direct:roundtrip", exchange);
    Message out = result.getOut();
    assertEquals("Body text", out.getBody(String.class));
    assertTrue(out.hasAttachments());
    assertEquals(1, out.getAttachmentNames().size());
    assertThat(out.getAttachmentNames(), hasItem(attFileName));
    DataHandler dh = out.getAttachment(attFileName);
    assertNotNull(dh);
    assertEquals(attContentType, dh.getContentType());
    InputStream is = dh.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, os);
    assertArrayEquals(attText, os.toByteArray());
}
项目:Camel    文件:ScpOperations.java   
private String readLine(InputStream is) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    try {
        int c;
        do {
            c = is.read();
            if (c == '\n') {
                return bytes.toString();
            }
            bytes.write(c);
        } while (c != -1);
    } finally {
        IOHelper.close(bytes);
    }

    String message = "[scp] Unexpected end of stream";
    throw new IOException(message);
}
项目:Camel    文件:XmlVerifierProcessor.java   
@Override
public void process(Exchange exchange) throws Exception { //NOPMD
    InputStream stream = exchange.getIn().getMandatoryBody(InputStream.class);
    try {
        // lets setup the out message before we invoke the signing
        // so that it can mutate it if necessary
        Message out = exchange.getOut();
        out.copyFrom(exchange.getIn());
        verify(stream, out);
        clearMessageHeaders(out);
    } catch (Exception e) {
        // remove OUT message, as an exception occurred
        exchange.setOut(null);
        throw e;
    } finally {
        IOHelper.close(stream, "input stream");
    }
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testMapWriteTextWithKey() throws Exception {
    if (!canTest()) {
        return;
    }
    String txtKey = "THEKEY";
    String txtValue = "CIAO MONDO !";
    template.sendBodyAndHeader("direct:write_text3", txtValue, "KEY", txtKey);

    Configuration conf = new Configuration();
    Path file1 = new Path("file:///" + TEMP_DIR.toUri() + "/test-camel-text3");
    FileSystem fs1 = FileSystem.get(file1.toUri(), conf);
    MapFile.Reader reader = new MapFile.Reader(fs1, "file:///" + TEMP_DIR.toUri() + "/test-camel-text3", conf);
    Text key = (Text) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Text value = (Text) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    assertEquals(key.toString(), txtKey);
    assertEquals(value.toString(), txtValue);

    IOHelper.close(reader);
}
项目:Camel    文件:StreamSourceCache.java   
public StreamSourceCache(StreamSource source, Exchange exchange) throws IOException {
    if (source.getInputStream() != null) {
        // set up CachedOutputStream with the properties
        CachedOutputStream cos = new CachedOutputStream(exchange);
        IOHelper.copyAndCloseInput(source.getInputStream(), cos);
        streamCache = cos.newStreamCache();
        readCache = null;
        setSystemId(source.getSystemId());
        setInputStream((InputStream) streamCache);
    } else if (source.getReader() != null) {
        String data = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, source.getReader());
        readCache = new ReaderCache(data);
        streamCache = null;
        setReader(readCache);
    } else {
        streamCache = null;
        readCache = null;
    }
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testWriteFloat() throws Exception {
    if (!canTest()) {
        return;
    }
    float aFloat = 12.34f;
    template.sendBody("direct:write_float", aFloat);

    Configuration conf = new Configuration();
    Path file1 = new Path("file:///" + TEMP_DIR.toUri() + "/test-camel-float");
    SequenceFile.Reader reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(file1));
    Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    float rFloat = ((FloatWritable) value).get();
    assertEquals(rFloat, aFloat, 0.0F);

    IOHelper.close(reader);
}
项目:Camel    文件:NIOConverter.java   
@Converter
public static ByteBuffer toByteBuffer(File file) throws IOException {
    InputStream in = null;
    try {
        byte[] buf = new byte[(int)file.length()];
        in = IOHelper.buffered(new FileInputStream(file));
        int sizeLeft = (int)file.length();
        int offset = 0;
        while (sizeLeft > 0) {
            int readSize = in.read(buf, offset, sizeLeft);
            sizeLeft -= readSize;
            offset += readSize;
        }
        return ByteBuffer.wrap(buf);
    } finally {
        IOHelper.close(in, "Failed to close file stream: " + file.getPath(), LOG);
    }
}
项目:Camel    文件:FlatpackEndpoint.java   
public Parser createDelimitedParser(Exchange exchange) throws InvalidPayloadException, IOException {
    Reader bodyReader = exchange.getIn().getMandatoryBody(Reader.class);

    Parser parser;
    if (ObjectHelper.isEmpty(getResourceUri())) {
        parser = getParserFactory().newDelimitedParser(bodyReader, delimiter, textQualifier);
    } else {
        InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), resourceUri);
        InputStreamReader reader = new InputStreamReader(is, IOHelper.getCharsetName(exchange));
        parser = getParserFactory().newDelimitedParser(reader, bodyReader, delimiter, textQualifier, ignoreFirstRecord);
    }

    if (isAllowShortLines()) {
        parser.setHandlingShortLines(true);
        parser.setIgnoreParseWarnings(true);
    }
    if (isIgnoreExtraColumns()) {
        parser.setIgnoreExtraColumns(true);
        parser.setIgnoreParseWarnings(true);
    }

    return parser;
}
项目:Camel    文件:CachedOutputStreamTest.java   
public void testCachedStreamAccessStreamWhenExchangeOnCompletion() throws Exception {
    context.start();
    CachedOutputStream cos = new CachedOutputStream(exchange, false);
    cos.write(TEST_STRING.getBytes("UTF-8"));

    File file = new File("target/cachedir");
    String[] files = file.list();
    assertEquals("we should have a temp file", 1, files.length);
    assertTrue("The file name should start with cos", files[0].startsWith("cos"));

    InputStream is = cos.getWrappedInputStream();
    exchange.getUnitOfWork().done(exchange);
    String temp = toString(is);
    assertEquals("Get a wrong stream content", temp, TEST_STRING);
    IOHelper.close(is);

    files = file.list();
    assertEquals("we should have a temp file", 0, files.length);
    IOHelper.close(cos);
}
项目:Camel    文件:MimeMultipartDataFormatTest.java   
@Test
public void roundtripWithTextAttachmentsHeadersInline() throws IOException {
    String attContentType = "text/plain";
    String attText = "Attachment Text";
    String attFileName = "Attachment File Name";
    in.setBody("Body text");
    in.setHeader(Exchange.CONTENT_TYPE, "text/plain;charset=iso8859-1;other-parameter=true");
    in.setHeader(Exchange.CONTENT_ENCODING, "UTF8");
    addAttachment(attContentType, attText, attFileName);
    Exchange result = template.send("direct:roundtripinlineheaders", exchange);
    Message out = result.getOut();
    assertEquals("Body text", out.getBody(String.class));
    assertThat(out.getHeader(Exchange.CONTENT_TYPE, String.class), startsWith("text/plain"));
    assertEquals("UTF8", out.getHeader(Exchange.CONTENT_ENCODING));
    assertTrue(out.hasAttachments());
    assertEquals(1, out.getAttachmentNames().size());
    assertThat(out.getAttachmentNames(), hasItem(attFileName));
    DataHandler dh = out.getAttachment(attFileName);
    assertNotNull(dh);
    assertEquals(attContentType, dh.getContentType());
    InputStream is = dh.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, os);
    assertEquals(attText, new String(os.toByteArray()));
}
项目:Camel    文件:MimeMultipartDataFormatTest.java   
@Test
public void roundtripWithTextAttachmentsAndBinaryContent() throws IOException {
    String attContentType = "text/plain";
    String attText = "Attachment Text";
    String attFileName = "Attachment File Name";
    in.setBody("Body text");
    in.setHeader(Exchange.CONTENT_TYPE, "text/plain;charset=iso8859-1;other-parameter=true");
    addAttachment(attContentType, attText, attFileName);
    Exchange result = template.send("direct:roundtripbinarycontent", exchange);
    Message out = result.getOut();
    assertEquals("Body text", out.getBody(String.class));
    assertThat(out.getHeader(Exchange.CONTENT_TYPE, String.class), startsWith("text/plain"));
    assertEquals("iso8859-1", out.getHeader(Exchange.CONTENT_ENCODING));
    assertTrue(out.hasAttachments());
    assertEquals(1, out.getAttachmentNames().size());
    assertThat(out.getAttachmentNames(), hasItem(attFileName));
    DataHandler dh = out.getAttachment(attFileName);
    assertNotNull(dh);
    assertEquals(attContentType, dh.getContentType());
    InputStream is = dh.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, os);
    assertEquals(attText, new String(os.toByteArray()));
}
项目:Camel    文件:FileLockExclusiveReadLockStrategy.java   
@Override
protected void doReleaseExclusiveReadLock(GenericFileOperations<File> operations,
                                          GenericFile<File> file, Exchange exchange) throws Exception {
    // must call super
    super.doReleaseExclusiveReadLock(operations, file, exchange);

    FileLock lock = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), FileLock.class);
    RandomAccessFile rac = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_EXCLUSIVE_LOCK), RandomAccessFile.class);

    String target = file.getFileName();
    if (lock != null) {
        Channel channel = lock.acquiredBy();
        try {
            lock.release();
        } finally {
            // close channel as well
            IOHelper.close(channel, "while releasing exclusive read lock for file: " + target, LOG);
            IOHelper.close(rac, "while releasing exclusive read lock for file: " + target, LOG);
        }
    }
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testProducer() throws Exception {
    if (!canTest()) {
        return;
    }
    template.sendBody("direct:start1", "PAPPO");

    Configuration conf = new Configuration();
    Path file1 = new Path("file:///" + TEMP_DIR.toUri() + "/test-camel1");
    SequenceFile.Reader reader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(file1));
    Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    assertEquals("PAPPO", value.toString());

    IOHelper.close(reader);
}
项目:Camel    文件:JettyChuckedFalseTest.java   
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {

            from("jetty:http://localhost:{{port}}/test?matchOnUriPrefix=true&chunked=false")
                .to("http://localhost:{{port2}}/other?bridgeEndpoint=true");

            from("jetty:http://localhost:{{port2}}/other").process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "image/jpeg");
                    CachedOutputStream stream = new CachedOutputStream(exchange);
                    stream.write("This is hello world.".getBytes());
                    exchange.getOut().setBody(stream.getInputStream());
                    IOHelper.close(stream);
                }
            });
        }
    };
}
项目:Camel    文件:TestUtil.java   
public static String readStream(InputStream is) throws IOException {
    try {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = IOHelper.buffered(new InputStreamReader(is, "UTF-8"));
        String line;
        boolean comment = false;
        while ((line = reader.readLine()) != null) {

            // skip comments such as ASF license headers
            if (line.startsWith("<!--")) {
                comment = true;
            } else if (line.startsWith("-->")) {
                comment = false;
            } else {
                if (!comment) {
                    sb.append(line).append("\n");
                }
            }
        }
        return sb.toString();
    } finally {
        is.close();
    }
}
项目:Camel    文件:LevelDBAggregationRepository.java   
private int size(final String repositoryName) {
    DBIterator it = levelDBFile.getDb().iterator();

    String prefix = repositoryName + '\0';
    int count = 0;
    try {
        for (it.seek(keyBuilder(repositoryName, "")); it.hasNext(); it.next()) {
            if (!asString(it.peekNext().getKey()).startsWith(prefix)) {
                break;
            }
            count++;
        }
    } finally {
        // Make sure you close the iterator to avoid resource leaks.
        IOHelper.close(it);
    }

    LOG.debug("Size of repository [{}] -> {}", repositoryName, count);
    return count;
}
项目:Camel    文件:PGPDataFormatTest.java   
void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception, IOException, PGPException,
        UnsupportedEncodingException {
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
            .setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath)));
    OutputStream encOut = encGen.open(bos, new byte[512]);
    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]);

    try {
        litOut.write("Test Message Without Compression".getBytes("UTF-8"));
        litOut.flush();
    } finally {
        IOHelper.close(litOut);
        IOHelper.close(encOut, bos);
    }
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testWriteLong() throws Exception {
    if (!canTest()) {
        return;
    }
    long aLong = 1234567890;
    template.sendBody("direct:write_long", aLong);

    Configuration conf = new Configuration();
    Path file1 = new Path("file:///" + TEMP_DIR.toUri() + "/test-camel-long");
    FileSystem fs1 = FileSystem.get(file1.toUri(), conf);
    SequenceFile.Reader reader = new SequenceFile.Reader(fs1, file1, conf);
    Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    long rLong = ((LongWritable) value).get();
    assertEquals(rLong, aLong);

    IOHelper.close(reader);
}
项目:Camel    文件:DefaultHttpBinding.java   
protected void doWriteGZIPResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
    byte[] bytes;
    try {
        bytes = message.getMandatoryBody(byte[].class);
    } catch (InvalidPayloadException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    }

    byte[] data = GZIPHelper.compressGZIP(bytes);
    ServletOutputStream os = response.getOutputStream();
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Streaming response as GZIP in non-chunked mode with content-length {} and buffer size: {}", data.length, response.getBufferSize());
        }
        response.setContentLength(data.length);
        os.write(data);
        os.flush();
    } finally {
        IOHelper.close(os);
    }
}
项目:Camel    文件:BundleContextUtils.java   
public static String getComponentDocumentation(BundleContext bundleContext,
                                               CamelContext camelContext,
                                               String componentName) throws IOException {
    String path = CamelContextHelper.COMPONENT_DOCUMENTATION_PREFIX + componentName + ".html";
    Bundle[] bundles = bundleContext.getBundles();
    for (Bundle bundle : bundles) {
        URL resource = bundle.getResource(path);
        if (resource != null) {
            InputStream inputStream = resource.openStream();
            if (inputStream != null) {
                return IOHelper.loadText(inputStream);
            }
        }
    }
    return null;
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testWriteTextWithKey() throws Exception {
    if (!canTest()) {
        return;
    }
    String txtKey = "THEKEY";
    String txtValue = "CIAO MONDO !";
    template.sendBodyAndHeader("direct:write_text2", txtValue, "KEY", txtKey);

    Configuration conf = new Configuration();
    Path file1 = new Path("file:///" + TEMP_DIR.toUri() + "/test-camel-text2");
    FileSystem fs1 = FileSystem.get(file1.toUri(), conf);
    SequenceFile.Reader reader = new SequenceFile.Reader(fs1, file1, conf);
    Text key = (Text) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Text value = (Text) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    assertEquals(key.toString(), txtKey);
    assertEquals(value.toString(), txtValue);

    IOHelper.close(reader);
}
项目:Camel    文件:FileProducerCharsetUTFtoUTFTest.java   
public void testFileProducerCharsetUTFtoUTF() throws Exception {
    oneExchangeDone.matchesMockWaitTime();

    File file = new File("target/charset/output.txt");
    assertTrue("File should exist", file.exists());

    InputStream fis = IOHelper.buffered(new FileInputStream(file));
    byte[] buffer = new byte[100];

    int len = fis.read(buffer);
    assertTrue("Should read data: " + len, len != -1);
    byte[] data = new byte[len];
    System.arraycopy(buffer, 0, data, 0, len);
    fis.close();

    // data should be in utf, where the danish ae is -61 -90
    assertEquals(5, data.length);
    assertEquals(65, data[0]);
    assertEquals(66, data[1]);
    assertEquals(67, data[2]);
    assertEquals(-61, data[3]);
    assertEquals(-90, data[4]);
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testMapWriteTextWithKey() throws Exception {
    if (!canTest()) {
        return;
    }
    String txtKey = "THEKEY";
    String txtValue = "CIAO MONDO !";
    template.sendBodyAndHeader("direct:write_text3", txtValue, "KEY", txtKey);

    Configuration conf = new Configuration();
    MapFile.Reader reader = new MapFile.Reader(new Path("file:///" + TEMP_DIR.toUri() + "/test-camel-text3"), conf);
    Text key = (Text) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Text value = (Text) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    assertEquals(key.toString(), txtKey);
    assertEquals(value.toString(), txtValue);

    IOHelper.close(reader);
}
项目:Camel    文件:ZipFileDataFormat.java   
@Override
public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception {
    String filename = exchange.getIn().getHeader(FILE_NAME, String.class);
    if (filename == null) {
        // generate the file name as the camel file component would do
        filename = StringHelper.sanitize(exchange.getIn().getMessageId());
    } else {
        filename = Paths.get(filename).getFileName().toString(); // remove any path elements
    }

    ZipOutputStream zos = new ZipOutputStream(stream);
    zos.putNextEntry(new ZipEntry(filename));

    InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph);

    try {
        IOHelper.copy(is, zos);
    } finally {
        IOHelper.close(is, zos);
    }

    String newFilename = filename + ".zip";
    exchange.getOut().setHeader(FILE_NAME, newFilename);
}
项目:Camel    文件:HL7MLLPCodecLongTest.java   
@Test
public void testSendHL7Message() throws Exception {
    // START SNIPPET: e2
    BufferedReader in = IOHelper.buffered(new InputStreamReader(getClass().getResourceAsStream("/mdm_t02.txt")));
    String line = "";
    String message = "";
    while (line != null) {
        if ((line = in.readLine()) != null) {
            message += line + "\r";
        }
    }
    message = message.substring(0, message.length() - 1);
    assertEquals(70010, message.length());
    String out = template.requestBody("mina2:tcp://127.0.0.1:" + getPort() + "?sync=true&codec=#hl7codec", message, String.class);
    assertEquals("some response", out);
    // END SNIPPET: e2
}
项目:Camel    文件:ModelHelper.java   
/**
 * Marshal the xml to the model definition
 *
 * @param context the CamelContext, if <tt>null</tt> then {@link org.apache.camel.spi.ModelJAXBContextFactory} is not in use
 * @param xml     the xml
 * @param type    the definition type to return, will throw a {@link ClassCastException} if not the expected type
 * @return the model definition
 * @throws javax.xml.bind.JAXBException is thrown if error unmarshalling from xml to model
 */
public static <T extends NamedNode> T createModelFromXml(CamelContext context, String xml, Class<T> type) throws JAXBException {
    JAXBContext jaxbContext;
    if (context == null) {
        jaxbContext = createJAXBContext();
    } else {
        jaxbContext = context.getModelJAXBContextFactory().newJAXBContext();
    }

    StringReader reader = new StringReader(xml);
    Object result;
    try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        result = unmarshaller.unmarshal(reader);
    } finally {
        IOHelper.close(reader);
    }

    if (result == null) {
        throw new JAXBException("Cannot unmarshal to " + type + " using JAXB from XML: " + xml);
    }
    return type.cast(result);
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testWriteInt() throws Exception {
    if (!canTest()) {
        return;
    }
    int anInt = 1234;
    template.sendBody("direct:write_int", anInt);

    Configuration conf = new Configuration();
    Path file1 = new Path("file:///" + TEMP_DIR.toUri() + "/test-camel-int");
    FileSystem fs1 = FileSystem.get(file1.toUri(), conf);
    SequenceFile.Reader reader = new SequenceFile.Reader(fs1, file1, conf);
    Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    int rInt = ((IntWritable) value).get();
    assertEquals(rInt, anInt);

    IOHelper.close(reader);
}
项目:Camel    文件:BeanIODataFormat.java   
private List<Object> readModels(Exchange exchange, InputStream stream) {
    List<Object> results = new ArrayList<Object>();
    BufferedReader streamReader = IOHelper.buffered(new InputStreamReader(stream, getEncoding()));

    BeanReader in = factory.createReader(getStreamName(), streamReader);

    try {
        if (ObjectHelper.isNotEmpty(configuration.getBeanReaderErrorHandler())) {
            in.setErrorHandler(configuration.getBeanReaderErrorHandler());
        } else {
            in.setErrorHandler(new BeanIOErrorHandler(configuration));
        }

        Object readObject;
        while ((readObject = in.read()) != null) {
            if (readObject instanceof BeanIOHeader) {
                exchange.getOut().getHeaders().putAll(((BeanIOHeader) readObject).getHeaders());
            }
            results.add(readObject);
        }
    } finally {
        in.close();
    }

    return results;
}
项目:Camel    文件:TokenXMLExpressionIterator.java   
/**
 * Strategy to evaluate the exchange
 *
 * @param exchange   the exchange
 * @param closeStream whether to close the stream before returning from this method.
 * @return the evaluated value
 */
protected Object doEvaluate(Exchange exchange, boolean closeStream) {
    InputStream in = null;
    try {
        in = exchange.getIn().getMandatoryBody(InputStream.class);
        // we may read from a file, and want to support custom charset defined on the exchange
        String charset = IOHelper.getCharsetName(exchange);
        return createIterator(exchange, in, charset);
    } catch (InvalidPayloadException e) {
        exchange.setException(e);
        // must close input stream
        IOHelper.close(in);
        return null;
    } finally {
        if (closeStream) {
            IOHelper.close(in);
        }
    }
}
项目:Camel    文件:CxfRsProducer.java   
protected void setupClientMatrix(WebClient client, Exchange exchange) throws Exception {

    org.apache.cxf.message.Message cxfMessage = (org.apache.cxf.message.Message) exchange.getIn().getHeader("CamelCxfMessage");
    if (cxfMessage != null) {
        String requestURL = (String)cxfMessage.get("org.apache.cxf.request.uri"); 
        String matrixParam = null;
        int matrixStart = requestURL.indexOf(";");
        int matrixEnd = requestURL.indexOf("?") > -1 ? requestURL.indexOf("?") : requestURL.length();
        Map<String, String> maps = null;
        if (requestURL != null && matrixStart > 0) {
            matrixParam = requestURL.substring(matrixStart + 1, matrixEnd);
            if (matrixParam != null) {
                maps = getMatrixParametersFromMatrixString(matrixParam, IOHelper.getCharsetName(exchange));
            }
        }
        if (maps != null) {
            for (Map.Entry<String, String> entry : maps.entrySet()) {
                client.matrix(entry.getKey(), entry.getValue());
                LOG.debug("Matrix param " + entry.getKey() + " :: " + entry.getValue());
            }
        }
    }
}
项目:Camel    文件:Main.java   
protected void findLocations(Set<String> locations, ClassLoader classLoader) throws IOException {
    Enumeration<URL> resources = classLoader.getResources(LOCATION_PROPERTIES);
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        BufferedReader reader = IOHelper.buffered(new InputStreamReader(url.openStream(), UTF8));
        try {
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                line = line.trim();
                if (line.startsWith("#") || line.length() == 0) {
                    continue;
                }
                locations.add(line);
            }
        } finally {
            IOHelper.close(reader, null, LOG);
        }
    }
}
项目:Camel    文件:HdfsProducerTest.java   
@Test
public void testBloomMapWriteText() throws Exception {
    if (!canTest()) {
        return;
    }
    String txtKey = "THEKEY";
    String txtValue = "CIAO MONDO !";
    template.sendBodyAndHeader("direct:write_text5", txtValue, "KEY", txtKey);

    Configuration conf = new Configuration();
    BloomMapFile.Reader reader = new BloomMapFile.Reader(new Path("file:///" + TEMP_DIR.toUri() + "/test-camel-text5"), conf);
    Text key = (Text) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
    Text value = (Text) ReflectionUtils.newInstance(reader.getValueClass(), conf);
    reader.next(key, value);
    assertEquals(key.toString(), txtKey);
    assertEquals(value.toString(), txtValue);

    IOHelper.close(reader);
}
项目:Camel    文件:DefaultCamelContext.java   
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";
        ClassResolver resolver = getClassResolver();
        InputStream inputStream = resolver.loadResourceAsStream(path);
        if (inputStream != null) {
            log.debug("Loading eip JSON Schema for: {} using class resolver: {} -> {}", new Object[]{eipName, resolver, inputStream});
            try {
                return IOHelper.loadText(inputStream);
            } finally {
                IOHelper.close(inputStream);
            }
        }
    }
    return null;
}
项目:Camel    文件:BeanIODataFormat.java   
@Override
protected void doStart() throws Exception {
    ObjectHelper.notNull(getStreamName(), "Stream name not configured.");
    if (factory == null) {
        // Create the stream factory that will be used to read/write objects.
        factory = StreamFactory.newInstance();

        // Load the mapping file using the resource helper to ensure it can be loaded in OSGi and other environments
        InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), getMapping());
        try {
            if (getProperties() != null) {
                factory.load(is, getProperties());
            } else {
                factory.load(is);
            }
        } finally {
            IOHelper.close(is);
        }
    }
}
项目:Camel    文件:QuartzComponent.java   
private Properties loadProperties() throws SchedulerException {
    Properties answer = getProperties();
    if (answer == null && getPropertiesFile() != null) {
        LOG.info("Loading Quartz properties file from: {}", getPropertiesFile());
        InputStream is = null;
        try {
            is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), getPropertiesFile());
            answer = new Properties();
            answer.load(is);
        } catch (IOException e) {
            throw new SchedulerException("Error loading Quartz properties file: " + getPropertiesFile(), e);
        } finally {
            IOHelper.close(is);
        }
    }
    return answer;
}
项目:Camel    文件:FileOperations.java   
private void writeFileByStream(InputStream in, File target) throws IOException {
    FileChannel out = null;
    try {
        out = prepareOutputFileChannel(target);
        LOG.debug("Using InputStream to write file: {}", target);
        int size = endpoint.getBufferSize();
        byte[] buffer = new byte[size];
        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            if (bytesRead < size) {
                byteBuffer.limit(bytesRead);
            }
            out.write(byteBuffer);
            byteBuffer.clear();
        }
    } finally {
        IOHelper.close(in, target.getName(), LOG);
        IOHelper.close(out, target.getName(), LOG, endpoint.isForceWrites());
    }
}
项目:drinkwater-java    文件:PropertiesResolver.java   
private Properties loadPropertiesFromFilePath(boolean ignoreMissingLocation, String path, String encoding) throws IOException {
    Properties answer = new Properties();

    if (path.startsWith("file:")) {
        path = ObjectHelper.after(path, "file:");
    }

    InputStream is = null;
    Reader reader = null;
    try {
        is = new FileInputStream(path);
        if (encoding != null) {
            reader = new BufferedReader(new InputStreamReader(is, encoding));
            answer.load(reader);
        } else {
            answer.load(is);
        }
    } catch (FileNotFoundException e) {
        if (!ignoreMissingLocation) {
            throw e;
        }
    } finally {
        IOHelper.close(reader, is);
    }

    return answer;
}
项目:drinkwater-java    文件:PropertiesResolver.java   
private Properties loadPropertiesFromClasspath(boolean ignoreMissingLocation, String path, String encoding) throws IOException {
    Properties answer = new Properties();

    if (path.startsWith("classpath:")) {
        path = ObjectHelper.after(path, "classpath:");
    }
    if(!path.startsWith("/")){
        path = "/" + path;
    }

    InputStream is = propLocator.getClass().getResourceAsStream(path);
    Reader reader = null;
    if (is == null) {
        if (!ignoreMissingLocation) {
            throw new FileNotFoundException("Properties file " + path + " not found in classpath");
        }
    } else {
        try {
            if (encoding != null) {
                reader = new BufferedReader(new InputStreamReader(is, encoding));
                answer.load(reader);
            } else {
                answer.load(is);
            }
        } finally {
            IOHelper.close(reader, is);
        }
    }
    return answer;
}
项目:Camel    文件:ZipAggregationStrategyEmptyFileTest.java   
@Test
public void testEmptyFile() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:aggregateToZipEntry");
    mock.expectedMessageCount(1);

    template.sendBody("file:target/foo", "Hello");
    // empty file which is not aggregated
    template.sendBody("file:target/foo", "");
    template.sendBody("file:target/foo", "Bye");
    template.sendBody("file:target/foo", "Howdy");

    assertMockEndpointsSatisfied();

    Thread.sleep(500);

    File[] files = new File("target/out").listFiles();
    assertTrue(files != null);
    assertTrue("Should be a file in target/out directory", files.length > 0);

    File resultFile = files[0];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(resultFile));
    try {
        int fileCount = 0;
        for (ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()) {
            fileCount = fileCount + 1;
        }
        assertEquals("Zip file should contains " + ZipAggregationStrategyEmptyFileTest.EXPECTED_NO_FILES + " files", ZipAggregationStrategyEmptyFileTest.EXPECTED_NO_FILES, fileCount);
    } finally {
        IOHelper.close(zin);
    }
}