Example usage for java.io File lastModified

List of usage examples for java.io File lastModified

Introduction

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

Prototype

public long lastModified() 

Source Link

Document

Returns the time that the file denoted by this abstract pathname was last modified.

Usage

From source file:de.clusteval.run.result.ClusteringRunResult.java

/**
 * @param repository/*from ww w. j ava  2 s  .  c  o m*/
 * @param run
 * @param dataConfig
 * @param programConfig
 * @param completeFile
 * @return The parameter optimization run result parsed from the given
 *         runresult folder.
 * @throws RegisterException
 */
public static ClusteringRunResult parseFromRunResultCompleteFile(Repository repository, ClusteringRun run,
        final DataConfig dataConfig, final ProgramConfig programConfig, final File completeFile,
        final boolean register) throws RegisterException {
    ClusteringRunResult result = null;
    if (completeFile.exists()) {
        result = new ClusteringRunResult(repository, completeFile.lastModified(), completeFile, dataConfig,
                programConfig, programConfig.getOutputFormat(),
                completeFile.getParentFile().getParentFile().getName(), run);

        if (register) {
            /*
             * Register after parsing
             */
            result.loadIntoMemory();
            try {
                result.register();
            } finally {
                result.unloadFromMemory();
            }
        }
    }
    return result;
}

From source file:jetbrains.exodus.util.CompressBackupUtil.java

/**
 * Adds the file to the tar archive represented by output stream. It's caller's responsibility to close output stream
 * properly./* w  w w .j a v  a  2 s  .  c  o m*/
 *
 * @param out           target archive.
 * @param pathInArchive relative path in archive. It will lead the name of the file in the archive.
 * @param source        file to be added.
 * @param fileSize      size of the file (which is known in most cases).
 * @throws IOException in case of any issues with underlying store.
 */
public static void archiveFile(@NotNull final ArchiveOutputStream out, @NotNull final String pathInArchive,
        @NotNull final File source, final long fileSize) throws IOException {
    if (!source.isFile()) {
        throw new IllegalArgumentException("Provided source is not a file: " + source.getAbsolutePath());
    }
    //noinspection ChainOfInstanceofChecks
    if (out instanceof TarArchiveOutputStream) {
        final TarArchiveEntry entry = new TarArchiveEntry(pathInArchive + source.getName());
        entry.setSize(fileSize);
        entry.setModTime(source.lastModified());
        out.putArchiveEntry(entry);
    } else if (out instanceof ZipArchiveOutputStream) {
        final ZipArchiveEntry entry = new ZipArchiveEntry(pathInArchive + source.getName());
        entry.setSize(fileSize);
        entry.setTime(source.lastModified());
        out.putArchiveEntry(entry);
    } else {
        throw new IOException("Unknown archive output stream");
    }
    try (InputStream input = new FileInputStream(source)) {
        IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);
    }
    out.closeArchiveEntry();
}

From source file:com.isomorphic.maven.util.ArchiveUtils.java

/**
 * Steps common to archiving both zip and jar files, which include reading files from disk and using
 * their contents to create {@link ZipEntry ZipEntries} and writing them to a ZipOutputStream.
 * // w w  w.j a v  a  2s . c o  m
 * @param root
 * @param source
 * @param target
 * @throws IOException
 */
