Example usage for java.io FilenameFilter FilenameFilter

List of usage examples for java.io FilenameFilter FilenameFilter

Introduction

In this page you can find the example usage for java.io FilenameFilter FilenameFilter.

Prototype

FilenameFilter

Source Link

Usage

From source file:com.dngames.mobilewebcam.UploadFTPPhoto.java

@Override
public void run() {
    doInBackgroundBegin();//from  w  w  w  .  j a va2 s.  co  m

    if (mSettings.mRefreshDuration >= 10
            && (mSettings.mFTPBatch == 1 || ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) == 0)))
        publishProgress(mContext.getString(R.string.uploading, mSettings.mFTP + mSettings.mFTPDir));
    else if (mSettings.mFTPBatch > 1 || ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) != 0))
        publishProgress("batch ftp store");

    ftpupload: {
        try {
            BufferedInputStream buffIn = null;
            buffIn = new BufferedInputStream(new ByteArrayInputStream(mJpeg));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            String filename = mSettings.mDefaultname;
            if (mSettings.mFTPKeepPics == 0) {
                if (mSettings.mFTPNumbered) {
                    if (mSettings.mFTPTimestamp)
                        filename = MobileWebCam.gPictureCounter + sdf.format(mDate) + ".jpg";
                    else
                        filename = MobileWebCam.gPictureCounter + ".jpg";
                } else if (mSettings.mFTPTimestamp) {
                    filename = sdf.format(mDate) + ".jpg";
                }
            }

            boolean result = false;
            boolean deletetmpfile = false;
            boolean upload_now = true;
            if (mSettings.mStoreGPS) {
                try {
                    byte[] buffer = new byte[1024 * 8];
                    // Creates a file in the internal, app private storage
                    FileOutputStream fos;
                    fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
                    int r = 0;
                    while ((r = buffIn.read(buffer)) > -1)
                        fos.write(buffer, 0, r);
                    buffIn.close();
                    fos.close();
                    deletetmpfile = true;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    MobileWebCam.LogE("No file to write EXIF gps tag!");
                }

                File filePath = mContext.getFilesDir();
                File file = new File(filePath, filename);
                ExifWrapper.addCoordinates(file.getAbsolutePath(), WorkImage.gLatitude, WorkImage.gLongitude,
                        WorkImage.gAltitude);

                buffIn = new BufferedInputStream(mContext.openFileInput(filename));
            } else if (mSettings.mFTPBatch > 1 && ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) != 0)) {
                // store picture for later upload!
                byte[] buffer = new byte[1024 * 8];
                FileOutputStream fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
                int r = 0;
                while ((r = buffIn.read(buffer)) > -1)
                    fos.write(buffer, 0, r);
                buffIn.close();
                fos.close();
                upload_now = false;
            }

            if (upload_now) {
                FTPConnection.client = new FTPClient();
                FTPConnection.client.connect(InetAddress.getByName(mSettings.mFTP), mSettings.mFTPPort);

                FTPConnection.client.login(mSettings.mFTPLogin, mSettings.mFTPPassword);
                if (!FTPConnection.client.getReplyString().contains("230")) {
                    publishProgress("wrong ftp login response: " + FTPConnection.client.getReplyString()
                            + "\nAre your credentials correct?");
                    MobileWebCam.LogE("wrong ftp login response: " + FTPConnection.client.getReplyString()
                            + "\nAre your credentials correct?");
                    FTPConnection.client = null;
                    break ftpupload;
                }

                FTPConnection.client.changeWorkingDirectory(mSettings.mFTPDir);
                if (!FTPConnection.client.getReplyString().contains("250")) {
                    publishProgress("wrong ftp cwd response: " + FTPConnection.client.getReplyString()
                            + "\nIs the directory correct?");
                    MobileWebCam.LogE("wrong ftp cwd response: " + FTPConnection.client.getReplyString()
                            + "\nIs the directory correct?");
                    FTPConnection.client = null;
                    break ftpupload;
                }

                FTPConnection.client.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);

                if (mSettings.mFTPPassive)
                    FTPConnection.client.enterLocalPassiveMode();
                else
                    FTPConnection.client.enterLocalActiveMode();

                if (mSettings.mFTPKeepPics > 0) {
                    String replacename = filename.replace(".jpg", "");
                    // rename old pictures first
                    for (int i = mSettings.mFTPKeepPics - 1; i > 0; i--) {
                        try {
                            FTPConnection.client.rename(replacename + i + ".jpg",
                                    replacename + (i + 1) + ".jpg");
                        } catch (IOException e) {
                        }
                    }
                    try {
                        FTPConnection.client.rename(mSettings.mDefaultname, replacename + "1.jpg");
                    } catch (Exception e) {
                        if (e.getMessage() != null)
                            MobileWebCam.LogE(e.getMessage());
                        e.printStackTrace();
                    }
                }

                do {
                    // upload now
                    result = FTPConnection.client.storeFile(filename, buffIn);
                    buffIn.close();
                    buffIn = null;

                    if (deletetmpfile)
                        mContext.deleteFile(filename);

                    if (mSettings.mFTPBatch > 1 || mSettings.mReliableUpload) {
                        // find older pictures not sent yet
                        File file = mContext.getFilesDir();
                        String[] pics = file.list(new FilenameFilter() {
                            public boolean accept(File dir, String filename) {
                                if (filename.endsWith(".jpg"))
                                    return true;
                                return false;
                            }
                        });
                        if (pics.length > 0) {
                            filename = pics[0];
                            buffIn = new BufferedInputStream(mContext.openFileInput(filename));
                            deletetmpfile = true; // delete this file after upload!
                            // rerun
                            MobileWebCam.LogI("ftp batched upload: " + filename);
                        }
                    }
                } while (buffIn != null);

                InputStream logIS = null;
                if (mSettings.mLogUpload) {
                    String log = MobileWebCam.GetLog(mContext,
                            mContext.getSharedPreferences(MobileWebCam.SHARED_PREFS_NAME, 0), mSettings);
                    logIS = new ByteArrayInputStream(log.getBytes("UTF-8"));
                    if (logIS != null) {
                        result &= FTPConnection.client.storeFile("log.txt", logIS);
                    }
                }

                if (result) {
                    publishProgress("ok");
                    MobileWebCam.LogI("ok");
                } else {
                    publishProgress("ftp error: " + FTPConnection.client.getReplyString());
                    MobileWebCam.LogE("ftp error: " + FTPConnection.client.getReplyString());
                }

                if (!mSettings.mFTPKeepConnected) {
                    FTPConnection.client.logout();
                    FTPConnection.client.disconnect();
                    FTPConnection.client = null;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            publishProgress("Ftp socket exception!");
            MobileWebCam.LogE("Ftp socket exception!");
            FTPConnection.client = null;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            publishProgress("Unknown ftp host!");
            MobileWebCam.LogE("Unknown ftp host!");
            FTPConnection.client = null;
        } catch (IOException e) {
            e.printStackTrace();
            if (e.getMessage() != null) {
                publishProgress("IOException: ftp\n" + e.getMessage());
                MobileWebCam.LogE("IOException: ftp\n" + e.getMessage());
            } else {
                publishProgress("ftp IOException");
                MobileWebCam.LogE("ftp IOException");
            }
            FTPConnection.client = null;
        } catch (NullPointerException e) {
            MobileWebCam.LogE("NullPointerException:\n" + e.getMessage());
            FTPConnection.client = null;
        }
    }

    doInBackgroundEnd(mSettings.mFTPBatch == 1 || ((MobileWebCam.gPictureCounter % mSettings.mFTPBatch) == 0));
}

