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.example.util.FileUtils.java

/**
 * Internal copy directory method./*from   w  w  w .  ja  v a 2 s .co  m*/
 * 
 * @param srcDir  the validated source directory, must not be {@code null}
 * @param destDir  the validated destination directory, must not be {@code null}
 * @param filter  the filter to apply, null means copy all directories and files
 * @param preserveFileDate  whether to preserve the file date
 * @param exclusionList  List of files and directories to exclude from the copy, may be null
 * @throws IOException if an error occurs
 * @since 1.1
 */
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate,
        List<String> exclusionList) throws IOException {
    // recurse
    File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
    if (srcFiles == null) { // null if abstract pathname does not denote a directory, or if an I/O error occurs
        throw new IOException("Failed to list contents of " + srcDir);
    }
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (!destDir.mkdirs() && !destDir.isDirectory()) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    for (File srcFile : srcFiles) {
        File dstFile = new File(destDir, srcFile.getName());
        if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) {
            if (srcFile.isDirectory()) {
                doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
            } else {
                doCopyFile(srcFile, dstFile, preserveFileDate);
            }
        }
    }

    // Do this last, as the above has probably affected directory metadata
    if (preserveFileDate) {
        destDir.setLastModified(srcDir.lastModified());
    }
}

From source file:org.wso2.carbon.registry.synchronization.operation.CheckOutCommand.java

private void checkOutRecursively(XMLStreamReader xmlReader, String filePath, String path,
        UserInputCallback callback) throws SynchronizationException, XMLStreamException {
    // we will first generate the axiom node from the reader,
    OMElement root = Utils.readMetaElement(xmlReader);
    // adding path and the registryUrl
    root.addAttribute(DumpConstants.RESOURCE_PATH, path, null);
    if (registryUrl != null) {
        root.addAttribute("registryUrl", registryUrl, null);
    }/*from w  w w  . j  a va  2 s  .  com*/

    String isCollectionString = root.getAttributeValue(new QName(DumpConstants.RESOURCE_IS_COLLECTION));
    boolean isCollection = isCollectionString.equals("true");

    String name = root.getAttributeValue(new QName(DumpConstants.RESOURCE_NAME));

    byte[] contentBytes = new byte[0];
    File file = new File(filePath);
    boolean overwrite = true;
    boolean fileAlreadyExist = false;

    String parentDirName = file.getAbsoluteFile().getParent();

    String metaDirectoryName;
    String metaFilePath;
    if (isCollection) {
        metaDirectoryName = filePath + File.separator + SynchronizationConstants.META_DIRECTORY;
        metaFilePath = filePath + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + SynchronizationConstants.META_FILE_EXTENSION;
    } else {
        metaDirectoryName = parentDirName + File.separator + SynchronizationConstants.META_DIRECTORY;
        metaFilePath = parentDirName + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + Utils.encodeResourceName(name)
                + SynchronizationConstants.META_FILE_EXTENSION;
    }

    if (file.exists()) {
        fileAlreadyExist = true;
    }

    if (!isCollection && fileAlreadyExist) {
        if (!Utils.resourceUpdated(metaFilePath, root) || (callback != null && !callback.getConfirmation(
                new Message(MessageCode.FILE_OVERWRITE_CONFIRMATION, new String[] { filePath }),
                SynchronizationConstants.OVERWRITE_CONFIRMATION_CONTEXT))) {
            overwrite = false;
        }
    }
    try {
        // Create file if it does not exist
        if (isCollection) {
            if (!fileAlreadyExist && Utils.resourceUpdated(metaFilePath, root)) {
                boolean ignore = file.mkdir(); // ignores the return value purposely
            } else {
                overwrite = false;
            }
        } else if (overwrite) {
            boolean ignore = file.createNewFile(); // ignores the return value purposely
        }
    } catch (IOException e) {
        throw new SynchronizationException(MessageCode.FILE_CREATION_FAILED, e,
                new String[] { "file: " + filePath });
    }

    // we are extracting the content from the meta element.
    Iterator children = root.getChildren();
    while (children.hasNext()) {
        OMElement child = (OMElement) children.next();
        String localName = child.getLocalName();

        // LastModified
        if (localName.equals(DumpConstants.LAST_MODIFIED)) {
            OMText text = (OMText) child.getFirstOMChild();
            if (text != null) {
                long date = Long.parseLong(text.getText());
                // We are not bothered whether this failed to set the last-modified time. If we
                // cannot modify the file, we would fail when attempting to write to it anyway.
                boolean ignore = file.setLastModified(date);
            }
        }
        // get content
        else if (localName.equals(DumpConstants.CONTENT)) {
            OMText text = (OMText) child.getFirstOMChild();
            // we keep content as base64 encoded
            if (text != null) {
                contentBytes = Base64.decode(text.getText());
            }
            String md5 = Utils.getMD5(contentBytes);
            root.addAttribute("md5", md5, null);
            child.detach();
        }
    }

    if (!isCollection && overwrite) {
        try {
            FileOutputStream fileStream = null;
            try {
                fileStream = new FileOutputStream(file);
                fileStream.write(contentBytes);
                fileStream.flush();
            } finally {
                if (fileStream != null) {
                    fileStream.close();
                }
            }
        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.PROBLEM_IN_CREATING_CONTENT, e,
                    new String[] { "file: " + filePath });
        }
    }

    // creating the meta directory
    File metaDirectory = new File(metaDirectoryName);
    if (!metaDirectory.exists() && !metaDirectory.mkdir()) {
        throw new SynchronizationException(MessageCode.ERROR_CREATING_META_FILE,
                new String[] { "file: " + metaDirectoryName });
    }

    // creating the meta file
    Utils.createMetaFile(metaFilePath, root);

    // printing out the information of the file
    if (!fileAlreadyExist) {
        if (callback != null) {
            callback.displayMessage(new Message(MessageCode.ADDED, new String[] { filePath }));
        }
        addedCount++;
    } else {
        if (overwrite) {
            if (callback != null) {
                callback.displayMessage(new Message(MessageCode.OVERWRITTEN, new String[] { filePath }));
            }
            overwrittenCount++;
        } else {
            if (callback != null) {
                callback.displayMessage(new Message(MessageCode.NON_OVERWRITTEN, new String[] { filePath }));
            }
            nonOverwrittenCount++;
        }
    }

    if (!xmlReader.hasNext()
            || !(xmlReader.isStartElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN))) {
        // finished the recursion
        // consuming the stream until the resource end element found
        while (xmlReader.hasNext()
                && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE))) {
            xmlReader.next();
        }
        return;
    }

    do {
        xmlReader.next();
        if (xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN)) {
            // this means empty children, just quit from here
            // before that we have to set the cursor to the end of the current resource
            if (xmlReader.hasNext()) {
                do {
                    xmlReader.next();
                } while (xmlReader.hasNext() && !(xmlReader.isEndElement()
                        && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
            }
            return;
        }
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    while (xmlReader.hasNext() && xmlReader.isStartElement()
            && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        // prepare the children absolute path
        String childName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
        String fileResourceName = childName;
        String childFilePath = filePath + File.separator + fileResourceName;
        String childPath = (path.equals("/") ? "" : path) + "/" + childName;

        checkOutRecursively(xmlReader, childFilePath, childPath, callback);

        while ((!xmlReader.isStartElement() && xmlReader.hasNext())
                && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN))) {
            xmlReader.next();
        }
        if (xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN)) {
            // we are in the end of the children tag.
            break;
        }
    }
    // consuming the stream until the resource end element found
    while (xmlReader.hasNext()
            && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE))) {
        xmlReader.next();
    }
}

