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

项目:eds    文件:CamelJmsTestHelper.java   
private static ConnectionFactory createPersistentConnectionFactory(String options) {
        // using a unique broker name improves testing when running the entire test suite in the same JVM
        int id = counter.incrementAndGet();

        // use an unique data directory in target
        String dir = "target/activemq-data-" + id;

        // remove dir so its empty on startup
        FileUtil.removeDir(new File(dir));

        String url = "vm://test-broker-" + id + "?broker.persistent=true&broker.useJmx=false&broker.dataDirectory=" + dir;
        if (options != null) {
            url = url + "&" + options;
        }
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        // optimize AMQ to be as fast as possible so unit testing is quicker
        connectionFactory.setCopyMessageOnSend(false);
        connectionFactory.setOptimizeAcknowledge(true);
        connectionFactory.setOptimizedMessageDispatch(true);
        connectionFactory.setAlwaysSessionAsync(false);
//        connectionFactory.setTrustAllPackages(true);
        return connectionFactory;
    }
项目:Camel    文件:ExpressionBuilder.java   
public static Expression fileOnlyNameExpression() {
    return new ExpressionAdapter() {
        public Object evaluate(Exchange exchange) {
            String answer = exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY, String.class);
            if (answer == null) {
                answer = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
                answer = FileUtil.stripPath(answer);
            }
            return answer;
        }

        @Override
        public String toString() {
            return "file:onlyname";
        }
    };
}
项目:Camel    文件:FileOperations.java   
public boolean renameFile(String from, String to) throws GenericFileOperationFailedException {
    boolean renamed = false;
    File file = new File(from);
    File target = new File(to);
    try {
        if (endpoint.isRenameUsingCopy()) {
            renamed = FileUtil.renameFileUsingCopy(file, target);
        } else {
            renamed = FileUtil.renameFile(file, target, endpoint.isCopyAndDeleteOnRenameFail());
        }
    } catch (IOException e) {
        throw new GenericFileOperationFailedException("Error renaming file from " + from + " to " + to, e);
    }

    return renamed;
}
项目:Camel    文件:FileComponent.java   
protected GenericFileEndpoint<File> buildFileEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    // the starting directory must be a static (not containing dynamic expressions)
    if (StringHelper.hasStartToken(remaining, "simple")) {
        throw new IllegalArgumentException("Invalid directory: " + remaining
                + ". Dynamic expressions with ${ } placeholders is not allowed."
                + " Use the fileName option to set the dynamic expression.");
    }

    File file = new File(remaining);

    FileEndpoint result = new FileEndpoint(uri, this);
    result.setFile(file);

    GenericFileConfiguration config = new GenericFileConfiguration();
    config.setDirectory(FileUtil.isAbsolute(file) ? file.getAbsolutePath() : file.getPath());
    result.setConfiguration(config);

    return result;
}
项目:Camel    文件:GenericFileEndpoint.java   
/**
 * Configures the given message with the file which sets the body to the
 * file object.
 */
public void configureMessage(GenericFile<T> file, Message message) {
    message.setBody(file);

    if (flatten) {
        // when flatten the file name should not contain any paths
        message.setHeader(Exchange.FILE_NAME, file.getFileNameOnly());
    } else {
        // compute name to set on header that should be relative to starting directory
        String name = file.isAbsolute() ? file.getAbsoluteFilePath() : file.getRelativeFilePath();

        // skip leading endpoint configured directory
        String endpointPath = getConfiguration().getDirectory() + getFileSeparator();

        // need to normalize paths to ensure we can match using startsWith
        endpointPath = FileUtil.normalizePath(endpointPath);
        String copyOfName = FileUtil.normalizePath(name);
        if (ObjectHelper.isNotEmpty(endpointPath) && copyOfName.startsWith(endpointPath)) {
            name = name.substring(endpointPath.length());
        }

        // adjust filename
        message.setHeader(Exchange.FILE_NAME, name);
    }
}
项目:Camel    文件:GenericFileEndpoint.java   
/**
 * Strategy to configure the move, preMove, or moveExisting option based on a String input.
 *
 * @param expression the original string input
 * @return configured string or the original if no modifications is needed
 */
