Example usage for java.io File equals

List of usage examples for java.io File equals

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

Tests this abstract pathname for equality with the given object.

Usage

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) {
    try {/*from www. j  a v a 2  s . c o  m*/
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        downloadFile.updateModificationDate();
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(file.getPath());
        setPlayerState(PREPARING);
        mediaPlayer.prepare();
        setPlayerState(PREPARED);

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

                // Acquire a temporary wakelock, since when we return from
                // this callback the MediaPlayer will release its wakelock
                // and allow the device to go to sleep.
                wakeLock.acquire(60000);

                setPlayerState(COMPLETED);

                // If COMPLETED and not playing partial file, we are *really" finished
                // with the song and can move on to the next.
                if (!file.equals(downloadFile.getPartialFile())) {
                    onSongCompleted();
                    return;
                }

                // If file is not completely downloaded, restart the playback from the current position.
                int pos = mediaPlayer.getCurrentPosition();
                synchronized (DownloadServiceImpl.this) {

                    // Work-around for apparent bug on certain phones: If close (less than ten seconds) to the end
                    // of the song, skip to the next rather than restarting it.
                    Integer duration = downloadFile.getSong().getDuration() == null ? null
                            : downloadFile.getSong().getDuration() * 1000;
                    if (duration != null) {
                        if (Math.abs(duration - pos) < 10000) {
                            LOG.info("Skipping restart from " + pos + " of " + duration);
                            onSongCompleted();
                            return;
                        }
                    }

                    LOG.info("Requesting restart from " + pos + " of " + duration);
                    reset();
                    bufferTask = new BufferTask(downloadFile, pos);
                    bufferTask.start();
                }
            }
        });

        if (position != 0) {
            LOG.info("Restarting player from position " + position);
            mediaPlayer.seekTo(position);
        }

        if (start) {
            mediaPlayer.start();
            setPlayerState(STARTED);
        } else {
            setPlayerState(PAUSED);
        }
        lifecycleSupport.serializeDownloadQueue();

    } catch (Exception x) {
        handleError(x);
    }
}

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java

public final EclipseSourceDir[] buildDirectoryList(MavenProject project, File basedir,
        File buildOutputDirectory) throws MojoExecutionException {
    File projectBaseDir = project.getFile().getParentFile();

    String mainOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir, buildOutputDirectory, false);

    // If using the standard output location, don't mix the test output into it.
    String testOutput = null;/*from w ww. j a v  a 2s.  c  o m*/
    boolean useStandardOutputDir = buildOutputDirectory
            .equals(new File(project.getBuild().getOutputDirectory()));
    if (useStandardOutputDir) {
        getLog().debug("testOutput toRelativeAndFixSeparator " + projectBaseDir + " , "
                + project.getBuild().getTestOutputDirectory());
        testOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir,
                new File(project.getBuild().getTestOutputDirectory()), false);
        getLog().debug("testOutput after toRelative : " + testOutput);
    }

    Set mainDirectories = new LinkedHashSet();

    extractSourceDirs(mainDirectories, project.getCompileSourceRoots(), basedir, projectBaseDir, false, null);

    extractResourceDirs(mainDirectories, project.getBuild().getResources(), basedir, projectBaseDir, false,
            mainOutput);

    Set testDirectories = new LinkedHashSet();

    extractSourceDirs(testDirectories, project.getTestCompileSourceRoots(), basedir, projectBaseDir, true,
            testOutput);

    extractResourceDirs(testDirectories, project.getBuild().getTestResources(), basedir, projectBaseDir, true,
            testOutput);

    // avoid duplicated entries
    Set directories = new LinkedHashSet();

    // NOTE: Since MNG-3118, test classes come before main classes
    boolean testBeforeMain = isMavenVersion("[2.0.8,)");

    // let users override this if needed, they need to simulate more than the test phase in eclipse
    if (testSourcesLast) {
        testBeforeMain = false;
    }

    if (testBeforeMain) {
        directories.addAll(testDirectories);
        directories.removeAll(mainDirectories);
        directories.addAll(mainDirectories);
    } else {
        directories.addAll(mainDirectories);
        directories.addAll(testDirectories);
    }
    if (ajdt) {
        extractAspectDirs(directories, project, basedir, projectBaseDir, testOutput);
    }
    return (EclipseSourceDir[]) directories.toArray(new EclipseSourceDir[directories.size()]);
}