From source file:org.opencms.staticexport.CmsStaticExportManager.java

/**
  * Writes a resource to the given export path with the given rfs name and the given content.<p>
  * /*from  w w w  . ja va2 s.  c om*/
  * @param req the current request
  * @param exportPath the path to export the resource
  * @param rfsName the rfs name
  * @param resource the resource
  * @param content the content
  * 
  * @throws CmsException if something goes wrong
  */
protected void writeResource(HttpServletRequest req, String exportPath, String rfsName, CmsResource resource,
        byte[] content) throws CmsException {

    String exportFileName = CmsFileUtil.normalizePath(exportPath + rfsName);

    // make sure all required parent folder exist
    createExportFolder(exportPath, rfsName);
    // generate export file instance and output stream
    File exportFile = new File(exportFileName);
    // write new exported file content
    try {
        FileOutputStream exportStream = new FileOutputStream(exportFile);
        exportStream.write(content);
        exportStream.close();

        // log export success 
        if (LOG.isInfoEnabled()) {
            LOG.info(Messages.get().getBundle().key(Messages.LOG_STATIC_EXPORTED_2, resource.getRootPath(),
                    exportFileName));
        }

    } catch (Throwable t) {
        throw new CmsStaticExportException(
                Messages.get().container(Messages.ERR_OUTPUT_STREAM_1, exportFileName), t);
    }
    // update the file with the modification date from the server
    if (req != null) {
        Long dateLastModified = (Long) req.getAttribute(CmsRequestUtil.HEADER_OPENCMS_EXPORT);
        if ((dateLastModified != null) && (dateLastModified.longValue() != -1)) {
            exportFile.setLastModified((dateLastModified.longValue() / 1000) * 1000);
            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_SET_LAST_MODIFIED_2, exportFile.getName(),
                        new Long((dateLastModified.longValue() / 1000) * 1000)));
            }
        }
    } else {
        // otherwise take the last modification date form the OpenCms resource
        exportFile.setLastModified((resource.getDateLastModified() / 1000) * 1000);
    }
}

From source file:com.matteoveroni.model.copy.FileUtils.java

/**
 * Internal copy file method.// w w w  .j  av a  2 s.c  o  m
 * 
 * @param srcFile  the validated source file, must not be {@code null}
 * @param destFile  the validated destination file, must not be {@code null}
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        bytesTransferedTotal = 0;
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;

            //pos += output.transferFrom(input, pos, count);

            //Split into into deceleration and assignment to count bytes transfered
            long bytesTransfered = output.transferFrom(input, pos, count);
            //complete original method
            pos += bytesTransfered;
            //update total bytes copied, so it can be used to calculate progress
            bytesTransferedTotal += bytesTransfered;
            System.out.println((int) Math.floor((100.0 / size) * bytesTransferedTotal) + "%");
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}

From source file:com.mediaworx.intellij.opencmsplugin.sync.VfsAdapter.java

/**
 * pushes a file from the RFS to the VFS
 * @param entity    the sync entity representing the file to be pushed
 * @return  a CMIS document of the newly created VFS file
 * @throws CmsPushException//  w  ww. j av a  2 s  . c  o  m
 */