From source file:com.runwaysdk.dataaccess.io.Restore.java

private void importSQL() {
    FilenameFilter filter = new FilenameFilter() {
        @Override/* ww  w  .  j  a  va2s  .com*/
        public boolean accept(File dir, String name) {
            return name.endsWith(".sql");
        }
    };

    File sqlDir = new File(
            this.restoreDirectory.getAbsoluteFile() + File.separator + Backup.SQL + File.separator);

    this.log.debug("Importing SQL from directory [" + sqlDir + "]");

    File[] sqlFiles = sqlDir.listFiles(filter);

    if (sqlFiles != null) {
        for (File sqlFile : sqlFiles) {
            Database.importFromSQL(sqlFile.getAbsolutePath(), this.logPrintStream);
        }
    }
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Adds all the jar files in the given directory.
 *//*w w  w .j a v a2  s  .c  o m*/
public void addJarFiles(File dir) throws IOException {
    // list up *.jar files in the appDir
    File[] jarFiles = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    });

    if (jarFiles == null)
        return; // no such dir

    for (File jar : jarFiles)
        addPathFile(jar);
}

From source file:org.eclipse.virgo.ide.runtime.core.ServerUtils.java

public static void clearCacheDirectory() {
    File stateLocation = ServerCorePlugin.getDefault().getStateLocation().toFile();

    for (File folder : stateLocation.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith(CACHE_LOCATION_PREFIX) || name.startsWith(REPOSITORY_DOWNLOADS_PREFIX);
        }/*from   ww w  .  j  a  v  a 2  s.  com*/
    })) {
        PublishUtil.deleteDirectory(folder, new NullProgressMonitor());
    }

}