From source file:org.lockss.protocol.BlockingStreamComm.java

/**
 * Set communication parameters from configuration, once only.
 * Some aspects of this service currently cannot be reconfigured.
 * @param config the Configuration/* w w w  .j  a v  a2s  .  c  om*/
 */
public void setConfig(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) {
    // Instances of this manager are started incrementally in testing,
    // after the daemon is running, so isDaemonInited() won't work here
    if (isInited()) {
        // one-time only init
        if (configShot.once()) {
            configure(config, prevConfig, changedKeys);
        }
        // the following params can be changed on the fly
        if (changedKeys.contains(PREFIX)) {
            if (enabled && isRunning() && !config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED)) {
                stopService();
            }

            paramMinFileMessageSize = config.getInt(PARAM_MIN_FILE_MESSAGE_SIZE, DEFAULT_MIN_FILE_MESSAGE_SIZE);
            paramMaxMessageSize = config.getLong(PARAM_MAX_MESSAGE_SIZE, DEFAULT_MAX_MESSAGE_SIZE);
            paramMinMeasuredMessageSize = config.getLong(PARAM_MIN_MEASURED_MESSAGE_SIZE,
                    DEFAULT_MIN_MEASURED_MESSAGE_SIZE);
            paramIsBufferedSend = config.getBoolean(PARAM_IS_BUFFERED_SEND, DEFAULT_IS_BUFFERED_SEND);
            paramIsTcpNoDelay = config.getBoolean(PARAM_TCP_NODELAY, DEFAULT_TCP_NODELAY);
            paramWaitExit = config.getTimeInterval(PARAM_WAIT_EXIT, DEFAULT_WAIT_EXIT);
            String paramDataDir = config.get(PARAM_DATA_DIR, PlatformUtil.getSystemTempDir());
            File dir = new File(paramDataDir);
            if (FileUtil.ensureDirExists(dir)) {
                if (!dir.equals(dataDir)) {
                    dataDir = dir;
                    log.debug2("Message data dir: " + dataDir);
                }
            } else {
                log.warning("No message data dir: " + dir);
                dataDir = null;
            }

            paramMaxChannels = config.getInt(PARAM_MAX_CHANNELS, DEFAULT_MAX_CHANNELS);
            paramConnectTimeout = config.getTimeInterval(PARAM_CONNECT_TIMEOUT, DEFAULT_CONNECT_TIMEOUT);
            paramSoTimeout = config.getTimeInterval(PARAM_DATA_TIMEOUT, DEFAULT_DATA_TIMEOUT);
            paramSslHandshakeTimeout = config.getTimeInterval(PARAM_SSL_HANDSHAKE_TIMEOUT,
                    DEFAULT_SSL_HANDSHAKE_TIMEOUT);
            paramDisableSslServerProtocols = config.getList(PARAM_DISABLE_SSL_SERVER_PROTOCOLS,
                    DEFAULT_DISABLE_SSL_SERVER_PROTOCOLS);
            paramDisableSslClientProtocols = config.getList(PARAM_DISABLE_SSL_CLIENT_PROTOCOLS,
                    DEFAULT_DISABLE_SSL_CLIENT_PROTOCOLS);
            paramSoKeepAlive = config.getBoolean(PARAM_SOCKET_KEEPALIVE, DEFAULT_SOCKET_KEEPALIVE);
            paramSendWakeupTime = config.getTimeInterval(PARAM_SEND_WAKEUP_TIME, DEFAULT_SEND_WAKEUP_TIME);

            paramChannelIdleTime = config.getTimeInterval(PARAM_CHANNEL_IDLE_TIME, DEFAULT_CHANNEL_IDLE_TIME);
            paramDrainInputTime = config.getTimeInterval(PARAM_DRAIN_INPUT_TIME, DEFAULT_DRAIN_INPUT_TIME);
            paramDissociateOnNoSend = config.getBoolean(PARAM_DISSOCIATE_ON_NO_SEND,
                    DEFAULT_DISSOCIATE_ON_NO_SEND);
            paramDissociateOnEveryStop = config.getBoolean(PARAM_DISSOCIATE_ON_EVERY_STOP,
                    DEFAULT_DISSOCIATE_ON_EVERY_STOP);

            paramRetryBeforeExpiration = config.getTimeInterval(PARAM_RETRY_BEFORE_EXPIRATION,
                    DEFAULT_RETRY_BEFORE_EXPIRATION);

            paramMaxPeerRetryInterval = config.getTimeInterval(PARAM_MAX_PEER_RETRY_INTERVAL,
                    DEFAULT_MAX_PEER_RETRY_INTERVAL);
            paramMinPeerRetryInterval = config.getTimeInterval(PARAM_MIN_PEER_RETRY_INTERVAL,
                    DEFAULT_MIN_PEER_RETRY_INTERVAL);
            paramRetryDelay = config.getTimeInterval(PARAM_RETRY_DELAY, DEFAULT_RETRY_DELAY);

            paramAbortOnUnknownOp = config.getBoolean(PARAM_ABORT_ON_UNKNOWN_OP, DEFAULT_ABORT_ON_UNKNOWN_OP);
            if (changedKeys.contains(PARAM_PEER_SEND_MESSAGE_RATE_LIMIT)) {
                sendRateLimiters.resetRateLimiters(config);
            }
            if (changedKeys.contains(PARAM_PEER_RECEIVE_MESSAGE_RATE_LIMIT)) {
                receiveRateLimiters.resetRateLimiters(config);
            }
        }
    }
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * Main thread simply looks for notification that the
 * test is complete, informs the various protocol stacks
 * to shutdown and then terminates the test.
 *
 *///from  w ww. j a va  2s.c o  m