private static void zip(File root, File source, ZipOutputStream target) throws IOException {
    String relativePath = root.toURI().relativize(source.toURI()).getPath().replace("\\", "/");

    BufferedInputStream in = null;
    try {
        if (source.isDirectory()) {

            if (!relativePath.endsWith("/")) {
                relativePath += "/";
            }
            ZipEntry entry = ZipEntryFactory.get(target, relativePath);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            target.closeEntry();

            for (File nestedFile : source.listFiles()) {
                zip(root, nestedFile, target);
            }
            return;
        }

        ZipEntry entry = ZipEntryFactory.get(target, relativePath);
        entry.setTime(source.lastModified());
        target.putNextEntry(entry);
        in = new BufferedInputStream(FileUtils.openInputStream(source));
        IOUtils.copy(in, target);
        target.closeEntry();

    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.cisco.step.jenkins.plugins.jenkow.WfUtil.java

static void deployAllToEngine() {
    File repoDir = JenkowWorkflowRepository.getRepositoryDir();
    if (!repoDir.exists()) {
        LOGGER.info("no workflow source repository");
        return;//  ww  w .  j  a  v  a  2  s.c o  m
    }

    LOGGER.info("deploying all workflow engine");

    RepositoryService repoSvc = JenkowEngine.getEngine().getRepositoryService();
    Map<String, Date> deplTimes = new HashMap<String, Date>();
    for (Deployment depl : repoSvc.createDeploymentQuery().list()) {
        //System.out.println("  depl: id="+depl.getId()+" name="+depl.getName()+" time="+depl.getDeploymentTime());
        deplTimes.put(depl.getId(), depl.getDeploymentTime());
    }
    Map<String, Date> pDefTimes = new HashMap<String, Date>();
    for (ProcessDefinition pDef : repoSvc.createProcessDefinitionQuery().latestVersion().list()) {
        //System.out.println(" pDef:"+pDef+" deplId="+pDef.getDeploymentId()+" key="+pDef.getKey());
        Date t = deplTimes.get(pDef.getDeploymentId());
        if (t != null)
            pDefTimes.put(pDef.getKey(), t);
    }

    for (Iterator it = FileUtils.iterateFiles(repoDir, new String[] { Consts.WORKFLOW_EXT },
            /*recursive=*/true); it.hasNext();) {
        File wff = (File) it.next();
        String wfn = wff.getName();
        int p = wfn.lastIndexOf('.');
        if (p > -1)
            wfn = wfn.substring(0, p);
        Date prevDeplTime = pDefTimes.get(wfn);
        //System.out.println("  f="+wff+" wfn="+wfn+" deplTime="+prevDeplTime+" wff.lastModified="+new Date(wff.lastModified()));
        if (prevDeplTime == null || prevDeplTime.before(new Date(wff.lastModified()))) {
            try {
                WfUtil.deployToEngine(wff);
            } catch (FileNotFoundException e) {
                LOGGER.log(Level.SEVERE, "file not found " + wff, e);
            }
        }
    }
}

From source file:net.rptools.lib.FileUtil.java

/**
 * Recursively deletes all files and/or directories that have been modified longer than <code>daysOld</code> days
 * ago. Note that this will recursively examine a directory, and only deletes those items that are too old.
 * //w  ww  .j  a  va 2s.  c  o  m
 * @param file
 *            the file or directory to recursively check and possibly delete
 * @param daysOld
 *            number of days old a file or directory can be before it is considered for deletion
 * @throws IOException
 *             if something goes wrong
 */
public static void delete(File file, int daysOld) throws IOException {
    Calendar olderThan = new GregorianCalendar();
    olderThan.add(Calendar.DATE, -daysOld);

    boolean shouldDelete = new Date(file.lastModified()).before(olderThan.getTime());

    if (file.isDirectory()) {
        // Wipe the contents first
        for (File currfile : file.listFiles()) {
            if (".".equals(currfile.getName()) || "..".equals(currfile.getName()))
                continue;
            delete(currfile, daysOld);
        }
    }
    if (shouldDelete)
        file.delete();
}

From source file:com.apporiented.hermesftp.utils.IOUtils.java

/**
 * Returns a line formated directory entry. The permissions are set as follows: The passed read
 * flag is relevant for owner, group and others. The passed write flag is only relevant for the
 * owner.//from   www. j av a2s. c  om
 * 
 * @param file The file to be formatted.
 * @param read True if readable.
 * @param write True if writable.
 * @return The formatted line.
 */
public static String formatUnixFtpFileInfo(File file, boolean read, boolean write) {
    long size;
    StringBuffer sb = new StringBuffer();
    String wFlag = write ? "w" : "-";
    String rFlag = read ? "r" : "-";
    String permflags;
    if (file.isDirectory()) {
        permflags = MessageFormat.format("d{0}{1}x{0}-x{0}-x", rFlag, wFlag);
        size = 0;
    } else {
        permflags = MessageFormat.format("-{0}{1}-{0}--{0}--", rFlag, wFlag);
        size = file.length();
    }
    Date date = new Date(file.lastModified());
    sb.append(permflags);
    sb.append(" 1 ftp ftp ");
    sb.append(StringUtils.leftPad("" + size, FILE_SIZE_LENGTH_UNIX));
    sb.append(" ");
    sb.append(DATE_FORMAT_UNIX.format(date));
    sb.append(" ");
    sb.append(file.getName());
    return sb.toString();
}

From source file:com.yoncabt.ebr.executor.jasper.JasperReport.java

private static File compile(File jrxmlFile) throws JRException {
    logManager.info(jrxmlFile + " compile");
    File jasperFile = new File(jrxmlFile.getAbsolutePath().replace(".jrxml", ".jasper"));
    jasperFile.getParentFile().mkdirs();
    if (jrxmlFile.lastModified() > jasperFile.lastModified()) {
        JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFile.getAbsolutePath());
        net.sf.jasperreports.engine.JasperReport jasperReport = JasperCompileManager
                .compileReport(jasperDesign);
        JRSaver.saveObject(jasperReport, jasperFile.getAbsolutePath());
        //toLog("Saving compiled report to: " + jasperFile.getAbsolutePath());
        //Compile sub reports
        JRElementsVisitor.visitReport(jasperReport, new JRVisitor() {

            @Override//from w w  w.  jav a  2 s .co m
            public void visitBreak(JRBreak breakElement) {
            }

            @Override
            public void visitChart(JRChart chart) {
            }

            @Override
            public void visitCrosstab(JRCrosstab crosstab) {
            }

            @Override
            public void visitElementGroup(JRElementGroup elementGroup) {
            }

            @Override
            public void visitEllipse(JREllipse ellipse) {
            }

            @Override
            public void visitFrame(JRFrame frame) {
            }

            @Override
            public void visitImage(JRImage image) {
            }

            @Override
            public void visitLine(JRLine line) {
            }

            @Override
            public void visitRectangle(JRRectangle rectangle) {
            }

            @Override
            public void visitStaticText(JRStaticText staticText) {
            }

            @Override
            public void visitSubreport(JRSubreport subreport) {
                String subReportName = subreport.getExpression().getText().replace("repo:", "");
                subReportName = StringUtils.strip(subReportName, "\"");
                //uzant jrxml olduuna emin olalm
                subReportName = FilenameUtils.removeExtension(subReportName) + ".jrxml";
                File subReportFile = new File(jrxmlFile.getParentFile(), subReportName);
                //Sometimes the same subreport can be used multiple times, but
                //there is no need to compile multiple times
                // burada tam path bulmak gerekebilir
                File compiledSubReportFile = compileIfRequired(subReportFile.getAbsoluteFile());
                File destSubReportFile = new File(
                        EBRConf.INSTANCE.getValue("report.subreport.path",
                                "/home/eastblue/apache-tomcat-8.0.28/webapps/ebr/WEB-INF/classes"),
                        compiledSubReportFile.getName());
                try {
                    // copy to classpoath
                    FileUtils.copyFile(compiledSubReportFile, destSubReportFile);
                } catch (IOException ex) {
                    throw new ReportException(ex);
                }
            }

            @Override
            public void visitTextField(JRTextField textField) {
            }

            @Override
            public void visitComponentElement(JRComponentElement componentElement) {
            }

            @Override
            public void visitGenericElement(JRGenericElement element) {
            }

        });
        JasperCompileManager.compileReportToFile(jrxmlFile.getAbsolutePath(), jasperFile.getAbsolutePath());
    }
    return jasperFile;
}

From source file:gribbit.server.siteresources.CacheExtension.java

/**
 * Adds a hash URI mapping for a file, and updates the mapping when the file is modified. Called by
 * HttpRequestHandler every time a file is served.
 *///from w  w w. ja v a2s  .co m
public static void updateHashURI(String origURI, File file) {
    // Can only hash absolute but local (i.e. domain-less) URIs that have not already been hashed
    if (origURI.startsWith("/") && !origURI.startsWith("//") && !origURI.startsWith("/_/")) {
        // Check to see if there is already a mapping to hash URI for this original URI
        HashInfo hashInfo = origURIToHashInfo.get(origURI);
        long lastModifiedEpochSeconds = file.lastModified() / 1000;
        if (hashInfo == null || hashInfo.lastModifiedEpochSeconds < lastModifiedEpochSeconds) {
            // There is no hash URI yet for origURI, or there is already a hash URI corresponding to origURI,
            // but the modification time has increased since the cached version, so need to re-hash.
            // Check if another thread has already enqueued the URI for hashing.
            Object alreadyInQueue = scheduledURIsToHash.put(origURI, new Object());
            if (alreadyInQueue == null) {
                // This URI is not currently queued for hashing by background workers, add it to the queue
                scheduleHasher(origURI, lastModifiedEpochSeconds, new Hasher() {
                    @Override
                    public String computeHashKey() {
                        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
                            // Compute MD5 hash of file contents, then base64-encode the results
                            return Base64Safe.base64Encode(DigestUtils.md5(inputStream));
                        } catch (IOException e) {
                            return null;
                        }
                    }
                });
            }
        }
    }
}