protected String configureMoveOrPreMoveExpression(String expression) {
    // if the expression already have ${ } placeholders then pass it unmodified
    if (StringHelper.hasStartToken(expression, "simple")) {
        return expression;
    }

    // remove trailing slash
    expression = FileUtil.stripTrailingSeparator(expression);

    StringBuilder sb = new StringBuilder();

    // if relative then insert start with the parent folder
    if (!isAbsolute(expression)) {
        sb.append("${file:parent}");
        sb.append(getFileSeparator());
    }
    // insert the directory the end user provided
    sb.append(expression);
    // append only the filename (file:name can contain a relative path, so we must use onlyname)
    sb.append(getFileSeparator());
    sb.append("${file:onlyname}");

    return sb.toString();
}
项目:Camel    文件:MarkerFileExclusiveReadLockStrategy.java   
@Override
public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations,
                                        GenericFile<File> file, Exchange exchange) throws Exception {

    if (!markerFile) {
        // if not using marker file then we assume acquired
        return true;
    }

    String lockFileName = getLockFileName(file);
    LOG.trace("Locking the file: {} using the lock file name: {}", file, lockFileName);

    // create a plain file as marker filer for locking (do not use FileLock)
    boolean acquired = FileUtil.createNewFile(new File(lockFileName));

    // store read-lock state
    exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_ACQUIRED), acquired);
    exchange.setProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_NAME), lockFileName);

    return acquired;
}
项目:Camel    文件:MarkerFileExclusiveReadLockStrategy.java   
protected void doReleaseExclusiveReadLock(GenericFileOperations<File> operations,
                                          GenericFile<File> file, Exchange exchange) throws Exception {
    if (!markerFile) {
        // if not using marker file then nothing to release
        return;
    }

    boolean acquired = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_ACQUIRED), false, Boolean.class);

    // only release the file if camel get the lock before
    if (acquired) {
        String lockFileName = exchange.getProperty(asReadLockKey(file, Exchange.FILE_LOCK_FILE_NAME), String.class);
        File lock = new File(lockFileName);

        if (lock.exists()) {
            LOG.trace("Unlocking file: {}", lockFileName);
            boolean deleted = FileUtil.deleteFile(lock);
            LOG.trace("Lock file: {} was deleted: {}", lockFileName, deleted);
        }
    }
}
项目:Camel    文件:FileLanguageTest.java   
public void testFile() throws Exception {
    assertExpression("${file:ext}", "txt");
    assertExpression("${file:name.ext}", "txt");
    assertExpression("${file:name.ext.single}", "txt");
    assertExpression("${file:name}", "test" + File.separator + file.getName());
    assertExpression("${file:name.noext}", "test" + File.separator + "hello");
    assertExpression("${file:name.noext.single}", "test" + File.separator + "hello");
    assertExpression("${file:onlyname}", file.getName());
    assertExpression("${file:onlyname.noext}", "hello");
    assertExpression("${file:onlyname.noext.single}", "hello");
    assertExpression("${file:parent}", file.getParent());
    assertExpression("${file:path}", file.getPath());
    assertExpression("${file:absolute}", FileUtil.isAbsolute(file));
    assertExpression("${file:absolute.path}", file.getAbsolutePath());
    assertExpression("${file:length}", file.length());
    assertExpression("${file:size}", file.length());

    // modified is a long object
    Long modified = SimpleLanguage.simple("${file:modified}").evaluate(exchange, Long.class);
    assertEquals(file.lastModified(), modified.longValue());
}
项目:Camel    文件:FileLanguageTest.java   
public void testFileUsingAlternativeStartToken() throws Exception {
    assertExpression("$simple{file:ext}", "txt");
    assertExpression("$simple{file:name.ext}", "txt");
    assertExpression("$simple{file:name}", "test" + File.separator + file.getName());
    assertExpression("$simple{file:name.noext}", "test" + File.separator + "hello");
    assertExpression("$simple{file:onlyname}", file.getName());
    assertExpression("$simple{file:onlyname.noext}", "hello");
    assertExpression("$simple{file:parent}", file.getParent());
    assertExpression("$simple{file:path}", file.getPath());
    assertExpression("$simple{file:absolute}", FileUtil.isAbsolute(file));
    assertExpression("$simple{file:absolute.path}", file.getAbsolutePath());
    assertExpression("$simple{file:length}", file.length());
    assertExpression("$simple{file:size}", file.length());

    // modified is a long object
    long modified = SimpleLanguage.simple("${file:modified}").evaluate(exchange, long.class);
    assertEquals(file.lastModified(), modified);
}
项目:Camel    文件:BarcodeTestBase.java   
protected void checkImage(MockEndpoint mock, int height, int width, String type, BarcodeFormat format) throws IOException {
    Exchange ex = mock.getReceivedExchanges().get(0);
    File in = ex.getIn().getBody(File.class);
    FileInputStream fis = new FileInputStream(in);

    // check image
    BufferedImage i = ImageIO.read(fis);
    IOHelper.close(fis);

    assertTrue(height >= i.getHeight());
    assertTrue(width >= i.getWidth());
    this.checkType(in, type);
    this.checkFormat(in, format);

    FileUtil.deleteFile(in);
}
项目:Camel    文件:SftpConsumer.java   
@Override
protected boolean pollDirectory(String fileName, List<GenericFile<ChannelSftp.LsEntry>> fileList, int depth) {
    String currentDir = null;
    if (isStepwise()) {
        // must remember current dir so we stay in that directory after the poll
        currentDir = operations.getCurrentDirectory();
    }

    // strip trailing slash
    fileName = FileUtil.stripTrailingSeparator(fileName);

    boolean answer = doPollDirectory(fileName, null, fileList, depth);
    if (currentDir != null) {
        operations.changeCurrentDirectory(currentDir);
    }

    return answer;
}
项目:Camel    文件:FtpConsumer.java   
@Override
protected boolean pollDirectory(String fileName, List<GenericFile<FTPFile>> fileList, int depth) {
    String currentDir = null;
    if (isStepwise()) {
        // must remember current dir so we stay in that directory after the poll
        currentDir = operations.getCurrentDirectory();
    }

    // strip trailing slash
    fileName = FileUtil.stripTrailingSeparator(fileName);

    boolean answer = doPollDirectory(fileName, null, fileList, depth);
    if (currentDir != null) {
        operations.changeCurrentDirectory(currentDir);
    }

    return answer;
}
项目:Camel    文件:SftpProduceTempFileTest.java   
@Test
public void testSftpTempFileNoStartingPath() throws Exception {
    if (!canTest()) {
        return;
    }

    template.sendBodyAndHeader("sftp://localhost:" + getPort()
            + "/?username=admin&password=admin&tempFileName=temp-${file:name}", "Hello World", Exchange.FILE_NAME, "hello.txt");

    File file = new File("hello.txt");
    assertTrue("File should exist: " + file, file.exists());
    assertEquals("Hello World", context.getTypeConverter().convertTo(String.class, file));

    // delete file when we are done testing
    FileUtil.deleteFile(file);
}
项目:Camel    文件:CamelJmsTestHelper.java   
public static ConnectionFactory createPersistentConnectionFactory(String options) {
    // using a unique broker name improves testing when running the entire test suite in the same JVM
    int id = counter.incrementAndGet();

    // use an unique data directory in target
    String dir = "target/activemq-data-" + id;

    // remove dir so its empty on startup
    FileUtil.removeDir(new File(dir));

    String url = "vm://test-broker-" + id + "?broker.persistent=true&broker.useJmx=false&broker.dataDirectory=" + dir;
    if (options != null) {
        url = url + "&" + options;
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
    // optimize AMQ to be as fast as possible so unit testing is quicker
    connectionFactory.setCopyMessageOnSend(false);
    connectionFactory.setOptimizeAcknowledge(true);
    connectionFactory.setOptimizedMessageDispatch(true);
    connectionFactory.setAlwaysSessionAsync(false);
    connectionFactory.setTrustAllPackages(true);
    return connectionFactory;
}
项目:Camel    文件:FileConsumerIdempotentLoadStoreTest.java   
@SuppressWarnings("unchecked")
@Override
protected void setUp() throws Exception {
    deleteDirectory("target/fileidempotent");
    createDirectory("target/fileidempotent");

    File file = new File("target/fileidempotent/.filestore.dat");
    FileOutputStream fos = new FileOutputStream(file);

    // insert existing name to the file repo, so we should skip this file
    String name = FileUtil.normalizePath(new File("target/fileidempotent/report.txt").getAbsolutePath());
    fos.write(name.getBytes());
    fos.write(LS.getBytes());

    fos.close();

    super.setUp();

    // add a file to the repo
    repo = context.getRegistry().lookupByNameAndType("fileStore", IdempotentRepository.class);
}
项目:Camel    文件:FileConsumerIdempotentLoadStoreTest.java   
public void testIdempotentLoad() throws Exception {
    // send two files (report.txt exists already in idempotent repo)
    template.sendBodyAndHeader("file://target/fileidempotent/", "Hello World", Exchange.FILE_NAME, "report.txt");
    template.sendBodyAndHeader("file://target/fileidempotent/", "Bye World", Exchange.FILE_NAME, "report2.txt");

    // consume the file the first time
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedBodiesReceived("Bye World");

    assertMockEndpointsSatisfied();
    // wait for the exchange to be done, as it only append to idempotent repo after success
    oneExchangeDone.matchesMockWaitTime();

    String name = FileUtil.normalizePath(new File("target/fileidempotent/report.txt").getAbsolutePath());
    assertTrue("Should contain file: " + name, repo.contains(name));

    String name2 = FileUtil.normalizePath(new File("target/fileidempotent/report2.txt").getAbsolutePath());
    assertTrue("Should contain file: " + name2, repo.contains(name2));
}
项目:syndesis    文件:HttpComponent.java   
private static String buildUrl(String scheme, String hostname, Object port, String path, String uri) {
    // build together from component level and given uri that has additional context path to append
    String build = scheme + "://" + hostname;
    if (port != null) {
        build += ":" + port;
    }
    if (path != null) {
        build = FileUtil.stripTrailingSeparator(build);
        build += "/" + path;
    }

    String query = null;
    if (uri != null && uri.contains("?")) {
        query = StringHelper.after(uri, "?");
        uri = StringHelper.before(uri, "?");
        uri = StringHelper.after(uri, "://");
    }

    // remaining is to be appending
    if (uri != null) {
        build = FileUtil.stripTrailingSeparator(build);
        build += "/" + uri;
    }

    if (query != null) {
        build += "?" + query;
    }
    return build;
}
项目:connectors    文件:HttpComponent.java   
private static String buildUrl(String scheme, String hostname, Object port, String path, String uri) {
    // build together from component level and given uri that has additional context path to append
    String build = scheme + "://" + hostname;
    if (port != null) {
        build += ":" + port;
    }
    if (path != null) {
        build = FileUtil.stripTrailingSeparator(build);
        build += "/" + path;
    }

    String query = null;
    if (uri != null && uri.contains("?")) {
        query = StringHelper.after(uri, "?");
        uri = StringHelper.before(uri, "?");
        uri = StringHelper.after(uri, "://");
    }

    // remaining is to be appending
    if (uri != null) {
        build = FileUtil.stripTrailingSeparator(build);
        build += "/" + uri;
    }

    if (query != null) {
        build += "?" + query;
    }
    return build;
}
项目:Camel    文件:FileInputStreamCache.java   
void cleanUpTempFile() {
    // cleanup temporary file
    try {
        if (tempFile != null) {
            FileUtil.deleteFile(tempFile);
            tempFile = null;
        }
    } catch (Exception e) {
        LOG.warn("Error deleting temporary cache file: " + tempFile + ". This exception will be ignored.", e);
    }
}
项目:Camel    文件:FileIdempotentRepository.java   
/**
 * Appends the given message id to the file store
 *
 * @param messageId  the message id
 */
protected void appendToStore(final String messageId) {
    LOG.debug("Appending {} to idempotent filestore: {}", messageId, fileStore);
    FileOutputStream fos = null;
    try {
        // create store parent directory if missing
        File storeParentDirectory = fileStore.getParentFile();
        if (storeParentDirectory != null && !storeParentDirectory.exists()) {
            LOG.info("Parent directory of file store {} doesn't exist. Creating.", fileStore);
            if (fileStore.getParentFile().mkdirs()) {
                LOG.info("Parent directory of file store {} successfully created.", fileStore);
            } else {
                LOG.warn("Parent directory of file store {} cannot be created.", fileStore);
            }
        }
        // create store if missing
        if (!fileStore.exists()) {
            FileUtil.createNewFile(fileStore);
        }
        // append to store
        fos = new FileOutputStream(fileStore, true);
        fos.write(messageId.getBytes());
        fos.write(STORE_DELIMITER.getBytes());
    } catch (IOException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    } finally {
        IOHelper.close(fos, "Appending to file idempotent repository", LOG);
    }
}
项目:Camel    文件:FileIdempotentRepository.java   
/**
 * Loads the given file store into the 1st level cache
 */
protected void loadStore() throws IOException {
    // auto create starting directory if needed
    if (!fileStore.exists()) {
        LOG.debug("Creating filestore: {}", fileStore);
        File parent = fileStore.getParentFile();
        if (parent != null) {
            parent.mkdirs();
        }
        boolean created = FileUtil.createNewFile(fileStore);
        if (!created) {
            throw new IOException("Cannot create filestore: " + fileStore);
        }
    }

    LOG.trace("Loading to 1st level cache from idempotent filestore: {}", fileStore);

    cache.clear();
    Scanner scanner = null;
    try {
        scanner = new Scanner(fileStore);
        scanner.useDelimiter(STORE_DELIMITER);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            cache.put(line, line);
        }
    } catch (IOException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

    LOG.debug("Loaded {} to the 1st level cache from idempotent filestore: {}", cache.size(), fileStore);
}
项目:Camel    文件:DefaultStreamCachingStrategy.java   
@Override
protected void doStop() throws Exception {
    if (spoolThreshold > 0 & spoolDirectory != null  && isRemoveSpoolDirectoryWhenStopping()) {
        LOG.debug("Removing spool directory: {}", spoolDirectory);
        FileUtil.removeDir(spoolDirectory);
    }

    if (LOG.isDebugEnabled() && statistics.isStatisticsEnabled()) {
        LOG.debug("Stopping StreamCachingStrategy with statistics: {}", statistics.toString());
    }

    statistics.reset();
}
项目:Camel    文件:ExpressionBuilder.java   
public static Expression fileNameNoExtensionExpression() {
    return new ExpressionAdapter() {
        public Object evaluate(Exchange exchange) {
            String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
            return FileUtil.stripExt(name);
        }

        @Override
        public String toString() {
            return "file:name.noext";
        }
    };
}
项目:Camel    文件:ExpressionBuilder.java   
public static Expression fileNameNoExtensionSingleExpression() {
    return new ExpressionAdapter() {
        public Object evaluate(Exchange exchange) {
            String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
            return FileUtil.stripExt(name, true);
        }

        @Override
        public String toString() {
            return "file:name.noext.single";
        }
    };
}
项目:Camel    文件:ExpressionBuilder.java   
public static Expression fileOnlyNameNoExtensionExpression() {
    return new ExpressionAdapter() {
        public Object evaluate(Exchange exchange) {
            String name = fileOnlyNameExpression().evaluate(exchange, String.class);
            return FileUtil.stripExt(name);
        }

        @Override
        public String toString() {
            return "file:onlyname.noext";
        }
    };
}
项目:Camel    文件:ExpressionBuilder.java   
public static Expression fileOnlyNameNoExtensionSingleExpression() {
    return new ExpressionAdapter() {
        public Object evaluate(Exchange exchange) {
            String name = fileOnlyNameExpression().evaluate(exchange, String.class);
            return FileUtil.stripExt(name, true);
        }

        @Override
        public String toString() {
            return "file:onlyname.noext.single";
        }
    };
}
项目:Camel    文件:ExpressionBuilder.java   
public static Expression fileExtensionExpression() {
    return new ExpressionAdapter() {
        public Object evaluate(Exchange exchange) {
            String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
            return FileUtil.onlyExt(name);
        }

        @Override
        public String toString() {
            return "file:ext";
        }
    };
}
项目:Camel    文件:ExpressionBuilder.java   
public static Expression fileExtensionSingleExpression() {
    return new ExpressionAdapter() {
        public Object evaluate(Exchange exchange) {
            String name = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
            return FileUtil.onlyExt(name, true);
        }

        @Override
        public String toString() {
            return "file:ext.single";
        }
    };
}
项目:Camel    文件:DefaultLSResourceResolver.java   
private String getUri(String systemId) {
    if (resourcePath != null) {
        return FileUtil.onlyPath(resourceUri) + "/" + systemId;
    } else {
        return systemId;
    }
}
项目:Camel    文件:DefaultLSResourceResolver.java   
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
    // systemId should be mandatory
    if (systemId == null) {
        throw new IllegalArgumentException(String.format("Resource: %s refers an invalid resource without SystemId."
                + " Invalid resource has type: %s, namespaceURI: %s, publicId: %s, systemId: %s, baseURI: %s", resourceUri, type, namespaceURI, publicId, systemId, baseURI));
    }
    String resourceURI = null;
    // Build up the relative path for using relatedURI and baseURI
    if (baseURI == null) {
        relatedURI = FileUtil.compactPath(getUri(systemId), '/');
        resourceURI = relatedURI;
    } else {
        String relatedPath = relatedURIMap.get(baseURI);
        if (relatedPath == null) {
            relatedPath = FileUtil.onlyPath(relatedURI);
            if (relatedPath == null) {
                relatedPath = "";
            }
            relatedURI = FileUtil.compactPath(FileUtil.onlyPath(relatedURI) + "/" + systemId, '/');
            resourceURI = relatedURI;
            relatedURIMap.put(baseURI, relatedPath);
        } else {
            resourceURI = FileUtil.compactPath(relatedPath + "/" + systemId, '/');
            relatedURI = resourceURI;
        }
    }
    return new DefaultLSInput(publicId, systemId, baseURI, resourceURI);
}
项目:Camel    文件:MockEndpoint.java   
/**
 * Adds an expectation that a file exists with the given name
 * <p/>
 * Will wait at most 5 seconds while checking for the existence of the file.
 *
 * @param name name of file, will cater for / and \ on different OS platforms
 * @param content content of file to compare, can be <tt>null</tt> to not compare content
 */