public Document pushFile(SyncEntity entity) throws CmsPushException {
    if (!connected) {
        LOG.info("not connected");
        return null;
    }

    File rfsFile = entity.getFile();
    FileInputStream rfsFileInputStream = null;
    Document vfsFile = null;
    long vfsFileModifiedTime = 0;

    try {
        rfsFileInputStream = new FileInputStream(rfsFile);
        String mimetype = new MimetypesFileTypeMap().getContentType(rfsFile);

        ContentStream contentStream = session.getObjectFactory().createContentStream(rfsFile.getName(),
                rfsFile.length(), mimetype, rfsFileInputStream);

        // if the file already exists in the VFS ...
        if (entity.replaceExistingEntity()) {
            // ... update its content
            vfsFile = (Document) entity.getVfsObject();
            vfsFile.setContentStream(contentStream, true, true);
        }
        // if the file doesn't exist in the VFS
        else {
            // ... get the parent folder object from the VFS
            String parentPath = entity.getVfsPath().substring(0, entity.getVfsPath().lastIndexOf("/"));
            Folder parent = getOrCreateFolder(parentPath);

            // ... and create the file as Document Object under the parent folder
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_DOCUMENT.value());
            properties.put(PropertyIds.NAME, rfsFile.getName());
            vfsFile = parent.createDocument(properties, contentStream, VersioningState.NONE);
        }

        // Set file modification date in the VFS to the RFS file date
        // This does not work when using OpenCms since OpenCms always sets the date of the CMIS change event
        // That's why the file date in the RFS has to be set to the VFS date (see finally block)
        /*
        Map<String, Object> dateProperties = new HashMap<String, Object>(1);
        GregorianCalendar modifiedGC = new GregorianCalendar();
        modifiedGC.setTime(new Date(rfsFile.lastModified()));
        dateProperties.put(PropertyIds.LAST_MODIFICATION_DATE, modifiedGC);
        vfsFile.updateProperties(dateProperties, false);
        */

        vfsFileModifiedTime = vfsFile.getLastModificationDate().getTimeInMillis();
    } catch (FileNotFoundException e) {
        LOG.info("File not found.");
    } catch (CmisNameConstraintViolationException e) {
        throw new CmsPushException("Could not push entity " + entity.getVfsPath()
                + ", there was a problem with the resource name.\n" + e.getMessage(), e);
    } catch (CmisRuntimeException e) {
        throw new CmsPushException("Could not push entity " + entity.getVfsPath()
                + ", there may be an issue with a lock or an XML validation issue. Look at the OpenCms log file to find out what went wrong.\n"
                + e.getMessage(), e);
    } finally {
        try {
            if (rfsFileInputStream != null) {
                rfsFileInputStream.close();
            }

            if (vfsFileModifiedTime > 0) {
                // Since setting the modification Date on the VFS file ain't possible, set the date for the RFS file
                if (rfsFile.setLastModified(vfsFileModifiedTime)) {
                    LOG.info("Setting lastModificationDate successful");
                } else {
                    LOG.info("Setting lastModificationDate NOT successful");
                }
            }
        } catch (IOException e) {
            // do nothing
        }
    }

    return vfsFile;
}

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

/**
 * Process all the GetOperations the server returned to us as a result of
 * its get() method. This is generally not called directly from users of
 * this library. Instead, call the get methods in the {@link Workspace}
 * class./*from w  ww . j  a  v  a 2s  .com*/
 * <p>
 * <!-- Event Origination Info -->
 * <p>
 * This method is an <b>core event origination point</b>. The
 * {@link EventSource} object that accompanies each event fired by this
 * method describes the execution context (current thread, etc.) when and
 * where this method was invoked.
 *
 * @param the
 *        workspace to process operations in (must not be <code>null</code>)
 * @param type
 *        the type of process to perform on the get operations (must not be
 *        <code>null</code>)
 * @param requestType
 *        the type of request for the operations (must not be
 *        <code>null</code>)
 * @param results
 *        the array of arrays of operations the server returned. Null items
 *        in the arrays will be skipped. Null arrays are not allowed.
 * @param options
 *        options for the get operation (must not be <code>null</code>)
 * @param deleteUndoneAdds
 *        if <code>true</code> adds which are undone can be deleted
 * @param onlineOperation
 *        true if this is for a server workspace
 * @param flags
 *        flags returned by the server when pending changes (must not be
 *        <code>null</code>; pass ChangePendedFlags.UNKNOWN if no server
 *        value available in your operation)
 * @return the status of the operation. Failure information for each item is
 *         available inside this object.
 * @throws CanceledException
 *         if the user canceled the processing through the default
 *         {@link TaskMonitor}
 */