public void run() {
    mainThread = Thread.currentThread();
    // GAREY test code       int count = 0;
    while (!shutdown) {
        // First determine if there are any tests to conduct
        boolean configsToProcess = false;
        synchronized (dutConfigsToRead) {
            synchronized (dutConfigsToRemove) {
                if (dutConfigsToRead.size() > 0 || dutConfigsToRemove.size() > 0) {
                    configsToProcess = true;
                }
            }
        }

        if (!configsToProcess && closeBatchFile) {
            if (ss != null) {
                ss.closeBatch();

            }
            if (stacks != null) {
                stacks.shutdown();
            }
            closeBatchFile = false;
            platformSettingsFile = null;
            if (globalRegEnabled) {
                globalRegFile = null;
                GlobalRegistrar.setMasterFSM(null, Transport.UDP);
                globalRegEnabled = false;
            }
            if (presenceServerEnabled) {
                presenceServerFile = null;
                presenceServerEnabled = false;
            }
        }
        // Next see if we are ready to run some test pairs
        // This can only be done if there are no dutConfigs to
        // process in add or remove lists
        else if (dutConfigFiles.size() > 0 && testScriptFiles.size() > 0 && !configsToProcess
                && platformSettingsFile != null) {
            try {
                if (dutPrimary) {

                    ListIterator<String> duts = dutConfigFiles.listIterator();
                    while (duts.hasNext() && !shutdown) {
                        activeDUTFile = duts.next();
                        ListIterator<String> testScripts = testScriptFiles.listIterator();
                        while (testScripts.hasNext() && !shutdown) {
                            activeTestScriptFile = testScripts.next();
                            executeTest();
                        }
                    }
                } else {
                    ListIterator<String> testScripts = testScriptFiles.listIterator();
                    while (testScripts.hasNext() && !shutdown) {
                        activeTestScriptFile = testScripts.next();
                        ListIterator<String> duts = dutConfigFiles.listIterator();
                        while (duts.hasNext() && !shutdown) {
                            activeDUTFile = duts.next();
                            executeTest();
                        }
                    }
                }
                testsComplete();
            }
            // This most likely will happen if the user stop's the tests. When the 
            // user terminates the test, the lists are emptied so that no record is made for 
            // unattempted test pairs.
            catch (ConcurrentModificationException cme) {
                logger.debug(PC2LogCategory.PCSim2, subCat,
                        "Either DUT or Test Script list have changed during test pair execution.");
            }
        } else if (pendingPSFile != null) {
            boolean restart = false;
            // Determine if we need to restart the existing stacks and 
            // configuration parameters of the platform.
            if (platformSettingsFile == null)
                restart = true;
            else if (platformSettingsFile != null) {
                // First we need to remove any UEs that are not being simulated from the
                // table of allowable registering devices.
                Enumeration<String> keys = SystemSettings.getPlatformLabels();
                if (keys != null) {
                    while (keys.hasMoreElements()) {
                        String key = keys.nextElement();
                        if (key.startsWith("UE")) {
                            Properties p = SystemSettings.getSettings(key);
                            LinkedList<String> puis = createRegistrarLabels(p);
                            Stacks.removeSIPRegistrarClient(key, puis);
                        }
                    }
                }
                if (!pendingPSFile.equals(platformSettingsFile))
                    restart = true;
                else if (psLastModified < (new File(platformSettingsFile)).lastModified())
                    restart = true;
            }
            if (restart && stacks != null)
                stacks.restart();
            platformSettingsFile = pendingPSFile;
            pendingPSFile = null;
            File ps = new File(platformSettingsFile);
            psLastModified = ps.lastModified();
            if (!ss.loadPlatformSettings(platformSettingsFile)) {
                logger.fatal(PC2LogCategory.Parser, subCat,
                        "PCSim2 encountered error while trying to read the Platform Settings information.");
                // Clear the file information
                platformSettingsFile = null;
            } else {
                Enumeration<String> labels = SystemSettings.getPlatformLabels();
                if (labels != null) {
                    while (labels.hasMoreElements()) {
                        String ne = labels.nextElement();
                        if (!ne.startsWith(SettingConstants.UE) && !ne.startsWith(SettingConstants.PCSCF)
                                && !ne.startsWith(SettingConstants.SCSCF))
                            continue;
                        Properties p = SystemSettings.getSettings(ne);
                        logNE(ne, p);
                    }
                }

                if (restart) {
                    logger.info(PC2LogCategory.PCSim2, subCat, "Starting servers.");
                    startServers();
                }

            }

            // Next reload the provisioning test script/policy/provisioning file table
            if (platformSettingsFile != null) {
                Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
                String cw = platform.getProperty(SettingConstants.CW_NUMBER);
                if (provDB == null)
                    provDB = new ProvDatabase(cw);
                else
                    provDB.load(cw);
            }

            // Now add all of the real devices in the platform settings to the 
            // allowable registering devices table.
            addRegistrarClients();
        }

        else {
            try {
                if (configsToProcess) {
                    synchronized (dutConfigsToRead) {

                        synchronized (dutConfigsToRemove) {
                            if (dutConfigsToRead.size() > 0 || dutConfigsToRemove.size() > 0) {
                                ListIterator<File> rmIter = dutConfigsToRemove.listIterator();
                                // Loop through the reads 
                                File read = null;
                                if (dutConfigsToRead.size() > 0)
                                    read = dutConfigsToRead.removeFirst();
                                while (read != null) {
                                    int prevRmIndex = -1;
                                    // Make sure the read doesn't also appear in the 
                                    // remove list
                                    while (rmIter.hasNext()) {
                                        File rm = rmIter.next();
                                        if (rm.equals(read)) {
                                            prevRmIndex = rmIter.previousIndex();

                                        }
                                    }
                                    // If the file appears in the remove list at the
                                    // same time we try to read, simply don't read
                                    // and remove from the remove list
                                    if (prevRmIndex != -1) {
                                        dutConfigsToRemove.remove(prevRmIndex);
                                        logger.warn(PC2LogCategory.Parser, subCat, "Skipping reading "
                                                + read.getName()
                                                + " because file was also found in DUT Config remove list.");
                                    } else {
                                        try {
                                            // Load the read file
                                            String neLabel = ss.loadDUTSettings(read.getAbsolutePath(), true,
                                                    false);
                                            if (neLabel != null && neLabel.startsWith("UE")) {
                                                // Now obtains the DUT's IP address and the expected IP address for
                                                // it to register with
                                                Properties p = SystemSettings.getSettings(neLabel);
                                                if (p != null) {
                                                    logNE(neLabel, p);

                                                    LinkedList<String> puis = createRegistrarLabels(p);
                                                    if (puis.size() > 0) {
                                                        Stacks.addSIPRegistrarClient(neLabel, puis);
                                                        // With the new design of using Public User Identifier we will need to
                                                        // use the first entry in the puis as the key for the table
                                                        //                                             dutConfigFileToPUIIndex.put(read, puis.get(0));
                                                        if (SystemSettings.getBooleanSetting(
                                                                SettingConstants.GLOBAL_REGISTRAR)) {
                                                            logger.info(PC2LogCategory.Parser, subCat,
                                                                    "Loaded " + read.getName()
                                                                            + " for global registrar.");
                                                        } else
                                                            logger.info(PC2LogCategory.Parser, subCat, read
                                                                    .getName()
                                                                    + " not loaded for global registrar because registrar is disabled.");
                                                    } else {
                                                        logger.error(PC2LogCategory.Parser, subCat,
                                                                "The DUT configuration file appears to not contain any Public User Identitier.");
                                                    }
                                                } else {
                                                    logger.warn(PC2LogCategory.Parser, subCat, "Failed to load "
                                                            + read.getName() + " for global registrar.");
                                                }
                                            } else if (neLabel != null && neLabel.startsWith("CN")) {
                                                // Since the CN could contain the PCSCF that real UEs
                                                // need to register, temporarily load the file's 
                                                // settings, add the clients and then remove them
                                                ss.setDUTProperties(read.getAbsolutePath());
                                                addRegistrarClients();
                                                ss.reset();
                                            } else {
                                                logger.info(PC2LogCategory.Parser, subCat,
                                                        "No elements added for global register for label "
                                                                + neLabel + " from file " + read.getName()
                                                                + ".");
                                            }
                                        } catch (Exception e) {
                                            logger.error(PC2LogCategory.PCSim2, subCat,
                                                    "The DUT Configuration File defined by ("
                                                            + read.getAbsolutePath()
                                                            + ") could not be processed. File is being dropped.");
                                        }
                                    }
                                    read = null;
                                    if (dutConfigsToRead.size() > 0)
                                        read = dutConfigsToRead.removeFirst();
                                }

                                File rm = null;
                                if (dutConfigsToRemove.size() > 0)
                                    rm = dutConfigsToRemove.removeFirst();
                                while (rm != null) {
                                    try {
                                        String neLabel = ss.loadDUTSettings(rm.getAbsolutePath(), true, true);
                                        if (neLabel != null && neLabel.startsWith("UE")) {
                                            Properties p = SystemSettings.getSettings(neLabel);
                                            LinkedList<String> puis = createRegistrarLabels(p);
                                            Stacks.removeSIPRegistrarClient(neLabel, puis);
                                            logger.info(PC2LogCategory.Parser, subCat,
                                                    "removing client defined by " + rm.getName()
                                                            + " to list of accepted clients for global registrar");
                                        }
                                    } catch (Exception e) {
                                        String err = "Simulator failed to sleep. Terminating test.";
                                        logger.fatal(PC2LogCategory.Parser, subCat, err, e);
                                    }
                                    rm = null;
                                    if (dutConfigsToRemove.size() > 0)
                                        rm = dutConfigsToRemove.removeFirst();
                                }
                                dutConfigsToRead.clear();
                                dutConfigsToRemove.clear();
                            }
                        }
                    }
                } else {
                    // Since there are aren't any dut and test script
                    // files we can simply go to sleep and check again 
                    // later for any work.
                    Thread.sleep(250);
                }

            } catch (InterruptedException ie) {
                String msg = "Simulator sleep interrupted.";
                logger.info(PC2LogCategory.Parser, subCat, msg);
            } catch (Exception e) {
                String err = "Simulator failed to sleep. Terminating test.";
                logger.fatal(PC2LogCategory.Parser, subCat, err, e);
            }
        }
    }
    LogAPI.shutdown();
}

