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.aliasi.lingmed.medline.DownloadMedline.java

private void downloadFile(String fileName, File targetDir) throws IOException {
    boolean success = false;
    File targetFile = new File(targetDir, fileName);
    OutputStream out = null;/*from   www . j a va2s.  com*/
    BufferedOutputStream bufOut = null;
    try {
        out = new FileOutputStream(targetFile);
        bufOut = new BufferedOutputStream(out);
        mFTPClient.retrieveFile(fileName, bufOut);
        // successful download results in reply code 226: "Transfer complete"
        checkFtpCompletion("File download", true);
        success = true;
    } catch (SocketException e) {
        //            mLogger.info("SocketException=" + e);
        //            mLogger.info("Reconnecting to server.");
        reconnectFTPClient();
        //            mLogger.info("Server reply from Retrieve file="+ fileName+": "+ftpLastReply());
    } finally {
        Streams.closeOutputStream(bufOut);
        Streams.closeOutputStream(out);
    }
    if (success) {
        Date date = new Date();
        targetFile.setLastModified(date.getTime());
    }
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

private static void setLocalFileLastModifiedTime(File olf, long lmtime) {
    //      Log.v("","fp="+lf.getPath());
    if (mGp.useSetLastModifiedByTouchCommand) {
        String lmdt = StringUtil.convDateTimeTo_YearMonthDayHourMinSec(lmtime - mTimeZoneDiff);
        String dt = lmdt.substring(0, 10).replace("/", "");
        String hm = lmdt.substring(11, 17).replace(":", "");
        String ss = lmdt.substring(17, 19);
        String cmd = "/system/xbin/touch -c -t " + dt + hm + "." + ss + " \"" + olf.getPath() + "\"";
        //         Log.v("","cmd="+cmd);
        //         Log.v("","dt="+lmdt+", cmd="+cmd+", lm="+lmtime+", tz="+mTimeZoneDiff);
        executeSuCmd(cmd);/*from  w ww  .  j ava  2  s  . c o  m*/
    } else {
        olf.setLastModified(lmtime);
        //         Log.v("","rc="+rc);
    }
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static void touch(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    try {/*  w w w  . j ava 2  s  .c  om*/
        if (ArgList.length == 1 && !isNull(ArgList[0]) && !isUndefined(ArgList[0])) {
            File file = new File(Context.toString(ArgList[0]));
            boolean success = file.createNewFile();
            if (!success) {
                file.setLastModified(System.currentTimeMillis());
            }
        } else {
            throw Context.reportRuntimeError("The function call touch requires 1 valid argument.");
        }
    } catch (Exception e) {
        throw Context.reportRuntimeError(e.toString());
    }
}

From source file:cn.wanghaomiao.maven.plugin.seimi.packaging.AbstractWarPackagingTask.java

/**
 * Copy file from source to destination. The directories up to <code>destination</code> will be created if they
 * don't already exist. if the <code>onlyIfModified</code> flag is <tt>false</tt>, <code>destination</code> will be
 * overwritten if it already exists. If the flag is <tt>true</tt> destination will be overwritten if it's not up to
 * date./*  w w w . j ava2  s.  com*/
 * <p/>
 *
 * @param context the packaging context
 * @param source an existing non-directory <code>File</code> to copy bytes from
 * @param destination a non-directory <code>File</code> to write bytes to (possibly overwriting).
 * @param targetFilename the relative path of the file from the webapp root directory
 * @param onlyIfModified if true, copy the file only if the source has changed, always copy otherwise
 * @return true if the file has been copied/updated, false otherwise
 * @throws IOException if <code>source</code> does not exist, <code>destination</code> cannot be written to, or an
 *             IO error occurs during copying
 */
protected boolean copyFile(WarPackagingContext context, File source, File destination, String targetFilename,
        boolean onlyIfModified) throws IOException {
    if (onlyIfModified && destination.lastModified() >= source.lastModified()) {
        context.getLog().debug(" * " + targetFilename + " is up to date.");
        return false;
    } else {
        if (source.isDirectory()) {
            context.getLog().warn(" + " + targetFilename + " is packaged from the source folder");

            try {
                JarArchiver archiver = context.getJarArchiver();
                archiver.addDirectory(source);
                archiver.setDestFile(destination);
                archiver.createArchive();
            } catch (ArchiverException e) {
                String msg = "Failed to create " + targetFilename;
                context.getLog().error(msg, e);
                IOException ioe = new IOException(msg);
                ioe.initCause(e);
                throw ioe;
            }
        } else {
            FileUtils.copyFile(source.getCanonicalFile(), destination);
            // preserve timestamp
            destination.setLastModified(source.lastModified());
            context.getLog().debug(" + " + targetFilename + " has been copied.");
        }
        return true;
    }
}

From source file:com.opoopress.maven.plugins.plugin.downloader.ProgressURLDownloader.java

private void downloadInternal(URL url, File destination) throws IOException {
    OutputStream out = null;//  w  w w . ja v a2 s  . c o  m
    URLConnection conn;
    InputStream in = null;
    try {
        //URL url = address.toURL();
        conn = url.openConnection();

        //user agent
        final String userAgentValue = calculateUserAgent();
        conn.setRequestProperty("User-Agent", userAgentValue);

        //do not set gzip header if download zip file
        if (useGzip) {
            conn.setRequestProperty("Accept-Encoding", "gzip");
        }

        if (!useCache) {
            conn.setRequestProperty("Pragma", "no-cache");
        }

        in = conn.getInputStream();
        out = new BufferedOutputStream(new FileOutputStream(destination));

        copy(in, out);

        if (checkContentLength) {
            long contentLength = conn.getContentLengthLong();
            if (contentLength > 0 && contentLength != destination.length()) {
                throw new IllegalArgumentException("File length mismatch. expected: " + contentLength
                        + ", actual: " + destination.length());
            }
        }

        if (keepLastModified) {
            long lastModified = conn.getLastModified();
            if (lastModified > 0) {
                destination.setLastModified(lastModified);
            }
        }
    } finally {
        logMessage("");
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.workers.GetDownloadWorker.java

/**
 * Analog of VS's AsyncGetFileState.Completed method.
 *
 * This is the completion routine for async get operations. It sends version
 * updates to the server and applies file attributes to the target local
 * item./*from   w  w  w .  j a  v a 2s.  c  o m*/
 *
 * @param targetSymLink
 *        pass <code>true</code> if the target item is supposed to be a
 *        symbolic link, <code>false</code> if it's a normal file
 * @param targetSymLinkDestinationUnmapped
 *        pass <code>true</code> if the target item was not created because
 *        it was supposed to be a symbolic link but the destination was
 *        unmapped; pass <code>false</code> for a normal file item or a
 *        successful symbolic link
 * @throws VersionControlException
 *         if the operation could not be completed
 */
private void completeGetOperation(final boolean targetSymLink, final boolean targetSymLinkDestinationUnmapped) {
    Check.notNullOrEmpty(operation.getTargetLocalItem(), "operation.getTargetLocalItem()"); //$NON-NLS-1$

    log.trace(MessageFormat.format("completing get operation for {0} ({1})", //$NON-NLS-1$
            operation.getTargetLocalItem(), operation.getTargetServerItem()));

    /*
     * We need to delete the existingLocalItem if it is different. Get the
     * lock on the action object as the main loop may null out the localItem
     * if the delete is to be skipped.
     */
    synchronized (operation) {
        /*
         * Don't change attributes of symbolic links.
         */
        if (!targetSymLink) {
            // Handle last write time and the +R bit for items which don't
            // have the Edit bit set.
            if (operation.getEffectiveChangeType().contains(ChangeType.EDIT) == false || operation.isUndo()) {
                final File targetLocalFile = new File(operation.getTargetLocalItem());
                final FileSystemAttributes attrs = FileSystemUtils.getInstance().getAttributes(targetLocalFile);

                if (0 != operation.getVersionServer()
                        && !DotNETDate.MIN_CALENDAR.equals(operation.getVersionServerDate())
                        && asyncOp.getWorkspace().getOptions().contains(WorkspaceOptions.SET_FILE_TO_CHECKIN)) {
                    // Strip the +R bit before calling SetLastWriteTime, if
                    // it's set.
                    if (attrs.isReadOnly()) {
                        attrs.setReadOnly(false);
                        FileSystemUtils.getInstance().setAttributes(targetLocalFile, attrs);
                    }

                    // Set the last modified time of the file.
                    targetLocalFile.setLastModified(operation.getVersionServerDate().getTimeInMillis());
                }

                // In a server workspace, make sure that the item has the +R
                // bit.
                if (WorkspaceLocation.SERVER == asyncOp.getWorkspace().getLocation() && !attrs.isReadOnly()) {
                    attrs.setReadOnly(true);
                    FileSystemUtils.getInstance().setAttributes(targetLocalFile, attrs);
                }
            }
        }

        /*
         * Don't send the version update if the sym link destination was
         * unmapped.
         */
        if (!targetSymLinkDestinationUnmapped) {
            // If a baseline wasn't created along with this download, then
            // it's because there was a pending edit reported in the
            // ChangeType of this GetOperation. That implies that the
            // content placed on disk isn't the committed content. The
            // HashValue member of the GetOperation refers to the content
            // which was referred to by the download URL -- so we can't
            // trust it by default.

            byte[] hashValue = null;
            long committedLength = -1;

            if (null != operation.getBaselineFileGUID()) {
                // OK, a baseline was generated with this download. So we'll
                // go ahead and provide the HashValue from the getop and the
                // committed length from disk to UpdateLocalVersion.

                Check.isTrue(operation.getEffectiveChangeType().contains(ChangeType.EDIT) == false,
                        "operation.getEffectiveChangeType().contains(ChangeType.EDIT) == false"); //$NON-NLS-1$

                hashValue = operation.getHashValue();
                committedLength = new File(operation.getTargetLocalItem()).length();
            }

            String pendingChangeTargetServerItem = operation.getTargetServerItem();

            // If there's no pending change on the item, or if the item is a
            // pending add, then we don't want to use QueryPendingChanges as
            // a data source for missing fields.
            if (operation.getChangeType().equals(ChangeType.NONE)
                    || operation.getChangeType().contains(ChangeType.ADD)) {
                pendingChangeTargetServerItem = null;
            }

            final ClientLocalVersionUpdate update = new ClientLocalVersionUpdate(
                    operation.getSourceServerItem(), operation.getItemID(), operation.getTargetLocalItem(),
                    operation.getVersionServer(), operation.getVersionServerDate(), operation.getEncoding(),
                    hashValue, committedLength, operation.getBaselineFileGUID(), pendingChangeTargetServerItem,
                    operation.getPropertyValues());

            asyncOp.queueLocalVersionUpdate(update);
        }

        if (existingLocalAttrs.exists() && operation.getCurrentLocalItem() != null
                && !LocalPath.equals(operation.getCurrentLocalItem(), operation.getTargetLocalItem())) {
            Check.isTrue(operation.getItemType() != ItemType.FOLDER, "Should not try to delete a folder here: " //$NON-NLS-1$
                    + operation);

            log.trace(MessageFormat.format("deleting source {0}", operation.getCurrentLocalItem())); //$NON-NLS-1$

            getEngine.deleteSource(operation, existingLocalAttrs);
        }

        /*
         * Apply any of the extended file attributes that were stored in a
         * .tpattributes file.
         */
        getEngine.applyFileAttributesAfterGet(asyncOp, operation);

        // Tell the main get loop that we have downloaded this item so that
        // it doesn't send the delete ULV if it decides to clear the
        // action's local item.
        operation.setDownloadCompleted(true);
    }
}

From source file:syncthing.android.service.SyncthingInstance.java

void ensureBinary(String asset, String destPath) {
    long myTime = getAPKModTime();
    File f = new File(destPath);
    Timber.d("My Time:  %d", myTime);
    Timber.d("Bin Time: %d", f.lastModified());
    if (f.exists() && f.lastModified() > myTime) {
        Timber.i("%s modtime up-to-date.", f.getName());
        return;/*www . j  a  v  a  2s  .c  om*/
    }
    Timber.i("%s missing or modtime stale. Re-copying from APK.", f.getName());
    String writingFilePath = destPath + ".writing";
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        is = getAssets().open(asset);
        fos = new FileOutputStream(new File(writingFilePath));
        IOUtils.copy(is, fos);
        fos.flush();
        Timber.d("wrote out %s", writingFilePath);
        Runtime.getRuntime().exec("chmod 0700 " + writingFilePath).waitFor();
        Timber.d("did chmod 0700 on %s", writingFilePath);
        Runtime.getRuntime().exec("mv " + writingFilePath + " " + destPath).waitFor();
        Timber.d("moved %s to %s", writingFilePath, destPath);
        f = new File(destPath);
        if (f.setLastModified(System.currentTimeMillis())) {
            Timber.d("set modtime of %s", destPath);
        }
    } catch (IOException | InterruptedException e) {
        FileUtils.deleteQuietly(new File(destPath));
        FileUtils.deleteQuietly(new File(writingFilePath));
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.alibaba.jstorm.daemon.nimbus.ServiceHandler.java

@Override
public void restart(String name, String jsonConf)
        throws TException, NotAliveException, InvalidTopologyException, TopologyAssignException {
    LOG.info("Begin to restart " + name + ", new configuration:" + jsonConf);

    // 1. get topologyId
    StormClusterState stormClusterState = data.getStormClusterState();
    String topologyId;//from  w  ww.  ja  v  a2 s . com
    try {
        topologyId = Cluster.get_topology_id(stormClusterState, name);
    } catch (Exception e2) {
        topologyId = null;
    }
    if (topologyId == null) {
        LOG.info("No topology of " + name);
        throw new NotAliveException("No topology of " + name);
    }

    // Restart the topology: Deactivate -> Kill -> Submit
    // 2. Deactivate
    deactivate(name);
    JStormUtils.sleepMs(5000);
    LOG.info("Deactivate " + name);

    // 3. backup old jar/configuration/topology
    StormTopology topology;
    Map topologyConf;
    String topologyCodeLocation = null;
    try {
        topology = StormConfig.read_nimbus_topology_code(conf, topologyId);
        topologyConf = StormConfig.read_nimbus_topology_conf(conf, topologyId);
        if (jsonConf != null) {
            Map<Object, Object> newConf = (Map<Object, Object>) JStormUtils.from_json(jsonConf);
            topologyConf.putAll(newConf);
        }

        // Copy storm files back to stormdist dir from the tmp dir
        String oldDistDir = StormConfig.masterStormdistRoot(conf, topologyId);
        String parent = StormConfig.masterInbox(conf);
        topologyCodeLocation = parent + PathUtils.SEPERATOR + topologyId;
        FileUtils.forceMkdir(new File(topologyCodeLocation));
        FileUtils.cleanDirectory(new File(topologyCodeLocation));
        File stormDistDir = new File(oldDistDir);
        stormDistDir.setLastModified(System.currentTimeMillis());
        FileUtils.copyDirectory(stormDistDir, new File(topologyCodeLocation));

        LOG.info("Successfully read old jar/conf/topology " + name);
    } catch (Exception e) {
        LOG.error("Failed to read old jar/conf/topology", e);
        if (topologyCodeLocation != null) {
            try {
                PathUtils.rmr(topologyCodeLocation);
            } catch (IOException ignored) {
            }
        }
        throw new TException("Failed to read old jar/conf/topology ");

    }

    // 4. Kill
    // directly use remove command to kill, more stable than issue kill cmd
    RemoveTransitionCallback killCb = new RemoveTransitionCallback(data, topologyId);
    killCb.execute(new Object[0]);
    LOG.info("Successfully kill the topology " + name);

    // send metric events
    TopologyMetricsRunnable.KillTopologyEvent killEvent = new TopologyMetricsRunnable.KillTopologyEvent();
    killEvent.clusterName = this.data.getClusterName();
    killEvent.topologyId = topologyId;
    killEvent.timestamp = System.currentTimeMillis();
    this.data.getMetricRunnable().pushEvent(killEvent);

    Remove removeEvent = new Remove();
    removeEvent.topologyId = topologyId;
    this.data.getMetricRunnable().pushEvent(removeEvent);

    // 5. submit
    try {
        submitTopology(name, topologyCodeLocation, JStormUtils.to_json(topologyConf), topology);
    } catch (AlreadyAliveException e) {
        LOG.info("Failed to kill the topology" + name);
        throw new TException("Failed to kill the topology" + name);
    } finally {
        try {
            PathUtils.rmr(topologyCodeLocation);
        } catch (IOException ignored) {
        }
    }

}

From source file:hudson.FilePath.java

/**
 * Reads from a tar stream and stores obtained files to the base dir.
 *//* ww  w.j  av a 2s.  c  o m*/
private static void readFromTar(String name, File baseDir, InputStream in) throws IOException {
    TarInputStream t = new TarInputStream(in);
    try {
        TarEntry te;
        while ((te = t.getNextEntry()) != null) {
            File f = new File(baseDir, te.getName());
            if (te.isDirectory()) {
                f.mkdirs();
            } else {
                File parent = f.getParentFile();
                if (parent != null)
                    parent.mkdirs();

                OutputStream fos = new FileOutputStream(f);
                try {
                    IOUtils.copy(t, fos);
                } finally {
                    fos.close();
                }
                f.setLastModified(te.getModTime().getTime());
                int mode = te.getMode() & 0777;
                if (mode != 0 && !Hudson.isWindows()) // be defensive
                    try {
                        LIBC.chmod(f.getPath(), mode);
                    } catch (NoClassDefFoundError e) {
                        // be defensive. see http://www.nabble.com/-3.0.6--Site-copy-problem%3A-hudson.util.IOException2%3A--java.lang.NoClassDefFoundError%3A-Could-not-initialize-class--hudson.util.jna.GNUCLibrary-td23588879.html
                    }
            }
        }
    } catch (IOException e) {
        throw new IOException2("Failed to extract " + name, e);
    } finally {
        t.close();
    }
}

From source file:org.opengion.fukurou.util.ZipArchive.java

/**
 * ???ZIP??????// w w w . j a v a  2  s.  c  o m
 * ?(targetPath)???ZIP(zipFile)????
 * ?????????????????
 * <p>
 * ???????????????
 *
 * @param targetPath ??
 * @param zipFile    ??ZIP
 * @param encording  ?(Windows???"Windows-31J" ???)
 * @return ???ZIP?
 * @og.rev 4.1.0.2 (2008/02/01) ?
 * @og.rev 4.3.1.1 (2008/08/23) mkdirs ?
 * @og.rev 4.3.3.3 (2008/10/22) mkdirs????
 * @og.rev 5.1.9.0 (2010/08/01) ?
 * @og.rev 5.7.1.2 (2013/12/20) org.apache.commons.compress ?(??)
 */
public static List<File> unCompress(final File targetPath, final File zipFile, final String encording) {
    List<File> list = new ArrayList<File>();

    // ???'/'??'\'????
    //      String tmpPrefix = targetPath;
    //      if( File.separatorChar != targetPath.charAt( targetPath.length() - 1 ) ) {
    //              tmpPrefix = tmpPrefix + File.separator;
    //      }

    ZipArchiveInputStream zis = null;
    File tmpFile = null;
    //      String fileName = null;

    try {
        zis = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(zipFile)), encording);

        ZipArchiveEntry entry = null;
        while ((entry = zis.getNextZipEntry()) != null) {
            //                      fileName = tmpPrefix + entry.getName().replace( '/', File.separatorChar );
            tmpFile = new File(targetPath, entry.getName());
            list.add(tmpFile);

            // ??????
            if (entry.isDirectory()) {
                if (!tmpFile.exists() && !tmpFile.mkdirs()) {
                    String errMsg = "??????[??="
                            + tmpFile + "]";
                    System.err.println(errMsg);
                    continue;
                }
            }
            // ????????
            else {
                // 4.3.3.3 (2008/10/22) ?????
                if (!tmpFile.getParentFile().exists() && !tmpFile.getParentFile().mkdirs()) {
                    String errMsg = "??????[??="
                            + tmpFile + "]";
                    System.err.println(errMsg);
                    continue;
                }

                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile));
                try {
                    IOUtils.copy(zis, out);
                } catch (IOException zex) {
                    String errMsg = "ZIP??(copy)?????[??="
                            + tmpFile + "]";
                    System.err.println(errMsg);
                    continue;
                } finally {
                    Closer.ioClose(out);
                }
            }
            // 5.1.9.0 (2010/08/01) ?
            long lastTime = entry.getTime();
            if (lastTime >= 0 && !tmpFile.setLastModified(lastTime)) {
                String errMsg = "ZIP??????[??=" + tmpFile
                        + "]";
                System.err.println(errMsg);
            }
        }
    } catch (FileNotFoundException ex) {
        String errMsg = "????????[??=" + tmpFile + "]";
        throw new RuntimeException(errMsg, ex);
    } catch (IOException ex) {
        String errMsg = "ZIP???????[??=" + tmpFile + "]";
        throw new RuntimeException(errMsg, ex);
    } finally {
        Closer.ioClose(zis);
    }

    return list;
}