public void expectedFileExists(final String name, final String content) {
    final File file = new File(FileUtil.normalizePath(name));

    expects(new Runnable() {
        public void run() {
            // wait at most 5 seconds for the file to exists
            final long timeout = System.currentTimeMillis() + 5000;

            boolean stop = false;
            while (!stop && !file.exists()) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // ignore
                }
                stop = System.currentTimeMillis() > timeout;
            }

            assertTrue("The file should exists: " + name, file.exists());

            if (content != null) {
                String body = getCamelContext().getTypeConverter().convertTo(String.class, file);
                assertEquals("Content of file: " + name, content, body);
            }
        }
    });
}
项目:Camel    文件:RestComponent.java   
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    RestEndpoint answer = new RestEndpoint(uri, this);
    setProperties(answer, parameters);
    answer.setParameters(parameters);

    if (!remaining.contains(":")) {
        throw new IllegalArgumentException("Invalid syntax. Must be rest:method:path[:uriTemplate] where uriTemplate is optional");
    }

    String method = ObjectHelper.before(remaining, ":");
    String s = ObjectHelper.after(remaining, ":");

    String path;
    String uriTemplate;
    if (s != null && s.contains(":")) {
        path = ObjectHelper.before(s, ":");
        uriTemplate = ObjectHelper.after(s, ":");
    } else {
        path = s;
        uriTemplate = null;
    }

    // remove trailing slashes
    path = FileUtil.stripTrailingSeparator(path);
    uriTemplate = FileUtil.stripTrailingSeparator(uriTemplate);

    answer.setMethod(method);
    answer.setPath(path);
    answer.setUriTemplate(uriTemplate);

    // if no explicit component name was given, then fallback and use default configured component name
    if (answer.getComponentName() == null && getCamelContext().getRestConfiguration() != null) {
        answer.setComponentName(getCamelContext().getRestConfiguration().getComponent());
    }

    return answer;
}
项目:Camel    文件:FileOperations.java   
/**
 * Creates a new file if the file doesn't exist.
 * If the endpoint's existing file logic is set to 'Override' then the target file will be truncated
 */
