Example usage for java.io File setLastModified

List of usage examples for java.io File setLastModified

Introduction

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

Prototype

public boolean setLastModified(long time) 

Source Link

Document

Sets the last-modified time of the file or directory named by this abstract pathname.

Usage

From source file:com.dbi.jmmerge.MapController.java

private void mergeFiles(File newFile, File oldFile) {
    LOG.debug("Trying to merge " + newFile);
    if (newFile.getName().contains(".png")) {
        LOG.debug(newFile + " is a PNG!");
        try {/*from   w w w  .ja  v a  2s .c o  m*/
            long updateTime = newFile.lastModified() > oldFile.lastModified() ? newFile.lastModified()
                    : oldFile.lastModified();
            ImageIO.write(PNGMerge.mergeImages(newFile, oldFile), "png", oldFile);
            oldFile.setLastModified(updateTime);
        } catch (IOException ex) {
            LOG.debug("Couldn't merge " + newFile.getName() + " and " + oldFile.getName());
            ex.printStackTrace();
        }
    } else if (newFile.getName().contains(".json")) {
        LOG.debug(newFile + " is a waypoint.");
    }
}

From source file:com.streamsets.pipeline.stage.origin.remote.TestRemoteDownloadSource.java

@Test
public void testOverrunErrorArchiveFileRecovery() throws Exception {
    path = "remote-download-source/parseRecoveryFromFailure";
    File dir = new File(currentThread().getContextClassLoader()
            .getResource("remote-download-source/parseRecoveryFromFailure").getPath());
    File[] files = dir.listFiles();
    for (File f : files) {
        System.out.println(f.getName());
        if (f.getName().equals("polarbear.txt")) {
            f.setLastModified(18000000L);
        } else if (f.getName().equals("longobject.txt")) {
            f.setLastModified(17500000L);
        } else if (f.getName().equals("sloth.txt")) {
            f.setLastModified(17000000L);
        }/*from w  ww.j  a va2 s.c o  m*/
    }
    setupSSHD(path, false);
    File archiveDir = testFolder.newFolder();
    FilenameFilter filter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.equals("longobject.txt");
        }
    };
    RemoteDownloadSource origin = new RemoteDownloadSource(
            getBean("sftp://localhost:" + String.valueOf(port) + "/", true, "testuser", "pass", null, null,
                    null, true, DataFormat.JSON, archiveDir.toString()));
    SourceRunner runner = new SourceRunner.Builder(RemoteDownloadSource.class, origin).addOutputLane("lane")
            .setOnRecordError(OnRecordError.TO_ERROR).build();
    runner.runInit();
    List<Record> expected = getExpectedRecords();
    Record record = RecordCreator.create();
    record.set(Field.create(new HashMap<String, Field>()));
    record.set("/name", Field.create("polarbear"));
    record.set("/age", Field.create("6"));
    record.set("/characterisitics", Field.create(Arrays.asList(Field.create("cool"), Field.create("cute"),
            Field.create("huge"), Field.create("round"), Field.create("playful"))));
    expected.add(record);
    Assert.assertEquals(0, archiveDir.listFiles().length);
    String offset = "-1";
    for (int i = 0; i < 3; i++) {
        StageRunner.Output op = runner.runProduce(offset, 1000);
        offset = op.getNewOffset();
        List<Record> actual = op.getRecords().get("lane");
        Assert.assertEquals(1, actual.size());
        if (i >= 1) { //longobject
            Assert.assertEquals(1, archiveDir.listFiles().length);
            continue;
        } else {
            Assert.assertEquals(0, archiveDir.listFiles().length);
        }
        Assert.assertEquals(expected.get(i).get(), actual.get(0).get());
    }
    Assert.assertEquals(1, archiveDir.listFiles().length);
    File expectedFile = new File(currentThread().getContextClassLoader()
            .getResource("remote-download-source/parseRecoveryFromFailure").getPath()).listFiles(filter)[0];

    File actualFile = archiveDir.listFiles(filter)[0];
    Assert.assertEquals(expectedFile.getName(), actualFile.getName());
    Assert.assertTrue(FileUtils.contentEquals(expectedFile, actualFile));
}

From source file:gov.nih.nci.caintegrator.application.gpvisualizer.CaIntegratorRunVisualizer.java

