001/**
002 * Copyright (C) 2006-2020 Talend Inc. - www.talend.com
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.talend.sdk.component.server.service;
017
018import java.io.File;
019import java.io.IOException;
020import java.nio.file.Files;
021import java.nio.file.Path;
022import java.util.stream.Stream;
023
024import javax.enterprise.context.ApplicationScoped;
025
026import org.talend.sdk.component.path.PathFactory;
027
028@ApplicationScoped
029public class GlobService {
030
031    public Stream<Path> toFiles(final String path) {
032        if (path.endsWith("*") || path.endsWith("*.properties")) {
033            final String prefix = path.substring(0, path.lastIndexOf('*'));
034            final int lastSlash = prefix.replace(File.separatorChar, '/').lastIndexOf('/');
035            final String folder;
036            final String filePrefix;
037            if (lastSlash > 0) {
038                folder = prefix.substring(0, lastSlash);
039                filePrefix = prefix.substring(lastSlash + 1);
040            } else {
041                folder = prefix;
042                filePrefix = "";
043            }
044            return Stream.of(PathFactory.get(folder)).filter(Files::exists).flatMap(it -> {
045                try {
046                    return Files.list(it).filter(file -> {
047                        final String name = file.getFileName().toString();
048                        return name.startsWith(filePrefix) && name.endsWith(".properties");
049                    });
050                } catch (final IOException e) {
051                    throw new IllegalStateException(e);
052                }
053            }).filter(Files::exists);
054        }
055        return Stream.of(PathFactory.get(path));
056    }
057}