public GetStatus processGetOperations(final Workspace workspace, final ProcessType type,
        final RequestType requestType, final GetOperation[][] results, final GetOptions options,
        final boolean deleteUndoneAdds, final boolean onlineOperation, final ChangePendedFlags flags)
        throws CanceledException {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$
    Check.notNull(type, "type"); //$NON-NLS-1$
    Check.notNull(requestType, "requestType"); //$NON-NLS-1$
    Check.notNull(results, "results"); //$NON-NLS-1$
    Check.notNull(options, "options"); //$NON-NLS-1$
    Check.notNull(flags, "flags"); //$NON-NLS-1$

    log.debug("Set all get operations type to: " + type.toString()); //$NON-NLS-1$
    int getOpsCount = 0;
    for (final GetOperation[] getOperations : results) {
        for (final GetOperation getOp : getOperations) {
            getOp.setProcessType(type);
            getOpsCount++;
        }
    }
    log.debug("Get operations count: " + String.valueOf(getOpsCount)); //$NON-NLS-1$

    final UpdateLocalVersionQueueOptions localUpdateOptions = calculateUpdateLocalVersionOptions(workspace,
            type, requestType, onlineOperation);

    log.debug("localUpdateOptions: " + localUpdateOptions.toString()); //$NON-NLS-1$
    log.debug("options: " + options.toString()); //$NON-NLS-1$

    final List<ClientLocalVersionUpdate> remapUpdates = new ArrayList<ClientLocalVersionUpdate>();

    if (WorkspaceLocation.LOCAL == workspace.getLocation() && options.contains(GetOptions.REMAP)) {
        final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
        try {
            log.debug("Trying to remap versions in the local workspace"); //$NON-NLS-1$
            transaction.execute(new LocalVersionTransaction() {
                @Override
                public void invoke(final WorkspaceVersionTable lv) {
                    // In a server workspace, when Remap is specified, the
                    // local version table is updated for you when an item
                    // is remapped. In a local workspace, the local version
                    // table is not updated, and a GetOperation is returned
                    // with VersionLocal set equal to VersionServer and
                    // SourceLocalItem equal to TargetLocalItem.
                    // VersionLocal is not actually set to that value yet.
                    // We must update the local version table (both local
                    // and server) in response to these GetOperations.

                    final boolean setLastFileTimeToCheckin = workspace.getOptions()
                            .contains(WorkspaceOptions.SET_FILE_TO_CHECKIN);

                    for (final GetOperation[] getOperations : results) {
                        for (final GetOperation getOp : getOperations) {
                            if (null != getOp.getTargetLocalItem()
                                    && LocalPath.equals(getOp.getSourceLocalItem(), getOp.getTargetLocalItem())
                                    &&
                            // Here the server is lying and telling us
                            // VersionLocal is equal to VersionServer
                            // even though it does not (yet). It is a
                            // signal that this is a remap operation.
                            getOp.getVersionLocal() == getOp.getVersionServer()) {
                                getOp.setIgnore(true);

                                final WorkspaceLocalItem lvExisting = lv
                                        .getByLocalItem(getOp.getTargetLocalItem());

                                if (null != lvExisting) {
                                    // If necessary, update the
                                    // last-modified time of the item on
                                    // disk to match the new check-in date
                                    // of the item that now occupies that
                                    // local path.
                                    if (setLastFileTimeToCheckin
                                            && !DotNETDate.MIN_CALENDAR.equals(getOp.getVersionServerDate())
                                            && VersionControlConstants.ENCODING_FOLDER != getOp.getEncoding()
                                            && new File(getOp.getTargetLocalItem()).exists()) {
                                        try {
                                            final File targetLocalFile = new File(getOp.getTargetLocalItem());
                                            final FileSystemAttributes attrs = FileSystemUtils.getInstance()
                                                    .getAttributes(targetLocalFile);
                                            boolean restoreReadOnly = false;

                                            if (attrs.isReadOnly()) {
                                                attrs.setReadOnly(false);
                                                FileSystemUtils.getInstance().setAttributes(targetLocalFile,
                                                        attrs);
                                                restoreReadOnly = true;
                                            }

                                            targetLocalFile.setLastModified(
                                                    getOp.getVersionServerDate().getTimeInMillis());

                                            if (restoreReadOnly) {
                                                attrs.setReadOnly(true);
                                                FileSystemUtils.getInstance().setAttributes(targetLocalFile,
                                                        attrs);
                                            }
                                        } catch (final Exception ex) {
                                            log.warn("Error setting file time for get with remap", ex); //$NON-NLS-1$
                                        }
                                    }

                                    remapUpdates.add(new ClientLocalVersionUpdate(getOp.getSourceServerItem(),
                                            getOp.getItemID(), getOp.getTargetLocalItem(),
                                            getOp.getVersionServer(), getOp.getVersionServerDate(),
                                            getOp.getEncoding(), lvExisting.getHashValue(),
                                            lvExisting.getLength(), lvExisting.getBaselineFileGUID(),
                                            null /* pendingChangeTargetServerItem */,
                                            getOp.getPropertyValues()));
                                }
                            }
                        }
                    }

                }
            });
        } finally {
            try {
                transaction.close();
            } catch (final IOException e) {
                throw new VersionControlException(e);
            }
        }

        log.debug("The remapUpdates list has been prepared"); //$NON-NLS-1$
    }

    final WorkspaceLock wLock = workspace.lock();

    try {
        /*
         * Create a BaselineFolderCollection object to speed up read
         * operations on the baseline folders (so that each simple operation
         * like creating a new baseline file, deleting a baseline file, etc.
         * does not require us to open/close the WP table). Then attach that
         * BaselineFolderCollection to the WorkspaceLock which protects this
         * ProcessGetOperations().
         */
        final AtomicReference<BaselineFolderCollection> baselineFolders = new AtomicReference<BaselineFolderCollection>();

        if (workspace.getLocation() == WorkspaceLocation.LOCAL) {
            final LocalWorkspaceTransaction transaction = new LocalWorkspaceTransaction(workspace);
            try {
                transaction.execute(new WorkspacePropertiesTransaction() {
                    @Override
                    public void invoke(final LocalWorkspaceProperties wp) {
                        baselineFolders.set(new BaselineFolderCollection(workspace, wp.getBaselineFolders()));
                    }
                });
            } finally {
                try {
                    transaction.close();
                } catch (final IOException e) {
                    throw new VersionControlException(e);
                }
            }

            wLock.setBaselineFolders(baselineFolders.get());
        }

        log.debug("remapUpdates.size(): " + remapUpdates.size()); //$NON-NLS-1$

        if (remapUpdates.size() > 0) {
            // If we have any remap update requests for the local version
            // table, execute them using a larger batch size than we
            // normally use. No file downloads are happening so these should
            // go through very quickly.
            Check.isTrue(localUpdateOptions.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER),
                    "localUpdateOptions.contains(UpdateLocalVersionQueueOptions.UPDATE_SERVER)"); //$NON-NLS-1$

            final UpdateLocalVersionQueue ulvq = new UpdateLocalVersionQueue(workspace, localUpdateOptions,
                    wLock, 5000 /* flushTriggerLevel */, 10000 /* maximumLevel */,
                    Integer.MAX_VALUE /* timeTriggerInMilliseconds */);

            try {
                for (final ClientLocalVersionUpdate remapUpdate : remapUpdates) {
                    ulvq.queueUpdate(remapUpdate);
                }
            } finally {
                ulvq.close();
            }

            log.debug("Local version updates have been successfully queued."); //$NON-NLS-1$
        }

        // Now, create an object to track the state for this get operation.
        final AsyncGetOperation asyncOp = new AsyncGetOperation(workspace, type, requestType, options,
                deleteUndoneAdds, wLock, localUpdateOptions, flags,
                new AccountingCompletionService<WorkerStatus>(client.getUploadDownloadWorkerExecutor()));

        log.debug("Preparing Get Operation actions"); //$NON-NLS-1$

        final GetOperation[] actions = prepareGetOperations(asyncOp, results);

        log.debug("Number of Get Operation actions prepared: " + actions.length); //$NON-NLS-1$

        processOperations(asyncOp, actions);

        log.debug("All Get Operation actions have been processed."); //$NON-NLS-1$

        return asyncOp.getStatus();
    } catch (final CoreCancelException e) {
        throw new CanceledException();
    } finally {
        if (wLock != null) {
            wLock.close();
        }
    }
}