From source file:edu.unc.lib.deposit.normalize.Proquest2N3BagJob.java

private void unzipPackages() {
    File dataDirectory = this.getDataDirectory();
    File zipFiles[] = dataDirectory.listFiles(new FilenameFilter() {
        @Override//from  w w w .  ja v a 2s  .c o m
        public boolean accept(File directory, String fileName) {
            return fileName.endsWith(".zip");
        }
    });

    for (File packageFile : zipFiles) {
        try {
            String packageDir = packageFile.getName();
            packageDir = packageDir.substring(0, packageDir.length() - 4);
            ZipFileUtil.unzipToDir(packageFile, new File(dataDirectory, packageDir));
        } catch (IOException e) {
            throw new Error("Unable to unpack your deposit: " + getDepositPID().getUUID(), e);
        }
    }
}

From source file:ua.pp.msk.maven.MavenHttpClient.java

public void promote(Artifact artifact) throws ArtifactPromotingException {
    // Example of url
    // http://localhost:8081/nexus/service/local/artifact/maven/content
    List<File> artifactFiles = new LinkedList<File>();
    if (artifact.getFile() != null) {
        artifactFiles.add(artifact.getFile());
    }/*from ww  w. ja  va2s.c o  m*/

    final String groupId = artifact.getGroupId();
    String[] groupIdComponents = groupId.split("\\.");
    final String artifactId = artifact.getArtifactId();
    final String version = artifact.getVersion();
    if (artifactFiles.isEmpty()) {
        StringBuilder sb = new StringBuilder(artifactRepository.getBasedir());
        for (int i = 0; i < groupIdComponents.length; i++) {
            sb.append(File.separator);
            sb.append(groupIdComponents[i]);
        }
        sb.append(File.separator);
        sb.append(artifactId);
        sb.append(File.separator);
        sb.append(version);
        File directory = new File(sb.toString());
        if (directory.isDirectory()) {
            File[] artifacts = directory.listFiles(new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    if (name.endsWith("jar") || name.endsWith("war") || name.endsWith("ear")) {
                        if (name.contains(version)) {
                            if (name.startsWith(artifactId))
                                return true;
                        }
                    }
                    return false;
                }
            });
            artifactFiles.addAll(Arrays.asList(artifacts));
        } else {
            throw new ArtifactPromotingException(String.format(
                    "Artifact file is null of %s artifact. Cannot locate it in the %s directory, because it is not a directory"));
        }

    }
    if (repository == null || repository.length() == 0) {
        getLog().error("Repository cannot be null value");
        throw new ArtifactPromotingException("Repository cannot be null value");
    } else {
        addUrlParameter("r", repository);
    }
    addUrlParameter("hasPom", "false");

    addUrlParameter("g", groupId);
    addUrlParameter("a", artifactId);
    addUrlParameter("v", version);
    // Packaging should be
    for (File af : artifactFiles) {
        String fileName = af.getName();
        getLog().debug("Processing artifact file " + fileName);
        String[] splitName = fileName.toLowerCase().split("\\.");
        getLog().debug("Split name: " + Arrays.toString(splitName));
        String extension = splitName[splitName.length - 1].trim();
        if (!extension.equals("jar") && !extension.equals("war") && !extension.equals("ear")) {
            throw new ArtifactPromotingException(extension
                    + " is not supported. Currently only jar, war, ear file extensions are supported");
        }
        addUrlParameter("p", extension);
        addUrlParameter("e", extension);
        int ec = execute(af);
        if (ec == HttpStatus.SC_OK || ec == HttpStatus.SC_CREATED) {
            if (log != null) {
                getLog().info("Artifact has been promoted successfully");
            }
        } else if (log != null) {
            throw new ArtifactPromotingException("Artifact promotion failed");
        }
    }
}

From source file:eu.stratosphere.nephele.configuration.GlobalConfiguration.java

/**
 * Loads the configuration files from the specified directory.
 * //from  w w  w  .j a v  a  2s. co  m
 * @param configDir
 *        the directory which contains the configuration files
 */