From source file:com.kylinolap.job.tools.DeployCoprocessorCLI.java

public static Path uploadCoprocessorJar(String localCoprocessorJar, FileSystem fileSystem,
        Set<String> oldJarPaths) throws IOException {
    Path uploadPath = null;//w w  w  .ja v  a2  s  .  c o m
    File localCoprocessorFile = new File(localCoprocessorJar);

    // check existing jars
    if (oldJarPaths == null) {
        oldJarPaths = new HashSet<String>();
    }
    Path coprocessorDir = getCoprocessorHDFSDir(fileSystem, KylinConfig.getInstanceFromEnv());
    for (FileStatus fileStatus : fileSystem.listStatus(coprocessorDir)) {
        if (fileStatus.getLen() == localCoprocessorJar.length()
                && fileStatus.getModificationTime() == localCoprocessorFile.lastModified()) {
            uploadPath = fileStatus.getPath();
            break;
        }
        String filename = fileStatus.getPath().toString();
        if (filename.endsWith(".jar")) {
            oldJarPaths.add(filename);
        }
    }

    // upload if not existing
    if (uploadPath == null) {
        // figure out a unique new jar file name
        Set<String> oldJarNames = new HashSet<String>();
        for (String path : oldJarPaths) {
            oldJarNames.add(new Path(path).getName());
        }
        String baseName = getBaseFileName(localCoprocessorJar);
        String newName = null;
        int i = 0;
        while (newName == null) {
            newName = baseName + "-" + (i++) + ".jar";
            if (oldJarNames.contains(newName))
                newName = null;
        }

        // upload
        uploadPath = new Path(coprocessorDir, newName);
        FileInputStream in = null;
        FSDataOutputStream out = null;
        try {
            in = new FileInputStream(localCoprocessorFile);
            out = fileSystem.create(uploadPath);
            IOUtils.copy(in, out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        fileSystem.setTimes(uploadPath, localCoprocessorFile.lastModified(), System.currentTimeMillis());
    }

    uploadPath = uploadPath.makeQualified(fileSystem.getUri(), null);
    return uploadPath;
}

From source file:cc.pp.analyzer.paoding.knife.PaodingMaker.java

@SuppressWarnings("resource")
private static long getFileLastModified(File file) throws IOException {
    String path = file.getPath();
    int jarIndex = path.indexOf(".jar!");
    if (jarIndex == -1) {
        return file.lastModified();
    } else {//from   w w  w.  jav  a2 s. c  o  m
        path = path.replaceAll("%20", " ").replaceAll("\\\\", "/");
        jarIndex = path.indexOf(".jar!");
        int protocalIndex = path.indexOf(":");
        String jarPath = path.substring(protocalIndex + ":".length(), jarIndex + ".jar".length());
        File jarPathFile = new File(jarPath);
        JarFile jarFile;
        try {
            jarFile = new JarFile(jarPathFile);
            String entryPath = path.substring(jarIndex + ".jar!/".length());
            JarEntry entry = jarFile.getJarEntry(entryPath);
            return entry.getTime();
        } catch (IOException e) {
            System.err.println("error in handler path=" + path);
            System.err.println("error in handler jarPath=" + jarPath);
            throw e;
        }
    }
}