From source file:com.kii.cloud.sync.DownloadManager.java

/**
 * Download KiiFile.//  w  w w. j  a  v  a  2  s .co m
 * 
 * @param destFile
 *            - specifiy where the downloaded file is saved.
 * @param srcFile
 *            - KiiFile to be downloaded
 * @param overwrite
 *            - specifiy if overwrite the destination file.
 * @throws IOException
 */
private void downloadKiiFile(File destFile, KiiFile srcFile, boolean overwrite) throws IOException {
    boolean result = true;
    InputStream input = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    File tempDest = null;
    try {
        // check for valid URL
        String remotePath = srcFile.getRemotePath();
        if (remotePath == null) {
            Log.e(TAG, "remotePath is empty");
            throw new IllegalArgumentException("HTTP download URL is empty");
        }
        Log.d(TAG, "downloadKiiFile, remotePath is " + remotePath);

        // check if the destinated file exist
        // if yes, check if overwrite permitted
        if (destFile.exists()) {
            if (!overwrite) {
                throw new IllegalArgumentException("File already exist:" + destFile.getAbsolutePath());
            }
        }

        // check if the destinated folder exist
        // if not, create the folder
        File destFolder = destFile.getParentFile();
        if (destFolder == null) {
            throw new IllegalArgumentException("Cannot create folder for file: " + destFile);
        }
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }

        // send notification that download in progress
        if (mContext != null) {
            Intent intent = new Intent();
            intent.setAction(ACTION_DOWNLOAD_START);
            intent.putExtra(DOWNLOAD_DEST_PATH, destFile.getAbsolutePath());
            mContext.sendBroadcast(intent);
            Intent progressIntent = new Intent(mContext.getApplicationContext(), ProgressListActivity.class);
            NotificationUtil.showDownloadProgressNotification(mContext.getApplicationContext(), progressIntent,
                    destFile.getAbsolutePath());
        }

        // create a temp file for download the file
        tempDest = new File(destFile.getAbsoluteFile() + "." + Long.toString(System.currentTimeMillis()));
        HttpGet httpGet = new HttpGet(remotePath);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            throw new IOException(
                    "Code: " + statusLine.getStatusCode() + "; Reason:" + statusLine.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new IOException("Cannot read file content.");
        }

        input = entity.getContent();
        fos = new FileOutputStream(tempDest);
        bos = new BufferedOutputStream(fos);
        int len = -1;
        byte[] buffer = new byte[1024];
        // download the file by batch
        while ((len = input.read(buffer)) > 0) {
            bos.write(buffer, 0, len);
            downloadCurrentSize += len;
        }

        // delete the existing if it exist
        if (destFile.exists()) {
            destFile.delete();
        }
        if (tempDest.exists()) {
            Log.d(TAG, "Download file: s=" + tempDest.length() + "; d=" + tempDest.lastModified());
            // rename the download file to it original file
            if (!tempDest.renameTo(destFile)) {
                throw new IllegalArgumentException("Failed to rename:" + tempDest.getAbsolutePath());
            }
            // TODO: the download is success, update the kiifile status;
            // after rename, create a new file handler
            tempDest = new File(destFile.getAbsolutePath());
            // check if the file exists
            if (tempDest.exists()) {
                if (tempDest.setLastModified(srcFile.getUpdateTime()) == false) {
                    // on some Galaxy phones, it will fail, we simply ignore
                    // this error and print an error log
                    Log.e(TAG, "Failed to restore:" + tempDest.getAbsolutePath());
                }
            } else {
                throw new IllegalArgumentException(
                        "Failed to restore, file not exist after rename:" + tempDest.getAbsolutePath());
            }
        } else {
            throw new IllegalArgumentException(
                    "Failed to restore, file not exist after dnload:" + tempDest.getAbsolutePath());
        }

    } catch (IllegalArgumentException ex) {
        if (mContext != null) {
            Intent intent = new Intent();
            intent.setAction(ACTION_DOWNLOAD_START);
            intent.putExtra(DOWNLOAD_DEST_PATH, destFile.getAbsolutePath());
            mContext.sendBroadcast(intent);

            Intent progressIntent = new Intent(mContext.getApplicationContext(), ProgressListActivity.class);
            NotificationUtil.showDownloadProgressNotification(mContext.getApplicationContext(), progressIntent,
                    ex.getMessage());
            result = false;
        }
        throw new IOException("IllegalArgumentException:" + ex.getMessage());

    } finally {
        Utils.closeSilently(bos);
        Utils.closeSilently(fos);
        Utils.closeSilently(input);
        if (mContext != null) {
            Intent intent = new Intent();
            intent.setAction(ACTION_DOWNLOAD_END);
            intent.putExtra(DOWNLOAD_DEST_PATH, destFile.getAbsolutePath());
            intent.putExtra(DOWNLOAD_RESULT, result);
            mContext.sendBroadcast(intent);
            // cancel the notification if no error
            if (result) {
                NotificationUtil.cancelDownloadProgressNotification(mContext);
            } else {
                // delete the temp file if error exist
                if ((tempDest != null) && tempDest.exists()) {
                    tempDest.delete();
                }
            }
            KiiSyncClient.getInstance(mContext).notifyKiiFileLocalChange();
            // force the system to run a media scan
            MediaScannerConnection.scanFile(mContext, new String[] { destFile.getAbsolutePath() }, null, null);
        }
    }
}