public static void loadConfiguration(final String configDir) {

    if (configDir == null) {

        LOG.warn("Given configuration directory is null, cannot load configuration");
        return;
    }

    final File confDirFile = new File(configDir);
    if (!(confDirFile.exists() && confDirFile.isDirectory())) {
        LOG.warn("The given configuration directory name '" + configDir + "'(" + confDirFile.getAbsolutePath()
                + ") does not describe an existing directory.");
        return;
    }

    // get all XML files in the directory
    final File[] files = confDirFile.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return dir.equals(confDirFile) && name != null && name.endsWith(".xml");
        }

    });
    if (files == null || files.length == 0) {
        LOG.warn("Unable to get the contents of the config directory '" + configDir + "' ("
                + confDirFile.getAbsolutePath() + ").");
        return;
    }

    // load each xml file
    for (File f : files) {
        get().loadResource(f);
    }

    // Store the path to the configuration directory itself
    if (configuration != null) {
        configuration.confData.put(CONFIGDIRKEY, configDir);
    }
}

From source file:com.marklogic.contentpump.ContentPump.java

private static void submitJob(Job job) throws Exception {
    String cpHome = System.getProperty(CONTENTPUMP_HOME_PROPERTY_NAME);

    // find job jar
    File cpHomeDir = new File(cpHome);
    FilenameFilter jobJarFilter = new FilenameFilter() {
        @Override/*ww  w .j  a va2  s .co m*/
        public boolean accept(File dir, String name) {
            if (name.endsWith(".jar") && name.startsWith(CONTENTPUMP_JAR_PREFIX)) {
                return true;
            } else {
                return false;
            }
        }
    };
    File[] cpJars = cpHomeDir.listFiles(jobJarFilter);
    if (cpJars == null || cpJars.length == 0) {
        throw new RuntimeException("Content Pump jar file " + "is not found under " + cpHome);
    }
    if (cpJars.length > 1) {
        throw new RuntimeException("More than one Content Pump jar file " + "are found under " + cpHome);
    }
    // set job jar
    Configuration conf = job.getConfiguration();
    conf.set("mapreduce.job.jar", cpJars[0].toURI().toURL().toString());

    // find lib jars
    FilenameFilter filter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            if (name.endsWith(".jar") && !name.startsWith("hadoop")) {
                return true;
            } else {
                return false;
            }
        }

    };

    // set lib jars
    StringBuilder jars = new StringBuilder();
    for (File jar : cpHomeDir.listFiles(filter)) {
        if (jars.length() > 0) {
            jars.append(',');
        }
        jars.append(jar.toURI().toURL().toString());
    }
    conf.set("tmpjars", jars.toString());
    if (LOG.isTraceEnabled())
        LOG.trace("LIBJARS:" + jars.toString());
    job.waitForCompletion(true);
    AuditUtil.auditMlcpFinish(conf, job.getJobName(), job.getCounters());
}

From source file:com.g2inc.scap.library.domain.SCAPContentManager.java

private void parseDocs(File fileOrDir) throws IOException, FileNotFoundException, Exception {
    if (fileOrDir.exists() && fileOrDir.canRead()) {
        if (fileOrDir.isDirectory()) {
            FilenameFilter fnf = new FilenameFilter() {
                @Override//w  w w.j a  v a  2  s.c o  m
                public boolean accept(File dir, String name) {
                    if (name.endsWith(".xml") || name.endsWith(".XML")) {
                        return true;
                    }
                    return false;
                }
            };

            File[] dircontents = fileOrDir.listFiles(fnf);
            int len = dircontents.length;
            for (int x = 0; x < len; x++) {
                parseDocs(dircontents[x]);
            }
        } else if (fileOrDir.isFile()) {
            Document doc = null;

            try {
                if (LOG.isDebugEnabled()) {
                    LOG.trace("Beginning parse of " + fileOrDir.getAbsolutePath());
                }

                SCAPDocument sdoc = SCAPDocumentFactory.loadDocument(fileOrDir);
                content.put(fileOrDir.getAbsolutePath(), sdoc);

            } catch (JDOMException je) {
                throw new IllegalArgumentException("JDOMException occured trying to parse file " + fileOrDir,
                        je);
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw e;
            }

        }
    } else {
        throw new FileNotFoundException(fileOrDir.getAbsolutePath() + " doesn't exist or is not readable!");
    }
}

From source file:eu.stratosphere.yarn.Utils.java

public static void logFilesInCurrentDirectory(final Log logger) {
    new File(".").list(new FilenameFilter() {

        @Override/*from  w  ww .ja v  a2s .  com*/
        public boolean accept(File dir, String name) {
            logger.info(dir.getAbsolutePath() + "/" + name);
            return true;
        }
    });
}