Example usage for org.apache.commons.io FilenameUtils isExtension

List of usage examples for org.apache.commons.io FilenameUtils isExtension

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils isExtension.

Prototype

public static boolean isExtension(String filename, Collection<String> extensions) 

Source Link

Document

Checks whether the extension of the filename is one of those specified.

Usage

From source file:org.orbisgis.framework.BundleTools.java

/**
 * Register in the host bundle the provided list of bundle reference
 * @param hostBundle Host BundleContext/*from w w  w . j ava2 s. co m*/
 * @param nonDefaultBundleDeploying Bundle Reference array to deploy bundles in a non default way (install&start)
 */
public void installBundles(BundleContext hostBundle, BundleReference[] nonDefaultBundleDeploying) {
    //Create a Map of nonDefaultBundleDeploying by their artifactId
    Map<String, BundleReference> customDeployBundles = new HashMap<String, BundleReference>(
            nonDefaultBundleDeploying.length);
    for (BundleReference ref : nonDefaultBundleDeploying) {
        customDeployBundles.put(ref.getArtifactId(), ref);
    }

    // List bundles in the /bundle subdirectory
    File bundleFolder = new File(BUNDLE_DIRECTORY);
    if (!bundleFolder.exists()) {
        return;
    }
    File[] files = bundleFolder.listFiles();
    List<File> jarList = new ArrayList<File>();
    if (files != null) {
        for (File file : files) {
            if (FilenameUtils.isExtension(file.getName(), "jar")) {
                jarList.add(file);
            }
        }
    }
    if (!jarList.isEmpty()) {
        Map<String, Bundle> installedBundleMap = new HashMap<String, Bundle>();
        Set<String> fragmentHosts = new HashSet<>();

        // Keep a reference to bundles in the framework cache
        for (Bundle bundle : hostBundle.getBundles()) {
            String key = bundle.getSymbolicName();
            installedBundleMap.put(key, bundle);
            String fragmentHost = getFragmentHost(bundle);
            if (fragmentHost != null) {
                fragmentHosts.add(fragmentHost);
            }
        }

        //
        final List<Bundle> installedBundleList = new LinkedList<Bundle>();
        for (File jarFile : jarList) {
            // Extract version and symbolic name of the bundle
            String key = "";
            BundleReference jarRef;
            try {
                List<PackageDeclaration> packageDeclarations = new ArrayList<PackageDeclaration>();
                jarRef = parseJarManifest(jarFile, packageDeclarations);
                key = jarRef.getArtifactId();
            } catch (IOException ex) {
                LOGGER.log(Logger.LOG_ERROR, ex.getLocalizedMessage(), ex);
                // Do not install this jar
                continue;
            }
            // Retrieve from the framework cache the bundle at this location
            Bundle installedBundle = installedBundleMap.remove(key);

            // Read Jar manifest without installing it
            BundleReference reference = new BundleReference(""); // Default deploy
            try (JarFile jar = new JarFile(jarFile)) {
                Manifest manifest = jar.getManifest();
                if (manifest != null && manifest.getMainAttributes() != null) {
                    String artifact = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
                    BundleReference customRef = customDeployBundles.get(artifact);
                    if (customRef != null) {
                        reference = customRef;
                    }
                }

            } catch (Exception ex) {
                LOGGER.log(Logger.LOG_ERROR, I18N.tr("Could not read bundle manifest"), ex);
            }

            try {
                if (installedBundle != null) {
                    if (getFragmentHost(installedBundle) != null) {
                        // Fragment cannot be reinstalled
                        continue;
                    } else {
                        String installedBundleLocation = installedBundle.getLocation();
                        int verDiff = -1;
                        if (installedBundle.getVersion() != null && jarRef.getVersion() != null) {
                            verDiff = installedBundle.getVersion().compareTo(jarRef.getVersion());
                        }
                        if (verDiff == 0) {
                            // If the same version or SNAPSHOT that is not used by fragments
                            if (!fragmentHosts.contains(installedBundle.getSymbolicName())
                                    && (!installedBundleLocation.equals(jarFile.toURI().toString())
                                            || (installedBundle.getVersion() != null && "SNAPSHOT"
                                                    .equals(installedBundle.getVersion().getQualifier())))) {
                                //if the location is not the same reinstall it
                                LOGGER.log(Logger.LOG_INFO,
                                        "Uninstall bundle " + installedBundle.getSymbolicName());
                                installedBundle.uninstall();
                                installedBundle = null;
                            }
                        } else if (verDiff < 0) {
                            // Installed version is older than the bundle version
                            LOGGER.log(Logger.LOG_INFO, "Uninstall bundle " + installedBundle.getLocation());
                            installedBundle.uninstall();
                            installedBundle = null;
                        } else {
                            // Installed version is more recent than the bundle version
                            // Do not install this jar
                            continue;
                        }
                    }
                }
                // If the bundle is not in the framework cache install it
                if ((installedBundle == null) && reference.isAutoInstall()) {
                    installedBundle = hostBundle.installBundle(jarFile.toURI().toString());
                    LOGGER.log(Logger.LOG_INFO, "Install bundle " + installedBundle.getSymbolicName());
                    if (!isFragment(installedBundle) && reference.isAutoStart()) {
                        installedBundleList.add(installedBundle);
                    }
                }
            } catch (BundleException ex) {
                LOGGER.log(Logger.LOG_ERROR, "Error while installing bundle in bundle directory", ex);
            }
        }
        // Start new bundles
        for (Bundle bundle : installedBundleList) {
            try {
                bundle.start();
            } catch (BundleException ex) {
                LOGGER.log(Logger.LOG_ERROR, "Error while starting bundle in bundle directory", ex);
            }
        }
    }
}