private void writeFileEmptyBody(File target) throws IOException {
    if (!target.exists()) {
        LOG.debug("Creating new empty file: {}", target);
        FileUtil.createNewFile(target);
    } else if (endpoint.getFileExist() == GenericFileExist.Override) {
        LOG.debug("Truncating existing file: {}", target);
        FileChannel out = new FileOutputStream(target).getChannel();
        try {
            out.truncate(0);
        } finally {
            IOHelper.close(out, target.getName(), LOG, endpoint.isForceWrites());
        }
    }
}
项目:Camel    文件:GenericFileProducer.java   
public void writeFile(Exchange exchange, String fileName) throws GenericFileOperationFailedException {
    // build directory if auto create is enabled
    if (endpoint.isAutoCreate()) {
        // we must normalize it (to avoid having both \ and / in the name which confuses java.io.File)
        String name = FileUtil.normalizePath(fileName);

        // use java.io.File to compute the file path
        File file = new File(name);
        String directory = file.getParent();
        boolean absolute = FileUtil.isAbsolute(file);
        if (directory != null) {
            if (!operations.buildDirectory(directory, absolute)) {
                log.debug("Cannot build directory [{}] (could be because of denied permissions)", directory);
            }
        }
    }

    // upload
    if (log.isTraceEnabled()) {
        log.trace("About to write [{}] to [{}] from exchange [{}]", new Object[]{fileName, getEndpoint(), exchange});
    }

    boolean success = operations.storeFile(fileName, exchange);
    if (!success) {
        throw new GenericFileOperationFailedException("Error writing file [" + fileName + "]");
    }
    log.debug("Wrote [{}] to [{}]", fileName, getEndpoint());
}
项目:Camel    文件:GenericFileProducer.java   
public String createTempFileName(Exchange exchange, String fileName) {
    String answer = fileName;

    String tempName;
    if (exchange.getIn().getHeader(Exchange.FILE_NAME) == null) {
        // its a generated filename then add it to header so we can evaluate the expression
        exchange.getIn().setHeader(Exchange.FILE_NAME, FileUtil.stripPath(fileName));
        tempName = endpoint.getTempFileName().evaluate(exchange, String.class);
        // and remove it again after evaluation
        exchange.getIn().removeHeader(Exchange.FILE_NAME);
    } else {
        tempName = endpoint.getTempFileName().evaluate(exchange, String.class);
    }

    // check for both windows and unix separators
    int pos = Math.max(answer.lastIndexOf("/"), answer.lastIndexOf("\\"));
    if (pos == -1) {
        // no path so use temp name as calculated
        answer = tempName;
    } else {
        // path should be prefixed before the temp name
        StringBuilder sb = new StringBuilder(answer.substring(0, pos + 1));
        sb.append(tempName);
        answer = sb.toString();
    }

    if (endpoint.getConfiguration().needToNormalize()) {
        // must normalize path to cater for Windows and other OS
        answer = normalizePath(answer);
    }

    return answer;
}
项目:Camel    文件:GenericFileConfiguration.java   
public void setDirectory(String directory) {
    this.directory = needToNormalize()
        // must normalize path to cater for Windows and other OS
        ? FileUtil.normalizePath(directory)
        // for the remote directory we don't need to do that
        : directory;

    // endpoint directory must not be null
    if (this.directory == null) {
        this.directory = "";
    }
}
项目:Camel    文件:GenericFileEndpoint.java   
/**
 * Creates the associated name of the done file based on the given file name.
 * <p/>
 * This method should only be invoked if a done filename property has been set on this endpoint.
 *
 * @param fileName the file name
 * @return name of the associated done file name
 */