From source file:com.opera.core.systems.util.ProfileUtils.java

public boolean isMainProfile(String prefsPath) {
    File prefsFile = new File(prefsPath);
    String absolutePrefsPath = prefsFile.getAbsolutePath();

    // Get user home
    String path = System.getProperty("user.home");

    if (isMac()) {
        /* Mac//w w w .ja va  2s  .  co m
         * ~/Library/Application Support/Opera 
         * ~/Library/Caches/Opera 
         * ~/Library/Preferences/Opera Preferences
         */
        File appSupport = new File(path + "/Library/Application Support/Opera");
        File cache = new File(path + "/Library/Caches/Opera");
        File prefs = new File(path + "/Library/Preferences/Opera Preference");

        // Check if profiles start with this path
        if (absolutePrefsPath.startsWith(appSupport.getAbsolutePath())
                || absolutePrefsPath.startsWith(cache.getAbsolutePath())
                || absolutePrefsPath.startsWith(prefs.getAbsolutePath()))
            return true;

    } else if (isWindows()) {

        // On XP and Vista/7: 
        String appData = System.getenv("APPDATA");
        File appFile = new File(appData + "\\Opera");
        if (absolutePrefsPath.startsWith(appFile.getAbsolutePath()))
            return true;

        // On XP:
        String homeDrive = System.getenv("HOMEDRIVE");
        String homePath = System.getenv("HOMEPATH");
        File homeOpera = new File(homeDrive + homePath + "\\Local Settings\\Application Data\\Opera");
        if (absolutePrefsPath.startsWith(homeOpera.getAbsolutePath()))
            return true;

        // In Vista/7:
        String localAppData = System.getenv("LOCALAPPDATA");
        File localAppDataFile = new File(localAppData + "\\Opera");
        if (absolutePrefsPath.startsWith(localAppDataFile.getAbsolutePath()))
            return true;

        // On all Windows systems, <Installation Path>\profile:
        File exeFile = new File(settings.getOperaBinaryLocation());
        String parentPath = exeFile.getParent();
        File profileFolder = new File(parentPath + "\\profile");

        //a/b/c/exe
        //a/b/c/profile
        if (prefsFile.equals(profileFolder))
            return true;

    } else {

        /* *nix */
        File dotOpera = new File(path + "/.opera");
        if (/*platform nix && */ prefsFile.equals(dotOpera))
            return true;

    }

    return false;
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Finds all of the files in a specified directory whose class name matches a specified 
 * collection of names.  Matched classes will be added to a found set of names and copied
 * to a destination directory./*from w w w.  j  av  a2 s . c  o m*/
 * @param root The source root (so we can figure out the class name based on a file path).
 * @param dir The directory whose children we are crawling for matches.
 * @param classNames The class names we are searching for.
 * @param found Set where found class names are added.
 * @param destDir The directory where matched classes are copied to.
 * @throws IOException 
 */
private void findClassesInPath(File root, File dir, Collection<String> classNames, Set<String> found,
        File destDir) throws IOException {
    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            findClassesInPath(root, f, classNames, found, destDir);
        } else {
            ClassFile cf = getClassFile(root, f);
            if (cf != null && classNames.contains(cf.getName()) && !found.contains(cf.getName())) {
                File destFile = new File(destDir, cf.getJavaClassPath());
                destFile.getParentFile().mkdirs();
                if (!f.equals(destFile)) {
                    System.out.println("Copying " + f + " to " + destFile);
                    FileUtils.copyFile(f, destFile);
                }
                found.add(cf.getName());
            }
        }
    }
}