From source file:org.pentaho.platform.repository.RepositoryFilenameUtils.java

/**
 * Checks whether the extension of the filename is that specified.
 * <p/>/*from w  w  w.jav  a  2  s.  co m*/
 * This method obtains the extension as the textual part of the filename after the last dot. There must be no
 * directory separator after the dot. The extension check is case-sensitive on all platforms.
 * 
 * @param filename
 *          the filename to query, null returns false
 * @param extension
 *          the extension to check for, null or empty checks for no extension
 * @return true if the filename has the specified extension
 */
public static boolean isExtension(final String filename, final String extension) {
    return FilenameUtils.isExtension(filename, extension);
}

From source file:org.pentaho.platform.repository.RepositoryFilenameUtils.java

/**
 * Checks whether the extension of the filename is one of those specified.
 * <p/>//w  w  w . j  a v  a 2s.c o  m
 * This method obtains the extension as the textual part of the filename after the last dot. There must be no
 * directory separator after the dot. The extension check is case-sensitive on all platforms.
 * 
 * @param filename
 *          the filename to query, null returns false
 * @param extensions
 *          the extensions to check for, null checks for no extension
 * @return true if the filename is one of the extensions
 */
public static boolean isExtension(final String filename, final String[] extensions) {
    return FilenameUtils.isExtension(filename, extensions);
}

From source file:org.pentaho.platform.repository.RepositoryFilenameUtils.java

/**
 * Checks whether the extension of the filename is one of those specified.
 * <p/>/*from  ww  w . j a va 2s . c  o m*/
 * This method obtains the extension as the textual part of the filename after the last dot. There must be no
 * directory separator after the dot. The extension check is case-sensitive on all platforms.
 * 
 * @param filename
 *          the filename to query, null returns false
 * @param extensions
 *          the extensions to check for, null checks for no extension
 * @return true if the filename is one of the extensions
 */
public static boolean isExtension(final String filename, final Collection extensions) {
    return FilenameUtils.isExtension(filename, extensions);
}

From source file:org.robovm.eclipse.internal.ib.AbstractNewXcodeFileWizard.java

@Override
public boolean performFinish() {
    IPath containerPath = page.getContainerFullPath();
    if (containerPath == null) {
        return false;
    }// w ww.  jav  a2 s .co m

    IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(containerPath);
    IProject project = resource.getProject();
    File path = resource.getLocation().toFile();
    String name = page.getFileName();
    if (FilenameUtils.isExtension(name, getExtension())) {
        name = FilenameUtils.removeExtension(name);
    }

    createFile(project, name, path);
    try {
        resource.refreshLocal(IResource.DEPTH_ONE, null);
    } catch (CoreException e) {
        RoboVMPlugin.log(e);
    }

    return true;
}

From source file:org.robovm.eclipse.internal.ib.AbstractNewXcodeFileWizard.java

@Override
public boolean canFinish() {
    IPath containerPath = page.getContainerFullPath();
    if (containerPath == null) {
        return false;
    }//from  ww  w .j  a v  a2 s .  c  om
    if (page.getFileName() == null) {
        return false;
    }

    IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(containerPath);
    IProject project = resource.getProject();
    boolean valid = false;
    try {
        if (RoboVMPlugin.isRoboVMIOSProject(project)) {
            Collection<File> resourcePaths = getProjectResourcePaths(project);
            for (File f = resource.getLocation().toFile().getAbsoluteFile(); f != null; f = f.getParentFile()) {
                if (resourcePaths.contains(f)) {
                    valid = true;
                    break;
                }
            }
        }
    } catch (CoreException e) {
        RoboVMPlugin.log(e);
    }

    if (!valid) {
        page.setErrorMessage("Selected folder must be a resource folder in a RoboVM iOS project");
        return false;
    }

    File f = new File(resource.getLocation().toFile().getAbsoluteFile(), page.getFileName());
    if (!FilenameUtils.isExtension(f.getName(), getExtension())) {
        f = new File(f.getParentFile(), f.getName() + "." + getExtension());
    }
    if (f.exists()) {
        page.setErrorMessage("A file named '" + FilenameUtils.removeExtension(page.getFileName())
                + "' already exists in the select folder");
        return false;
    }

    return true;
}

From source file:org.sejda.core.support.io.IOUtilsTest.java