From source file:edu.mit.mobile.android.locast.data.MediaSync.java

/**
 * Checks the local file system and checks to see if the given media
 * resource has been downloaded successfully already. If not, it will
 * download it from the server and store it in the filesystem. This uses the
 * last-modified header and file length to determine if a media resource is
 * up to date.//from   w  w w  .  ja va2s.com
 *
 * This method blocks for the course of the download, but shows a progress
 * notification.
 *
 * @param pubUri
 *            the http:// uri of the public resource
 * @param saveFile
 *            the file that the resource will be saved to
 * @param castMediaUri
 *            the content:// uri of the cast
 * @return true if anything has changed. False if this function has
 *         determined it doesn't need to do anything.
 * @throws SyncException
 */
public boolean downloadMediaFile(String pubUri, File saveFile, Uri castMediaUri) throws SyncException {
    final NetworkClient nc = NetworkClient.getInstance(this);
    try {
        boolean dirty = true;
        //String contentType = null;

        if (saveFile.exists()) {
            final HttpResponse headRes = nc.head(pubUri);
            final long serverLength = Long.valueOf(headRes.getFirstHeader("Content-Length").getValue());
            // XXX should really be checking the e-tag too, but this will be
            // fine for our application.
            final Header remoteLastModifiedHeader = headRes.getFirstHeader("last-modified");

            long remoteLastModified = 0;
            if (remoteLastModifiedHeader != null) {
                remoteLastModified = DateUtils.parseDate(remoteLastModifiedHeader.getValue()).getTime();
            }

            final HttpEntity entity = headRes.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            if (saveFile.length() == serverLength && saveFile.lastModified() >= remoteLastModified) {
                if (DEBUG) {
                    Log.i(TAG, "Local copy of cast " + saveFile
                            + " seems to be the same as the one on the server. Not re-downloading.");
                }

                dirty = false;
            }
            // fall through and re-download, as we have a different size
            // file locally.
        }
        if (dirty) {
            final Uri castUri = CastMedia.getCast(castMediaUri);
            String castTitle = Cast.getTitle(this, castUri);
            if (castTitle == null) {
                castTitle = "untitled";
            }

            final HttpResponse res = nc.get(pubUri);
            final HttpEntity ent = res.getEntity();

            /*
            final ProgressNotification notification = new ProgressNotification(
                  this, getString(R.string.sync_downloading_cast,
                castTitle), ProgressNotification.TYPE_DOWNLOAD,
                  PendingIntent.getActivity(this, 0, new Intent(
                Intent.ACTION_VIEW, castUri)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0),
                  false);
            */
            final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            final NotificationProgressListener npl = new NotificationProgressListener(nm, null,
                    ent.getContentLength(), 0);
            final InputStreamWatcher is = new InputStreamWatcher(ent.getContent(), npl);

            try {
                if (DEBUG) {
                    Log.d(TAG, "Downloading " + pubUri + " and saving it in " + saveFile.getAbsolutePath());
                }
                final FileOutputStream fos = new FileOutputStream(saveFile);
                StreamUtils.inputStreamToOutputStream(is, fos);
                fos.close();

                // set the file's last modified to match the remote.
                // We can check this later to see if everything is up to
                // date.
                final Header lastModified = res.getFirstHeader("last-modified");
                if (lastModified != null) {
                    saveFile.setLastModified(DateUtils.parseDate(lastModified.getValue()).getTime());
                }

                //contentType = ent.getContentType().getValue();

            } finally {
                npl.done();
                ent.consumeContent();
                is.close();
            }

            // XXX avoid this to prevent adding to local collection
            // final String filePath = saveFile.getAbsolutePath();

            // scanMediaItem(castMediaUri, filePath, contentType);
            return true;
        }
    } catch (final Exception e) {
        final SyncException se = new SyncException("Error downloading content item.");
        se.initCause(e);
        throw se;
    }
    return false;
}

