Example usage for java.nio.file Path getFileName

List of usage examples for java.nio.file Path getFileName

Introduction

In this page you can find the example usage for java.nio.file Path getFileName.

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by this path as a Path object.

Usage

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {//from   ww w. j  a  v  a2  s . co  m
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:dotaSoundEditor.Controls.ItemPanel.java

@Override
protected File promptUserForNewFile(String wavePath) {
    DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
    String waveString = selectedTreeNode.getUserObject().toString();
    String allowedExtension = FilenameUtils.getExtension(waveString).replace("\"", "");

    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = allowedExtension.equals("wav") ? new FileNameExtensionFilter("WAVs", "wav")
            : new FileNameExtensionFilter("MP3s", "mp3");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);/*  w w  w . j a  v  a 2  s. co m*/
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());

        int startIndex = -1;
        int endIndex = -1;
        //Get the actual value for the wavestring key-value pair.
        if (waveString.contains("\"wave\"")) {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 2);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 3);
        } else //Some wavestrings don't have the "wave" at the beginning for some reason
        {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 0);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 1);
        }
        String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
        String waveStringNormalizedFilePath = waveStringFilePath.substring(0,
                waveStringFilePath.lastIndexOf("\""));
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace(")", "");
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace("\"", "");

        Path destPath = Paths.get(installDir, "/dota/sound/" + waveStringNormalizedFilePath);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            if (waveString.contains("//")) {
                waveString = waveString
                        .replace(waveString.substring(waveString.indexOf("//"), waveString.length()), "");
            }
            waveString = waveString.replace(waveStringFilePath, "\"" + waveStringNormalizedFilePath
                    + "\" //Replaced by: " + chosenFile.getFileName().toString());
            selectedTreeNode.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:com.hpe.caf.worker.testing.validation.ReferenceDataValidator.java