protected String downloadSupportFiles() throws IOException {

    String name = (String) params.get(MODULE_NAME);
    String lsid = (String) params.get(RunVisualizerConstants.LSID);
    //System.out.println("Name = " + name);
    // don't even bother using the local files since downloading is so fast
    // and the caching is conservative
    Date startDLTime = new Date();
    File fLibdir = new File(getTempDir(), name + ".libdir");
    fLibdir.mkdirs();/*from  www  .j a v a2s  . c o  m*/

    //System.out.println("temp file path for support files = " + fLibdir.getAbsolutePath());

    File[] currentFiles = fLibdir.listFiles();

    int supf;

    // delete any currently downloaded files that are extraneous or
    // out-of-date (older or newer)
    for (int curf = 0; curf < currentFiles.length; curf++) {
        boolean found = false;
        // if it isn't a support file, delete it
        for (supf = 0; supf < supportFileNames.length; supf++) {
            if (currentFiles[curf].getName().equals(supportFileNames[supf])) {
                found = true;
                break;
            }
        }
        if (!found) {
            // delete extraneous file
            if (DEBUG) {
                System.out.println("deleting extraneous file " + currentFiles[curf].getCanonicalPath());
            }
            currentFiles[curf].delete();
        } else {
            if (currentFiles[curf].lastModified() != supportFileDates[supf]) {
                // delete out-of-date file (either more recent or older)
                if (DEBUG) {
                    System.out.println("deleting out-of-date file " + currentFiles[curf].getCanonicalPath());
                }
                currentFiles[curf].delete();
            }
        }
    }

    // user CaIntegrator's genepattern server URL ---------- CaIntegrator
    String serverLibdir = (String) params.get(SUPPORT_FILE_URL);
    serverLibdir = replace(serverLibdir, "<lsid>", encode(lsid));

    // figure out which support files are not in the currently downloaded
    // set and download them
    for (supf = 0; supf < supportFileNames.length; supf++) {
        if (!new File(fLibdir, supportFileNames[supf]).exists()) {
            // need to download it
            if (DEBUG) {
                System.out.print("downloading missing file " + supportFileNames[supf] + "...");
            }
            Date startTime = new Date();
            String urlString = replace(serverLibdir, "<supportFileName>", encode(supportFileNames[supf]));
            String ticketString = (String) params.get(TICKET_STRING);
            urlString = urlString + "&" + ticketString.substring(1);
            //System.out.println("Support file URL = " + urlString);
            URL urlFile = new URL(urlString);
            //URL urlFile = new URL(serverLibdir + "/gp/getFile.jsp?task=" + encode(lsid) + "&file="
            //       + encode(supportFileNames[supf]));

            //URL urlFile = new URL(server + "/gp/getFile.jsp?task=" + encode(lsid) + "&file="
            //        + encode(supportFileNames[supf]));
            File file = downloadFile(urlFile, fLibdir, supportFileNames[supf]);
            file.setLastModified(supportFileDates[supf]);

            if (DEBUG) {
                long downloadTime = new Date().getTime() - startTime.getTime();
                System.out.println(
                        " received " + file.length() + " bytes in " + downloadTime / 1000.0 + " seconds");
            }
        }
    }

    if (DEBUG) {
        System.out.println(
                "Total download time " + (new Date().getTime() - startDLTime.getTime()) / 1000.0 + " seconds");
    }
    return fLibdir.getCanonicalPath();
}

From source file:org.abstracthorizon.proximity.storage.local.ReadOnlyFileSystemStorage.java

/**
 * Store item properties./*from w w w .  ja va 2  s  .com*/
 * 
 * @param iProps the i props
 * 
 * @throws StorageException the storage exception
 */
protected void storeItemProperties(ItemProperties iProps) throws StorageException {
    if (!iProps.isFile()) {
        throw new IllegalArgumentException("Only files can be stored!");
    }
    logger.debug("Storing metadata in [{}] in storage directory {}", iProps.getPath(), getMetadataBaseDir());
    try {

        File target = new File(getMetadataBaseDir(), iProps.getPath());
        target.getParentFile().mkdirs();
        Properties metadata = new Properties();
        metadata.putAll(iProps.getAllMetadata());
        FileOutputStream os = new FileOutputStream(target);
        try {
            metadata.store(os, "Written by " + this.getClass());
            os.flush();
        } finally {
            os.close();
        }
        target.setLastModified(iProps.getLastModified().getTime());

    } catch (IOException ex) {
        throw new StorageException("IOException in FS storage " + getMetadataBaseDir(), ex);
    }
}

From source file:com.blackducksoftware.integration.hub.cli.CLIDownloadService.java