From source file:edu.mit.mobile.android.locast.sync.AbsMediaSync.java

/**
 * Checks the local file system and checks to see if the given media resource has been
 * downloaded successfully already. If not, it will download it from the server and store it in
 * the filesystem. This uses the last-modified header and file length to determine if a media
 * resource is up to date.//w ww  . jav  a2  s  . c o m
 *
 * This method blocks for the course of the download, but shows a progress notification.
 *
 * @param pubUri
 *            the http:// uri of the public resource
 * @param saveFile
 *            the file that the resource will be saved to
 * @param castMediaUri
 *            the content:// uri of the cast
 * @param listener
 *            TODO
 * @return true if anything has changed. False if this function has determined it doesn't need
 *         to do anything.
 * @throws SyncException
 */
public boolean downloadMediaFile(String pubUri, File saveFile, final Uri castMediaUri,
        final FileTransferProgressListener listener) throws SyncException {
    final NetworkClient nc = getNetworkClient(getAccount());

    try {
        boolean dirty = true;
        // String contentType = null;

        if (saveFile.exists()) {
            final HttpResponse headRes = nc.head(pubUri);
            final long serverLength = Long.valueOf(headRes.getFirstHeader("Content-Length").getValue());
            // XXX should really be checking the e-tag too, but this will be
            // fine for our application.
            final Header remoteLastModifiedHeader = headRes.getFirstHeader("last-modified");

            long remoteLastModified = 0;
            if (remoteLastModifiedHeader != null) {
                remoteLastModified = DateUtils.parseDate(remoteLastModifiedHeader.getValue()).getTime();
            }

            final HttpEntity entity = headRes.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            if (saveFile.length() == serverLength && saveFile.lastModified() >= remoteLastModified) {
                if (DEBUG) {
                    Log.i(TAG, "Local copy of cast " + saveFile
                            + " seems to be the same as the one on the server. Not re-downloading.");
                }

                dirty = false;
            }
            // fall through and re-download, as we have a different size
            // file locally.
        }
        if (dirty) {
            final Uri titledItem = getTitledItemForCastMedia(castMediaUri);
            String castTitle = TitledUtils.getTitle(this, titledItem);
            if (castTitle == null) {
                castTitle = "untitled";
            }

            listener.onTransferStart(castMediaUri, castTitle, null, 0);

            final HttpResponse res = nc.get(pubUri);
            final HttpEntity ent = res.getEntity();

            final long max = ent.getContentLength();

            final TransferProgressListener tpl = new TransferProgressListener() {

                @Override
                public void publish(long bytes) {
                    listener.onTransferProgress(castMediaUri, bytes, max);

                }
            };

            final InputStreamWatcher is = new InputStreamWatcher(ent.getContent(), tpl);

            try {
                if (DEBUG) {
                    Log.d(TAG, "Downloading " + pubUri + " and saving it in " + saveFile.getAbsolutePath());
                }
                final FileOutputStream fos = new FileOutputStream(saveFile);
                StreamUtils.inputStreamToOutputStream(is, fos);
                fos.close();

                // set the file's last modified to match the remote.
                // We can check this later to see if everything is up to
                // date.
                final Header lastModified = res.getFirstHeader("last-modified");
                if (lastModified != null) {
                    saveFile.setLastModified(DateUtils.parseDate(lastModified.getValue()).getTime());
                }

            } finally {
                listener.onTransferComplete(castMediaUri);
                ent.consumeContent();
                is.close();
            }

            // XXX avoid this to prevent adding to local collection
            // final String filePath = saveFile.getAbsolutePath();

            // scanMediaItem(castMediaUri, filePath, contentType);
            return true;
        }
    } catch (final Exception e) {
        final SyncException se = new SyncException("Error downloading content item.");
        se.initCause(e);
        throw se;
    }
    return false;
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

/**
 * Upload a file for a particular field in a particular record. If a file
 * with the same name already exists, rename the old one to avoid
 * overwriting. Reset the last modified time of the old one so the rename
 * doesn't muck this up. Maintaining the file timestamp is useful for
 * version history/*from ww w . jav a2  s . c  om*/
 */
private void uploadFile(HttpServletRequest request, FileField field, FileValue fileValue, int rowId,
        List<FileItem> multipartItems) throws CantDoThatException, FileUploadException {
    if (rowId < 0) {
        throw new CantDoThatException("Row ID " + rowId + " invalid");
    }
    if (!FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        throw new CantDoThatException("To upload a file, the form must be posted as multi-part form data");
    }
    if (fileValue.toString().contains("/")) {
        throw new CantDoThatException(
                "Filename contains a slash character which is not allowed, no upload done");
    }
    if (fileValue.toString().contains("'") || fileValue.toString().contains("\"")) {
        throw new CantDoThatException("Filename must not contain quote marks");
    }
    // Put the file in a unique folder per row ID.
    // This is in the format table ID / field ID / row ID
    String uploadFolderName = this.getWebAppRoot() + "uploads/"
            + field.getTableContainingField().getInternalTableName() + "/" + field.getInternalFieldName() + "/"
            + rowId;
    File uploadFolder = new File(uploadFolderName);
    if (!uploadFolder.exists()) {
        if (!uploadFolder.mkdirs()) {
            throw new CantDoThatException("Error creating upload folder " + uploadFolderName);
        }
    }
    for (FileItem item : multipartItems) {
        // if item is a file
        if (!item.isFormField()) {
            long fileSize = item.getSize();
            if (fileSize == 0) {
                throw new CantDoThatException("An empty file was submitted, no upload done");
            }
            String filePath = uploadFolderName + "/" + fileValue.toString();
            File selectedFile = new File(filePath);
            String extension = "";
            if (filePath.contains(".")) {
                extension = filePath.replaceAll("^.*\\.", "").toLowerCase();
            }
            if (selectedFile.exists()) {
                // rename the existing file to something else so we don't
                // overwrite it
                String basePath = filePath;
                int fileNum = 1;
                if (basePath.contains(".")) {
                    basePath = basePath.substring(0, basePath.length() - extension.length() - 1);
                }
                String renamedFileName = basePath + "-" + fileNum;
                if (!extension.equals("")) {
                    renamedFileName += "." + extension;
                }
                File renamedFile = new File(renamedFileName);
                while (renamedFile.exists()) {
                    fileNum++;
                    renamedFileName = basePath + "-" + fileNum;
                    if (!extension.equals("")) {
                        renamedFileName += "." + extension;
                    }
                    renamedFile = new File(renamedFileName);
                }
                // Keep the original timestamp
                long lastModified = selectedFile.lastModified();
                if (!selectedFile.renameTo(renamedFile)) {
                    throw new FileUploadException("Rename of existing file from '" + selectedFile + "' to '"
                            + renamedFile + "' failed");
                }
                if (!renamedFile.setLastModified(lastModified)) {
                    throw new FileUploadException("Error setting the last modified date of " + renamedFile);
                }
                // I think a File object's name is inviolable but just in
                // case
                selectedFile = new File(filePath);
            }
            try {
                item.write(selectedFile);
            } catch (Exception ex) {
                // Catching a general exception?! This is because the
                // library throws a raw exception. Not very good
                throw new FileUploadException("Error writing file: " + ex.getMessage());
            }
            // Record upload speed
            long requestStartTime = request.getSession().getLastAccessedTime();
            float secondsToUpload = (System.currentTimeMillis() - requestStartTime) / ((float) 1000);
            if (secondsToUpload > 10) {
                // Only time reasonably long uploads otherwise we'll amplify
                // errors
                float uploadSpeed = ((float) fileSize) / secondsToUpload;
                this.updateUploadSpeed(uploadSpeed);
            }
            if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png")) {
                // image.png -> image.png.40.png
                String thumb40Path = filePath + "." + 40 + "." + extension;
                String thumb500Path = filePath + "." + 500 + "." + extension;
                File thumb40File = new File(thumb40Path);
                File thumb500File = new File(thumb500Path);
                int midSize = 500;
                if (field.getAttachmentType().equals(AttachmentType.PROFILE_PHOTO)) {
                    midSize = 250;
                }
                try {
                    BufferedImage originalImage = ImageIO.read(selectedFile);
                    int height = originalImage.getHeight();
                    int width = originalImage.getWidth();
                    // Conditional resize
                    if ((height > midSize) || (width > midSize)) {
                        Thumbnails.of(selectedFile).size(midSize, midSize).toFile(thumb500File);
                    } else {
                        FileUtils.copyFile(selectedFile, thumb500File);
                    }
                    // Allow files that are up to 60 px tall as long as the
                    // width is no > 40 px
                    Thumbnails.of(selectedFile).size(40, 60).toFile(thumb40File);
                } catch (IOException ioex) {
                    throw new FileUploadException("Error generating thumbnail: " + ioex.getMessage());
                }
            } else if (extension.equals("pdf")) {
                // Convert first page to PNG with imagemagick
                ConvertCmd convert = new ConvertCmd();
                IMOperation op = new IMOperation();
                op.addImage(); // Placeholder for input PDF
                op.resize(500, 500);
                op.addImage(); // Placeholder for output PNG
                try {
                    // [0] means convert only first page
                    convert.run(op, new Object[] { filePath + "[0]", filePath + "." + 500 + ".png" });
                } catch (IOException ioex) {
                    throw new FileUploadException("IO error while converting PDF to PNG: " + ioex);
                } catch (InterruptedException iex) {
                    throw new FileUploadException("Interrupted while converting PDF to PNG: " + iex);
                } catch (IM4JavaException im4jex) {
                    throw new FileUploadException("Problem converting PDF to PNG: " + im4jex);
                }
            }
        }
    }
}