From source file:org.eclipse.swt.examples.fileviewer.FileViewer.java

/**
 * Handles deferred Refresh notifications (due to Drag & Drop)
 *///w w  w .j  a  va  2  s .  c  o m
void handleDeferredRefresh() {
    if (isDragging || isDropping || !deferredRefreshRequested)
        return;
    if (progressDialog != null) {
        progressDialog.close();
        progressDialog = null;
    }

    deferredRefreshRequested = false;
    File[] files = deferredRefreshFiles;
    deferredRefreshFiles = null;

    // shell.setCursor(iconCache.stockCursors[iconCache.cursorWait]);

    /*
     * Table view: Refreshes information about any files in the list and
     * their children.
     */
    boolean refreshTable = false;
    if (files != null) {
        for (int i = 0; i < files.length; ++i) {
            final File file = files[i];
            if (file.equals(currentDirectory)) {
                refreshTable = true;
                break;
            }
            File parentFile = file.getParentFile();
            if ((parentFile != null) && (parentFile.equals(currentDirectory))) {
                refreshTable = true;
                break;
            }
        }
    } else
        refreshTable = true;
    if (refreshTable)
        workerUpdate(currentDirectory, true);

    /*
     * Combo view: Refreshes the list of roots
     */
    final File[] roots = getRoots();

    if (files == null) {
        boolean refreshCombo = false;
        final File[] comboRoots = (File[]) combo.getData(COMBODATA_ROOTS);

        if ((comboRoots != null) && (comboRoots.length == roots.length)) {
            for (int i = 0; i < roots.length; ++i) {
                if (!roots[i].equals(comboRoots[i])) {
                    refreshCombo = true;
                    break;
                }
            }
        } else
            refreshCombo = true;

        if (refreshCombo) {
            combo.removeAll();
            combo.setData(COMBODATA_ROOTS, roots);
            for (int i = 0; i < roots.length; ++i) {
                final File file = roots[i];
                combo.add(file.getPath());
            }
        }
    }

    /*
     * Tree view: Refreshes information about any files in the list and
     * their children.
     */
    treeRefresh(roots);

    // Remind everyone where we are in the filesystem
    final File dir = currentDirectory;
    currentDirectory = null;
    notifySelectedDirectory(dir, false);

    // shell.setCursor(iconCache.stockCursors[iconCache.cursorDefault]);
}