private void unzip(File dir, final File zipFile, final IntLogger logger) throws IOException {
    // without getAbsoluteFile, getParentFile below seems to fail
    dir = dir.getAbsoluteFile();/*  w ww  .  j a  v a  2  s .c  o  m*/
    final ZipFile zip = new ZipFile(zipFile);
    final Enumeration<ZipEntry> entries = zip.getEntries();
    try {
        while (entries.hasMoreElements()) {
            final ZipEntry e = entries.nextElement();
            final File f = new File(dir, e.getName());
            if (e.isDirectory()) {
                f.mkdirs();
            } else {
                final File p = f.getParentFile();
                if (p != null) {
                    p.mkdirs();
                }
                final InputStream input = zip.getInputStream(e);
                try {
                    copyInputStreamToFile(input, f);
                } finally {
                    input.close();
                }
                f.setLastModified(e.getTime());
            }
        }
    } finally {
        zip.close();
    }
}

From source file:com.krawler.esp.servlets.importICSServlet.java

public static Calendar setUpICal(String url, String ID, int interval) throws ServiceException {
    Calendar calByUrl = null;//from   w w  w  .j  a  v a 2 s  .c om
    try {
        setSystemProperties();
        boolean fileCreated = false;

        File file = new File(
                StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + ID + ".ics");

        if (file.exists()) { // if this calendar file exists in the store?
            java.util.Calendar cal = java.util.Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(java.util.Calendar.MINUTE, interval);
            if (new Date(file.lastModified()).before(cal.getTime())
                    || new Date(file.lastModified()).equals(cal.getTime())) { // if its older than given time?
                fileCreated = getICalFileFromURL(file, url, true);
                if (fileCreated) {
                    interval = interval * -1;
                    Tree.updateInternetCalendar(ID, interval, true);
                    file.setLastModified(new Date().getTime());
                }
            } else {
                fileCreated = true;
            }
        } else { // file does not exists. it has to be created.
            fileCreated = getICalFileFromURL(file, url, false);
            if (fileCreated)
                file.setLastModified(new Date().getTime());
        }
        if (fileCreated) {
            FileInputStream fip = new FileInputStream(file);
            CalendarBuilder cb = new CalendarBuilder(new CalendarParserImpl());
            calByUrl = cb.build(fip);
            fip.close();
            file.setReadOnly();
            if (!calByUrl.toString().contains(Organizer.ORGANIZER)) {
                Property p = new Organizer("MAILTO:calendar@deskera.com");
                calByUrl.getProperties().add(p);
            }
            calByUrl.validate();
        }
    } catch (FileNotFoundException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calFileEx, e);
    } catch (ValidationException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calValidationEx, e);
    } catch (ParserException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calParseEx, e);
    } catch (ConfigurationException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calFileEx, e);
    } catch (URISyntaxException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calURLEx, e);
    } catch (IOException e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calIOEx, e);
    } catch (Exception e) {
        throw ServiceException.FAILURE(KWLErrorMsgs.calIOEx, e);
    }
    return calByUrl;
}

From source file:com.asakusafw.operation.tools.hadoop.fs.CleanTest.java

private File touch(String path, double day) throws IOException {
    File file = file(path);/*  ww  w  . j av a 2s .com*/
    if (file.exists() == false) {
        file.getParentFile().mkdirs();
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }
    File root = folder.getRoot().getCanonicalFile();
    File current = file;
    while (true) {
        current = current.getCanonicalFile();
        if (root.equals(current)) {
            break;
        }
        boolean succeed = current.setLastModified((long) (day * TimeUnit.DAYS.toMillis(1)));
        if (succeed == false) {
            break;
        }
        current = current.getParentFile();
        if (current == null) {
            break;
        }
    }
    return file;
}

From source file:org.geoserver.wps.remote.plugin.output.XMPPRawDataOutput.java