@Override
public boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) {

    if (testedPropertyValue == null && validatorPropertyValue == null)
        return true;

    ObjectMapper mapper = new ObjectMapper();

    ContentFileTestExpectation expectation = mapper.convertValue(validatorPropertyValue,
            ContentFileTestExpectation.class);

    ReferencedData referencedData = mapper.convertValue(testedPropertyValue, ReferencedData.class);

    InputStream dataStream;/*from   www.ja  v  a2 s . c om*/

    if (expectation.getExpectedContentFile() == null && expectation.getExpectedSimilarityPercentage() == 0) {
        return true;
    }

    try {
        System.out.println("About to retrieve content for " + referencedData.toString());
        dataStream = ContentDataHelper.retrieveReferencedData(dataStore, codec, referencedData);
        System.out.println("Finished retrieving content for " + referencedData.toString());
    } catch (DataSourceException e) {
        e.printStackTrace();
        System.err.println("Failed to acquire referenced data.");
        e.printStackTrace();
        TestResultHelper.testFailed("Failed to acquire referenced data. Exception message: " + e.getMessage(),
                e);
        return false;
    }
    try {
        String contentFileName = expectation.getExpectedContentFile();
        Path contentFile = Paths.get(contentFileName);
        if (Files.notExists(contentFile) && !Strings.isNullOrEmpty(testSourcefileBaseFolder)) {
            contentFile = Paths.get(testSourcefileBaseFolder, contentFileName);
        }

        if (Files.notExists(contentFile)) {
            contentFile = Paths.get(testDataFolder, contentFileName);
        }

        byte[] expectedFileBytes = Files.readAllBytes(contentFile);

        if (expectation.getComparisonType() == ContentComparisonType.TEXT) {

            String actualText = IOUtils.toString(dataStream, StandardCharsets.UTF_8);
            String expectedText = new String(expectedFileBytes, StandardCharsets.UTF_8);

            if (expectation.getExpectedSimilarityPercentage() == 100) {
                boolean equals = actualText.equals(expectedText);
                if (!equals) {
                    String message = "Expected and actual texts were different.\n\n*** Expected Text ***\n"
                            + expectedText + "\n\n*** Actual Text ***\n" + actualText;
                    System.err.println(message);
                    if (throwOnValidationFailure)
                        TestResultHelper.testFailed(message);
                    return false;
                }
                return true;
            }

            double similarity = ContentComparer.calculateSimilarityPercentage(expectedText, actualText);

            System.out.println("Compared text similarity:" + similarity + "%");

            if (similarity < expectation.getExpectedSimilarityPercentage()) {
                String message = "Expected similarity of " + expectation.getExpectedSimilarityPercentage()
                        + "% but actual similarity was " + similarity + "%";
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        } else {
            byte[] actualDataBytes = IOUtils.toByteArray(dataStream);
            boolean equals = Arrays.equals(actualDataBytes, expectedFileBytes);
            if (!equals) {
                String actualContentFileName = contentFile.getFileName() + "_actual";
                Path actualFilePath = Paths.get(contentFile.getParent().toString(), actualContentFileName);
                Files.deleteIfExists(actualFilePath);
                Files.write(actualFilePath, actualDataBytes, StandardOpenOption.CREATE);
                String message = "Data returned was different than expected for file: " + contentFileName
                        + "\nActual content saved in file: " + actualFilePath.toString();
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        TestResultHelper.testFailed("Error while processing reference data! " + e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:gov.noaa.pfel.coastwatch.util.FileVisitorDNLS.java

/** Invoked for a file in a directory. */
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

    int oSize = directoryPA.size();
    try {// www . j a va2  s.  com
        String name = file.getFileName().toString();
        if (!fileNamePattern.matcher(name).matches()) {
            if (debugMode)
                String2.log(">> fileName doesn't match: name=" + name + " regex=" + fileNameRegex);
            return FileVisitResult.CONTINUE;
        }

        //getParent returns \\ or /, without trailing /
        String ttDir = String2.replaceAll(file.getParent().toString(), fromSlash, toSlash) + toSlash;
        if (debugMode)
            String2.log(">> add fileName: " + ttDir + name);
        directoryPA.add(ttDir);
        namePA.add(name);
        lastModifiedPA.add(attrs.lastModifiedTime().toMillis());
        sizePA.add(attrs.size());
        //for debugging only:
        //String2.log(ttDir + name + 
        //    " mod=" + attrs.lastModifiedTime().toMillis() +
        //    " size=" + attrs.size());
    } catch (Throwable t) {
        if (directoryPA.size() > oSize)
            directoryPA.remove(oSize);
        if (namePA.size() > oSize)
            namePA.remove(oSize);
        if (lastModifiedPA.size() > oSize)
            lastModifiedPA.remove(oSize);
        if (sizePA.size() > oSize)
            sizePA.remove(oSize);
        String2.log(MustBe.throwableToString(t));
    }

    return FileVisitResult.CONTINUE;
}

From source file:de.decoit.visa.rdf.RDFManager.java

/**
 * Create a JSON object which contains a list of all imported RDF/XML source
 * files//from w  w w.j  a  v  a  2 s  . c  o m
 *
 * @return JSON object with import history
 * @throws JSONException
 */
public JSONObject historyToJSON() throws JSONException {
    JSONObject rv = new JSONObject();

    int i = 0;
    for (Path f : source) {
        rv.put(String.valueOf(i), f.getFileName().toString());
        i++;
    }

    return rv;
}

From source file:de.decoit.visa.rdf.RDFManager.java

/**
 * Delete all uploaded RDF/XML source files and the corresponding named
 * models/* ww  w. java  2 s .  c  o  m*/
 *
 * @throws IOException
 */
private void clearSourceFiles() throws IOException {
    if (source.size() > 0) {
        // Delete all uploaded files (if any) and clear the source file list
        for (Path f : source) {
            Files.delete(f);

            // Remove the named model the contains the information in this
            // file
            ds.removeNamedModel(VISA.createModelURI(f.getFileName().toString()));
        }

        source.clear();
    }
}

From source file:de.decoit.visa.rdf.RDFManager.java

/**
 * Load a RDF/XML file into a named model. The file will be read from the
 * specified location. It can be specified if the existing model will be
 * replaced or the new data will be appended to the current model.
 *
 * @param pFile Path and file name of the source file
 * @param pReplace Specify if the new data will replace the existing model
 *            or if it will be appended to the model
 * @throws IOException//  w  ww . j av a2 s  .c o  m
 * @throws RDFSourceException
 */
public void loadRDF(Path pFile, boolean pReplace) throws IOException, RDFSourceException {
    InputStream is = Files.newInputStream(pFile);

    if (pReplace) {
        source = new ArrayList<>();
        source.add(pFile);
    } else {
        source.add(pFile);
    }

    loadRDF(is, pReplace, pFile.getFileName().toString());
}

From source file:com.github.podd.example.ExamplePoddClient.java

public Map<Path, String> uploadToStorage(final List<Path> bagsToUpload, final String sshServerFingerprint,
        final String sshHost, final int portNo, final String username, final Path pathToPublicKey,
        final Path localRootPath, final Path remoteRootPath, final PasswordFinder keyExtractor)
        throws PoddClientException, NoSuchAlgorithmException, IOException {
    final Map<Path, String> results = new ConcurrentHashMap<>();

    final ConcurrentMap<Path, ConcurrentMap<PoddDigestUtils.Algorithm, String>> digests = PoddDigestUtils
            .getDigests(bagsToUpload);/*from  w ww .jav a2  s .c om*/

    try (SSHClient sshClient = new SSHClient(ExamplePoddClient.DEFAULT_CONFIG);) {
        sshClient.useCompression();
        sshClient.addHostKeyVerifier(sshServerFingerprint);
        sshClient.connect(sshHost, portNo);
        if (!Files.exists(pathToPublicKey)) {
            throw new PoddClientException("Could not find public key: " + pathToPublicKey);
        }
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            throw new PoddClientException("Bouncy castle needed");
        }
        final FileKeyProvider rsa = new PKCS8KeyFile();
        rsa.init(pathToPublicKey.toFile(), keyExtractor);
        sshClient.authPublickey(username, rsa);
        // Session session = sshClient.startSession();
        try (SFTPClient sftp = sshClient.newSFTPClient();) {
            for (final Path nextBag : bagsToUpload) {
                // Check to make sure that the bag was under the local root path
                final Path localPath = nextBag.toAbsolutePath();
                if (!localPath.startsWith(localRootPath)) {
                    this.log.error(
                            "Local bag path was not a direct descendant of the local root path: {} {} {}",
                            localRootPath, nextBag, localPath);
                    throw new PoddClientException(
                            "Local bag path was not a direct descendant of the local root path: " + localPath
                                    + " " + localRootPath);
                }

                // Take the local root path out to get the subpath to use on the remote
                final Path remoteSubPath = localPath.subpath(localRootPath.getNameCount(),
                        nextBag.getNameCount() - 1);

                this.log.info("Remote sub path: {}", remoteSubPath);

                final Path remoteDirPath = remoteRootPath.resolve(remoteSubPath);
                this.log.info("Remote dir path: {}", remoteDirPath);

                final Path remoteBagPath = remoteDirPath.resolve(nextBag.getFileName());

                this.log.info("Remote bag path: {}", remoteBagPath);

                boolean fileFound = false;
                boolean sizeCorrect = false;
                try {
                    // check details of a remote bag
                    final FileAttributes attribs = sftp.lstat(remoteBagPath.toAbsolutePath().toString());
                    final long localSize = Files.size(nextBag);
                    final long remoteSize = attribs.getSize();

                    if (localSize <= 0) {
                        this.log.error("Local bag was empty: {}", nextBag);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (remoteSize <= 0) {
                        this.log.warn("Remote bag was empty: {} {}", nextBag, attribs);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (localSize == remoteSize) {
                        this.log.info("Found file on remote already with same size as local: {} {}", nextBag,
                                remoteBagPath);
                        sizeCorrect = true;
                        fileFound = true;
                    } else {
                        sizeCorrect = false;
                        fileFound = true;
                        // We always assume that a non-zero local file is correct
                        // The bags contain time-stamps that will be modified when they are
                        // regenerated, likely changing the file-size, and hopefully changing
                        // the digest checksums
                        // throw new PoddClientException(
                        // "Could not automatically compare file sizes (need manual intervention to delete one) : "
                        // + nextBag + " " + remoteBagPath + " localSize=" + localSize
                        // + " remoteSize=" + remoteSize);
                    }
                } catch (final IOException e) {
                    // lstat() throws an IOException if the file does not exist
                    // Ignore
                    sizeCorrect = false;
                    fileFound = false;
                }

                final ConcurrentMap<Algorithm, String> bagDigests = digests.get(nextBag);
                if (bagDigests.isEmpty()) {
                    this.log.error("No bag digests were generated for bag: {}", nextBag);
                }
                for (final Entry<Algorithm, String> entry : bagDigests.entrySet()) {
                    final Path localDigestPath = localPath
                            .resolveSibling(localPath.getFileName() + entry.getKey().getExtension());
                    // Create the local digest file
                    Files.copy(
                            new ReaderInputStream(new StringReader(entry.getValue()), StandardCharsets.UTF_8),
                            localDigestPath);
                    final Path remoteDigestPath = remoteBagPath
                            .resolveSibling(remoteBagPath.getFileName() + entry.getKey().getExtension());
                    boolean nextDigestFileFound = false;
                    boolean nextDigestCorrect = false;
                    try {
                        final Path tempFile = Files.createTempFile("podd-digest-",
                                entry.getKey().getExtension());
                        final SFTPFileTransfer sftpFileTransfer = new SFTPFileTransfer(sftp.getSFTPEngine());
                        sftpFileTransfer.download(remoteBagPath.toAbsolutePath().toString(),
                                tempFile.toAbsolutePath().toString());
                        nextDigestFileFound = true;

                        final List<String> allLines = Files.readAllLines(tempFile, StandardCharsets.UTF_8);
                        if (allLines.isEmpty()) {
                            nextDigestCorrect = false;
                        } else if (allLines.size() > 1) {
                            nextDigestCorrect = false;
                        }
                        // Check if the digests match exactly
                        else if (allLines.get(0).equals(entry.getValue())) {
                            nextDigestCorrect = true;
                        } else {
                            nextDigestCorrect = false;
                        }
                    } catch (final IOException e) {
                        nextDigestFileFound = false;
                        nextDigestCorrect = false;
                    }
                    if (nextDigestFileFound && nextDigestCorrect) {
                        this.log.info(
                                "Not copying digest to remote as it exists and contains the same content as the local digest");
                    } else if (nextDigestFileFound && !nextDigestCorrect) {
                        this.log.error("Found remote digest but content was not correct: {} {}",
                                localDigestPath, remoteDigestPath);
                        sftp.rm(remoteDigestPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    } else if (!nextDigestFileFound) {
                        this.log.info("About to make directories on remote: {}", remoteDirPath);
                        sftp.mkdirs(remoteDirPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    }
                }

                if (fileFound && sizeCorrect) {
                    this.log.info("Not copying bag to remote as it exists and is the same size as local bag");
                } else if (fileFound && !sizeCorrect) {
                    this.log.error("Found remote bag but size was not correct: {} {}", nextBag, remoteBagPath);
                    sftp.rm(remoteBagPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                } else if (!fileFound) {
                    this.log.info("About to make directories on remote: {}", remoteDirPath);
                    sftp.mkdirs(remoteDirPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                }

            }
        }
    } catch (final IOException e) {
        throw new PoddClientException("Could not copy a bag to the remote location", e);
    }

    return results;
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * #2526//from ww  w.j a v  a 2s.co  m
 */
private void backupConfigAssets() {
    Path backupDir = getMiscFilesLocation().resolve("backups/" + Format.formatDateCanonical(new Date()));
    if (Files.notExists(backupDir)) {
        try {
            Files.createDirectories(backupDir);
        } catch (IOException ioe) {
            logInfo("Could not create directory '" + backupDir.toAbsolutePath().toString() + "'");
        }
    }
    Path configBackup = backupDir.resolve(configFile.getFileName());
    try {
        PathUtils.copyFile(configFile, configBackup);
    } catch (IOException e) {
        logWarning("Unable to backup file " + configFile + ". " + e);
    }
    if (Files.exists(configFolderFile)) {
        Path configFolderBackup = backupDir.resolve(configFolderFile.getFileName());
        try {
            PathUtils.copyFile(configFolderFile, configFolderBackup);
        } catch (IOException e) {
            logWarning("Unable to backup file " + configFolderFile + ". " + e);
        }
    }
    Path myKeyFile = getMiscFilesLocation().resolve(getConfigName() + ".mykey");
    Path mykeyBackup = backupDir.resolve(myKeyFile.getFileName());
    if (Files.exists(myKeyFile)) {
        try {
            PathUtils.copyFile(myKeyFile, mykeyBackup);
        } catch (IOException e) {
            logWarning("Unable to backup file " + myKeyFile + ". " + e);
        }
    }
    Path dbFile = getMiscFilesLocation().resolve("Accounts.h2.db");
    Path dbBackup = backupDir.resolve(dbFile.getFileName());
    if (Files.exists(dbFile)) {
        try {
            PathUtils.copyFile(dbFile, dbBackup);
        } catch (IOException e) {
            logWarning("Unable to backup file " + dbFile + ". " + e);
        }
    }
}

From source file:com.liferay.sync.engine.file.system.SyncWatchEventProcessor.java

protected void addFile(SyncWatchEvent syncWatchEvent) throws Exception {
    final Path targetFilePath = Paths.get(syncWatchEvent.getFilePathName());

    if (FileUtil.notExists(targetFilePath) || sanitizeFileName(targetFilePath)
            || isInErrorState(targetFilePath)) {

        return;// w  ww . jav a2  s . c o  m
    }

    Path parentTargetFilePath = targetFilePath.getParent();

    final SyncFile parentSyncFile = SyncFileService.fetchSyncFile(parentTargetFilePath.toString());

    if ((parentSyncFile == null) || (!parentSyncFile.isSystem() && (parentSyncFile.getTypePK() == 0))) {

        queueSyncWatchEvent(parentTargetFilePath.toString(), syncWatchEvent);

        return;
    }

    SyncFile syncFile = SyncFileService.fetchSyncFile(targetFilePath.toString());

    if (syncFile == null) {
        syncFile = SyncFileService.fetchSyncFile(FileKeyUtil.getFileKey(targetFilePath));

        if (!verifySite(syncFile, parentSyncFile)) {
            syncFile = null;
        }
    }

    if (syncFile == null) {
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    SyncSite syncSite = SyncSiteService.fetchSyncSite(parentSyncFile.getRepositoryId(),
                            _syncAccountId);

                    if ((syncSite == null) || !syncSite.isActive() || !FileUtil.checkFilePath(targetFilePath)) {

                        return;
                    }

                    SyncFileService.addFileSyncFile(targetFilePath, parentSyncFile.getTypePK(),
                            parentSyncFile.getRepositoryId(), _syncAccountId);
                } catch (Exception e) {
                    if (SyncFileService.fetchSyncFile(targetFilePath.toString()) == null) {

                        _logger.error(e.getMessage(), e);
                    }
                }
            }

        };

        _executorService.execute(runnable);

        return;
    }

    Path sourceFilePath = Paths.get(syncFile.getFilePathName());

    if (targetFilePath.equals(sourceFilePath)) {
        if (isPendingTypePK(syncFile) || (syncFile.getState() == SyncFile.STATE_IN_PROGRESS)) {

            queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent);

            return;
        }

        if (FileUtil.isModified(syncFile)) {
            SyncFileService.updateFileSyncFile(targetFilePath, _syncAccountId, syncFile);
        }
    } else if (FileUtil.exists(sourceFilePath)) {
        try {
            if ((Files.size(targetFilePath) == 0) || FileUtil.isModified(syncFile, targetFilePath)
                    || isInErrorState(sourceFilePath)) {

                SyncFileService.addFileSyncFile(targetFilePath, parentSyncFile.getTypePK(),
                        parentSyncFile.getRepositoryId(), _syncAccountId);
            } else {
                SyncFileService.copySyncFile(syncFile, targetFilePath, parentSyncFile.getTypePK(),
                        parentSyncFile.getRepositoryId(), _syncAccountId);
            }
        } catch (Exception e) {
            if (SyncFileService.fetchSyncFile(targetFilePath.toString()) == null) {

                _logger.error(e.getMessage(), e);
            }
        }

        return;
    } else if (parentTargetFilePath.equals(sourceFilePath.getParent())) {
        if (isPendingTypePK(syncFile) || (syncFile.getState() == SyncFile.STATE_IN_PROGRESS)) {

            queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent);

            return;
        }

        SyncFileService.updateFileSyncFile(targetFilePath, _syncAccountId, syncFile);
    } else {
        if (isPendingTypePK(syncFile) || (syncFile.getState() == SyncFile.STATE_IN_PROGRESS)) {

            queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent);

            return;
        }

        SyncFileService.moveFileSyncFile(targetFilePath, parentSyncFile.getTypePK(), _syncAccountId, syncFile);

        Path sourceFileNameFilePath = sourceFilePath.getFileName();

        if (!sourceFileNameFilePath.equals(targetFilePath.getFileName())) {
            SyncFileService.updateFileSyncFile(targetFilePath, _syncAccountId, syncFile);
        }
    }

    SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(_syncAccountId);

    if (syncAccount.getState() == SyncAccount.STATE_CONNECTED) {
        SyncWatchEvent relatedSyncWatchEvent = SyncWatchEventService.fetchSyncWatchEvent(
                SyncWatchEvent.EVENT_TYPE_DELETE, syncWatchEvent.getFilePathName(),
                syncWatchEvent.getTimestamp());

        if (relatedSyncWatchEvent != null) {
            _processedSyncWatchEventIds.add(relatedSyncWatchEvent.getSyncWatchEventId());
        }
    }
}