@Test
public void testCreatePdfBuffer() throws TaskIOException {
    File tmp = IOUtils.createTemporaryPdfBuffer();
    tmp.deleteOnExit();/*from  ww  w.  j  a v  a  2 s  .c om*/
    assertTrue(tmp.exists());
    assertTrue(tmp.isFile());
    assertTrue(
            FilenameUtils.isExtension(tmp.getName(), Collections.singleton(SejdaFileExtensions.PDF_EXTENSION)));
}

From source file:org.silverpeas.core.mail.extractor.Extractor.java

public static MailExtractor getExtractor(File file) throws ExtractorException {
    if (!file.exists() || file.isDirectory()) {
        throw new ExtractorException("file not found");
    }/*w w  w  .  ja v  a  2 s  . c  o m*/
    if (FilenameUtils.isExtension(file.getName(), "eml")) {
        return new EMLExtractor(file);
    }
    if (FilenameUtils.isExtension(file.getName(), "msg")) {
        return new MSGExtractor(file);
    }
    throw new ExtractorException("Extension not supported");
}

From source file:org.silverpeas.util.mail.Extractor.java

public static MailExtractor getExtractor(File file) throws ExtractorException {
    if (!file.exists() || file.isDirectory()) {
        throw new ExtractorException("Extractor.getExtractor", SilverpeasException.ERROR, "file not found");
    }//from  w  w  w.  ja va 2 s.  co m
    if (FilenameUtils.isExtension(file.getName(), "eml")) {
        return new EMLExtractor(file);
    }
    if (FilenameUtils.isExtension(file.getName(), "msg")) {
        return new MSGExtractor(file);
    }
    throw new ExtractorException("Extractor.getExtractor", SilverpeasException.ERROR,
            "Extension not supported");
}

From source file:org.wso2.carbon.event.simulator.core.internal.generator.csv.util.FileUploader.java

/**
 * Method to upload a CSV file.//  ww w.j a  v a2 s .c om
 *
 * @param fileInfo    fileInfo of file being uploaded
 * @param inputStream inputStream of file content
 * @param destination destination where the file should be copied to i.e. destination
 * @throws FileAlreadyExistsException if the file exists in 'destination' directory
 * @throws FileOperationsException    if an IOException occurs while copying uploaded stream to
 *                                    'destination' directory
 * @throws InvalidFileException       if the file being uploaded is not a csv file
 */
public void uploadFile(FileInfo fileInfo, InputStream inputStream, String destination)
        throws FileAlreadyExistsException, FileOperationsException, InvalidFileException {
    String fileName = fileInfo.getFileName();
    // Validate file extension
    if (FilenameUtils.isExtension(fileName, EventSimulatorConstants.CSV_FILE_EXTENSION)) {
        if (!fileStore.checkExists(fileName)) {
            //use ValidatedInputStream to check whether the file size is less than the maximum size allowed ie 8MB
            try (ValidatedInputStream validatedStream = new ValidatedInputStream(inputStream,
                    EventSimulatorDataHolder.getInstance().getMaximumFileSize())) {
                Files.copy(validatedStream, Paths.get(destination, "temp.temp"));
                FileUtils.moveFile(FileUtils.getFile(Paths.get(destination, "temp.temp").toString()),
                        FileUtils.getFile(Paths.get(destination, fileName).toString()));
                if (log.isDebugEnabled()) {
                    log.debug("Successfully uploaded CSV file '" + fileName + "'.");
                }
            } catch (java.nio.file.FileAlreadyExistsException | FileExistsException e) {
                /*
                 * since the deployer takes about 15 seconds to update the fileStore, 2 consecutive requests
                 * upload the same csv file will result in java.nio.file.FileAlreadyExistsException
                 */
                log.error("File '" + fileName + "' already exists.");
                throw new FileAlreadyExistsException("File '" + fileName + "' already exists.");
            } catch (FileLimitExceededException e) {
                //                    since the validated input streams checks for the file size while streaming, part of the file may
                //                    be copied prior to raising an error for file exceeding the maximum size limit.
                deleteFile("temp.temp", destination);
                log.error("File '" + fileName + "' exceeds the maximum file size of "
                        + (EventSimulatorDataHolder.getInstance().getMaximumFileSize() / 1024 / 1024) + " MB.",
                        e);
                throw new FileLimitExceededException("File '" + fileName + "' exceeds the maximum file size of "
                        + (EventSimulatorDataHolder.getInstance().getMaximumFileSize() / 1024 / 1024) + " MB.",
                        e);
            } catch (IOException e) {
                log.error("Error occurred while copying the file '" + fileName + "'. ", e);
                throw new FileOperationsException("Error occurred while copying the file '" + fileName + "'. ",
                        e);
            }
        } else {
            log.error("File '" + fileName + "' already exists.");
            throw new FileAlreadyExistsException("File '" + fileName + "' already exists.");
        }
    } else {
        log.error("File '" + fileName + "' is not a CSV file.");
        throw new InvalidFileException("File '" + fileName + "' is not a CSV file.");
    }
}