From source file:ffx.ui.ModelingPanel.java

private void loadLogSettings() {
    String selected = (String) logSettings.getSelectedItem();
    logSettings.removeActionListener(this);
    logSettings.removeAllItems();/*  w w w.j  a  v  a  2  s  .c  o m*/
    File currentLog;
    String fileName;
    File logDir;
    File systemDir;
    // This implies no Open System
    if (activeSystem == null) {
        fileName = ((String) currentCommandBox.getSelectedItem()).toLowerCase() + ".log";
        currentLog = new File(MainPanel.getPWD() + File.separator + fileName);
        logDir = currentLog.getParentFile();
        systemDir = MainPanel.getPWD();
    } else {
        currentLog = activeSystem.getLogFile();
        fileName = currentLog.getName();
        logDir = currentLog.getParentFile();
        systemDir = activeSystem.getFile().getAbsoluteFile().getParentFile();
    }
    File tempLog;
    File newLog;
    if (logDir == null || !logDir.equals(systemDir)) {
        tempLog = new File(systemDir.getAbsolutePath() + File.separator + fileName);
        if (!commandFileTypes.contains(FileType.ANY)) {
            activeSystem.setLogFile(tempLog);
        }
    } else {
        tempLog = currentLog;
    }
    // Simple Case - default log file doesn't exist yet
    String createNew = null;
    if (!tempLog.exists()) {
        createNew = "Create " + fileName;
        logSettings.addItem(createNew);
        logSettings.setSelectedItem(createNew);
        logString = getLogString(tempLog);
        logSettings.addActionListener(this);
        if (!commandFileTypes.contains(FileType.ANY)) {
            activeSystem.setLogFile(tempLog);
        }
        return;
    }
    // The default log exists, so we can append to it, overwrite it, or
    // create a new one
    newLog = SystemFilter.version(tempLog);
    tempLog = SystemFilter.previousVersion(newLog);
    fileName = tempLog.getName();
    String append = "Append to " + fileName;
    String overwrite = "Overwrite " + fileName;
    logSettings.addItem(append);
    logSettings.addItem(overwrite);
    if (!newLog.equals(tempLog)) {
        createNew = "Create " + newLog.getName();
        logSettings.addItem(createNew);
    }
    if (selected == null) {
        logSettings.setSelectedIndex(0);
        logString = null;
    } else if (selected.startsWith("Append")) {
        logSettings.setSelectedItem(append);
        logString = getLogString(tempLog);
    } else if (selected.startsWith("Overwrite")) {
        logSettings.setSelectedItem(overwrite);
        logString = getLogString(tempLog);
    } else {
        if (createNew != null) {
            logSettings.setSelectedItem(createNew);
            logString = getLogString(newLog);
        } else {
            logString = getLogString(tempLog);
            logSettings.setSelectedItem(append);
        }
    }
    logSettings.addActionListener(this);
}