protected String createDoneFileName(String fileName) {
    String pattern = getDoneFileName();
    ObjectHelper.notEmpty(pattern, "doneFileName", pattern);

    // we only support ${file:name} or ${file:name.noext} as dynamic placeholders for done files
    String path = FileUtil.onlyPath(fileName);
    String onlyName = FileUtil.stripPath(fileName);

    pattern = pattern.replaceFirst("\\$\\{file:name\\}", onlyName);
    pattern = pattern.replaceFirst("\\$simple\\{file:name\\}", onlyName);
    pattern = pattern.replaceFirst("\\$\\{file:name.noext\\}", FileUtil.stripExt(onlyName));
    pattern = pattern.replaceFirst("\\$simple\\{file:name.noext\\}", FileUtil.stripExt(onlyName));

    // must be able to resolve all placeholders supported
    if (StringHelper.hasStartToken(pattern, "simple")) {
        throw new ExpressionIllegalSyntaxException(fileName + ". Cannot resolve reminder: " + pattern);
    }

    String answer = pattern;
    if (ObjectHelper.isNotEmpty(path) && ObjectHelper.isNotEmpty(pattern)) {
        // done file must always be in same directory as the real file name
        answer = path + getFileSeparator() + pattern;
    }

    if (getConfiguration().needToNormalize()) {
        // must normalize path to cater for Windows and other OS
        answer = FileUtil.normalizePath(answer);
    }

    return answer;
}
项目:Camel    文件:MarkerFileExclusiveReadLockStrategy.java   
private static void deleteLockFiles(File dir, boolean recursive, String endpointPath,
                                    GenericFileFilter filter, GenericFileFilter antFilter,
                                    Pattern excludePattern, Pattern includePattern) {
    File[] files = dir.listFiles();
    if (files == null || files.length == 0) {
        return;
    }

    for (File file : files) {

        if (file.getName().startsWith(".")) {
            // files starting with dot should be skipped
            continue;
        }

        // filter unwanted files and directories to avoid traveling everything
        if (filter != null || antFilter != null || excludePattern != null || includePattern != null) {
            if (!acceptFile(file, endpointPath, filter, antFilter, excludePattern, includePattern)) {
                continue;
            }
        }

        if (file.getName().endsWith(FileComponent.DEFAULT_LOCK_FILE_POSTFIX)) {
            LOG.warn("Deleting orphaned lock file: " + file);
            FileUtil.deleteFile(file);
        } else if (recursive && file.isDirectory()) {
            deleteLockFiles(file, true, endpointPath, filter, antFilter, excludePattern, includePattern);
        }
    }
}
项目:Camel    文件:GenericFileProcessStrategySupport.java   
protected void deleteLocalWorkFile(Exchange exchange) {
    // delete local work file, if it was used (eg by ftp component)
    File local = exchange.getIn().getHeader(Exchange.FILE_LOCAL_WORK_PATH, File.class);
    if (local != null && local.exists()) {
        boolean deleted = FileUtil.deleteFile(local);
        log.trace("Local work file: {} was deleted: {}", local, deleted);
    }
}