@Override
public Object produceOutput(Object value, String type, String pID, String baseURL, XMPPClient xmppClient,
        boolean publish, String name, String title, String description, String defaultStyle,
        String targetWorkspace, String metadata) throws Exception {

    LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] " + value + " - type:" + type + " - pID:" + pID
            + " - name:" + name + " - title:" + title + " - description:" + description + " - style:"
            + defaultStyle + " - workspace:" + targetWorkspace + " - metadata:" + metadata);

    if (XMPPClient.PRIMITIVE_NAME_TYPE_MAP.get(type) != null) {
        Object sample = ((Object[]) XMPPClient.PRIMITIVE_NAME_TYPE_MAP.get(type))[2];

        if (sample instanceof StreamRawData) {
            final String fileName = FilenameUtils.getBaseName(((String) value)) + "_" + pID + "."
                    + ((StreamRawData) sample).getFileExtension();

            LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] StreamRawData:" + fileName);

            value = new StreamRawData(((StreamRawData) sample).getMimeType(),
                    new FileInputStream(((String) value)), ((StreamRawData) sample).getFileExtension());
            if (publish) {
                final File tempFile = new File(FileUtils.getTempDirectory(), fileName);
                FileUtils.copyInputStreamToFile(((StreamRawData) value).getInputStream(), tempFile);

                try {
                    xmppClient.importLayer(tempFile, type, null, name + "_" + pID, title, description,
                            defaultStyle, targetWorkspace, metadata);
                } catch (Exception e) {
                    LOGGER.log(Level.WARNING,
                            "There was an issue while trying to automatically publish the Layer into the Catalog!",
                            e);//from   w  ww  . j a  va  2s  .  c  om
                }

                // need to re-open the stream
                value = new StreamRawData(((StreamRawData) sample).getMimeType(), new FileInputStream(tempFile),
                        ((StreamRawData) sample).getFileExtension());
            }

            LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] Value:" + value);

            return value;
        } else if (sample instanceof ResourceRawData) {
            final String fileName = FilenameUtils.getBaseName(((String) value)) + "_" + pID + "."
                    + ((ResourceRawData) sample).getFileExtension();

            LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] FileRawData:" + fileName);

            File outputFile = getOutputFile(xmppClient, (String) value);
            if (outputFile.renameTo(new File(outputFile.getParentFile(), fileName))) {
                outputFile = new File(outputFile.getParentFile(), fileName);
                outputFile.setLastModified(System.nanoTime());
            }

            value = new ResourceRawData(Files.asResource(outputFile), ((ResourceRawData) sample).getMimeType(),
                    ((ResourceRawData) sample).getFileExtension());
            if (publish) {
                try {
                    xmppClient.importLayer(outputFile, type, null, name + "_" + pID, title, description,
                            defaultStyle, targetWorkspace, metadata);
                } catch (Exception e) {
                    LOGGER.log(Level.WARNING,
                            "There was an issue while trying to automatically publish the Layer into the Catalog!",
                            e);
                }
            }

            LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] Value:" + value);

            return value;
        } else if (sample instanceof StringRawData) {

            LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] StringRawData:" + type);

            if (type.equals("application/owc")) {
                value = encodeAsPlainOWCMapContext(value, type, pID, baseURL, xmppClient, publish,
                        name + "_" + pID, title, description, defaultStyle, targetWorkspace, metadata);
            } else {
                value = encodeAsPlainRawData(value, type, pID, baseURL, xmppClient, publish, name + "_" + pID,
                        title, description, defaultStyle, targetWorkspace, metadata);
            }

            LOGGER.finest("[XMPP Raw Data Output - ProduceOutput] Value:" + value);

            return value;
        }
    }

    return null;
}

From source file:org.apache.webdav.ant.taskdefs.Get.java

/**
 * Retrieves the data of a resource and stores it in a file.
 * /*ww w  . j  a va 2 s. com*/
 * Creates required directories and sets the last modified time of the file.
 * 
 * @param url url of the resource to be retrieved
 * @param target file where the resource data ist stored
 * @param lastMod last modified date of the resource, used to set 
 *        the last modified date of the target file
 * @param relative path og the resource for logging purposes.
 * @throws IOException
 * @throws HttpException
 * @throws FileNotFoundException
 */
private void getAndStoreResource(HttpURL url, File target, long lastMod, String relative)
        throws IOException, HttpException, FileNotFoundException {
    log("downloading: " + relative, ifVerbose());
    File directory = target.getParentFile();
    if (!directory.exists()) {
        directory.mkdirs();
    }

    InputStream in = Utils.getFile(getHttpClient(), url);

    if (!target.exists()) {
        target.createNewFile();
    }
    FileOutputStream out = new FileOutputStream(target);

    copyStream(in, out, this.filterSets, this.encoding);

    out.close();
    target.setLastModified(lastMod);
    this.countWrittenFiles++;
}

From source file:com.knowbout.epg.processor.Downloader.java

private boolean downloadFile(FTPFile remoteFile) throws IOException {
    boolean success = false;
    File file = new File(destinationFolder + File.separator + remoteFile.getName());
    long lastModified = remoteFile.getTimestamp().getTimeInMillis();
    log.debug("Remote file is " + remoteFile.getName() + " local file is " + file.getAbsoluteFile()
            + " does it exist:" + file.exists());
    if (forceDownload || !file.exists() || (file.lastModified() < lastModified)) {
        log.debug("Downloading " + remoteFile.getName() + " " + remoteFile.getSize() + " to "
                + file.getAbsolutePath());

        FileOutputStream fos = new FileOutputStream(file);
        client.retrieveFile(remoteFile.getName(), fos);
        fos.close();/*from w w w  .j av a  2  s .  co  m*/
        fos.flush();
        file.setLastModified(lastModified);
        success = true;
    }
    return success;
}