From source file:org.opentravel.schemacompiler.repository.ProjectManager.java

/**
 * Returns true if the given URL references a location in the user's local repository -- either
 * as a locally-managed item or a local copy of a remotely-managed library.
 * //from   w  w w . j a v  a  2  s. c  o m
 * @param libraryUrl
 *            the library URL to analyze
 * @return boolean
 */
public boolean isRepositoryUrl(URL libraryUrl) {
    boolean result = false;

    if (URLUtils.isFileURL(libraryUrl)) {
        File repositoryLocation = repositoryManager.getRepositoryLocation();
        File libraryFolder = URLUtils.toFile(libraryUrl).getParentFile();

        while (!result && (libraryFolder != null)) {
            result = libraryFolder.equals(repositoryLocation);
            libraryFolder = libraryFolder.getParentFile();
        }
    }
    return result;
}

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImpl.java

/**
 * Removes a set of volumes from FsDataset.
 * @param volumesToRemove a set of absolute root path of each volume.
 * @param clearFailure set true to clear failure information.
 *
 * DataNode should call this function before calling
 * {@link DataStorage#removeVolumes(java.util.Collection)}.
 *///from  w  ww .java  2  s  .  c om
@Override
public synchronized void removeVolumes(Set<File> volumesToRemove, boolean clearFailure) {
    // Make sure that all volumes are absolute path.
    for (File vol : volumesToRemove) {
        Preconditions.checkArgument(vol.isAbsolute(), String.format("%s is not absolute path.", vol.getPath()));
    }
    for (int idx = 0; idx < dataStorage.getNumStorageDirs(); idx++) {
        Storage.StorageDirectory sd = dataStorage.getStorageDir(idx);
        final File absRoot = sd.getRoot().getAbsoluteFile();
        if (volumesToRemove.contains(absRoot)) {
            LOG.info("Removing " + absRoot + " from FsDataset.");

            // Disable the volume from the service.
            asyncDiskService.removeVolume(sd.getCurrentDir());
            volumes.removeVolume(absRoot, clearFailure);

            // Removed all replica information for the blocks on the volume. Unlike
            // updating the volumeMap in addVolume(), this operation does not scan
            // disks.
            for (String bpid : volumeMap.getBlockPoolList()) {
                for (Iterator<ReplicaInfo> it = volumeMap.replicas(bpid).iterator(); it.hasNext();) {
                    ReplicaInfo block = it.next();
                    final File absBasePath = new File(block.getVolume().getBasePath()).getAbsoluteFile();
                    if (absBasePath.equals(absRoot)) {
                        invalidate(bpid, block);
                        it.remove();
                    }
                }
            }

            storageMap.remove(sd.getStorageUuid());
        }
    }
}