Example usage for java.io File isAbsolute

List of usage examples for java.io File isAbsolute

Introduction

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

Prototype

public boolean isAbsolute() 

Source Link

Document

Tests whether this abstract pathname is absolute.

Usage

From source file:org.apache.nifi.bootstrap.RunNiFi.java

private NotificationServiceManager loadServices() throws IOException {
    final File bootstrapConfFile = getBootstrapConfFile();
    final Properties properties = new Properties();
    try (final FileInputStream fis = new FileInputStream(bootstrapConfFile)) {
        properties.load(fis);/*  w  w  w  .j av  a 2 s .  c o m*/
    }

    final NotificationServiceManager manager = new NotificationServiceManager();
    final String attemptProp = properties.getProperty(NOTIFICATION_ATTEMPTS_PROP);
    if (attemptProp != null) {
        try {
            final int maxAttempts = Integer.parseInt(attemptProp.trim());
            if (maxAttempts >= 0) {
                manager.setMaxNotificationAttempts(maxAttempts);
            }
        } catch (final NumberFormatException nfe) {
            defaultLogger.error(
                    "Maximum number of attempts to send notification email is set to an invalid value of {}; will use default value",
                    attemptProp);
        }
    }

    final String notificationServicesXmlFilename = properties.getProperty(NOTIFICATION_SERVICES_FILE_PROP);
    if (notificationServicesXmlFilename == null) {
        defaultLogger.info("No Bootstrap Notification Services configured.");
        return manager;
    }

    final File xmlFile = new File(notificationServicesXmlFilename);
    final File servicesFile;

    if (xmlFile.isAbsolute()) {
        servicesFile = xmlFile;
    } else {
        final File confDir = bootstrapConfigFile.getParentFile();
        final File nifiHome = confDir.getParentFile();
        servicesFile = new File(nifiHome, notificationServicesXmlFilename);
    }

    if (!servicesFile.exists()) {
        defaultLogger.error("Bootstrap Notification Services file configured as " + servicesFile
                + " but could not find file; will not load notification services");
        return manager;
    }

    try {
        manager.loadNotificationServices(servicesFile);
    } catch (final Exception e) {
        defaultLogger.error("Bootstrap Notification Services file configured as " + servicesFile
                + " but failed to load notification services", e);
    }

    registerNotificationServices(manager, NotificationType.NIFI_STARTED,
            properties.getProperty(NIFI_START_NOTIFICATION_SERVICE_IDS_PROP));
    registerNotificationServices(manager, NotificationType.NIFI_STOPPED,
            properties.getProperty(NIFI_STOP_NOTIFICATION_SERVICE_IDS_PROP));
    registerNotificationServices(manager, NotificationType.NIFI_DIED,
            properties.getProperty(NIFI_DEAD_NOTIFICATION_SERVICE_IDS_PROP));

    return manager;
}

From source file:maspack.fileutil.FileManager.java

/**
 * Retrieves a local file if it exists, null otherwise. If the file
 * path is relative, then it prepends the download directory.
 * /*from www  .  j  a v  a2 s  .co  m*/
 * @param file path for the local file
 * @return the file handle
 */
public File getLocal(File file) {

    if (!file.isAbsolute()) {
        file = new File(downloadDir, file.getPath());
    }
    if (!file.exists()) {
        return null;
    }
    lastFile = file;
    lastWasRemote = false;
    return file;
}

From source file:maspack.fileutil.FileManager.java

/**
 * Converts a relative file to an absolute one using the object's download
 * directory. If the supplied file is absolute, this is returned.
 * //from  w  ww  .  jav a2 s. co m
 * @param relFile
 * the relative file
 * @return absolute file
 */
public File getAbsoluteFile(File relFile) {
    File file = relFile;
    if (!file.isAbsolute()) {
        file = new File(downloadDir.getAbsoluteFile(), relFile.getPath());
    }
    return file;
}

From source file:nl.tudelft.goal.SimpleIDE.FilePanel.java

/**
 * Updates the tree model so that the children of the given mas node
 * correspond to the agent files described in the mas file. Any goal files
 * that are children of the given mas node but are not referenced to in the
 * mas file will be moved to the null file node.
 *
 * @param masNode//w w w. j a  v a2 s .  co  m
 *            The mas node of which the children should be refreshed.
 * @param showLoadError
 *            If this is <code>false</code>, any GOALException thrown when
 *            getting the agent file names will be ignored. If
 *            <code>true</code>, the user will be notified of them.<br>
 *            Use <code>false</code> when this is called after saving, as
 *            the message should have already been displayed.
 */
private void refreshMASNode(MASNode masNode) {

    // Do nothing if the given node is not part of the tree (or null)
    if (!this.rootNode.isNodeDescendant(masNode)) {
        return;
    }

    // Do nothing if the file is not validated.
    MASProgram mas = this.platform.getMASProgram(masNode.getBaseFile());
    if (mas == null) {
        return;
    }

    // Compare current nodes with current agent files associated with MAS
    // file.
    // Get current node children.
    List<FileNode> currentChildren = getChildrenOf(masNode);
    // Get the associated files.
    List<File> currentFiles = new ArrayList<File>();
    for (FileNode node : currentChildren) {
        currentFiles.add(node.getBaseFile());
    }

    // Get new agent files.
    List<File> newFiles = this.platform.getMASProgram(masNode.getBaseFile()).getAgentFiles();

    // Get new emotion file.
    String emoString = this.platform.getMASProgram(masNode.getBaseFile()).getEmotionFile();
    if (emoString != null) {
        if (new File(emoString).isAbsolute()) {
            newFiles.add(new File(emoString));
        } else {
            String emoPath = masNode.getBaseFile().getParentFile().getAbsolutePath();
            newFiles.add(new File(emoPath, emoString));
        }
    }

    // Check whether nodes need to be removed, i.e., whether they do not
    // correspond with any files associated with the MAS file.
    for (FileNode node : currentChildren) {
        if (!newFiles.contains(node.getBaseFile())) {
            // Move node to the spurious file node.
            appendNode(null, node);
        }
    }
    // CHECK is this always absolute path?
    String masdir = masNode.getBaseFile().getParent();
    // Check whether agent files need to be inserted.
    for (File agentFile : newFiles) {
        if (!agentFile.exists()) {
            // doesn't exist. Suggest to create
            String path = agentFile.getPath();
            File newFile = new File(path);
            if (!newFile.isAbsolute()) {
                // If relative, prepend MAS dir. #2926
                newFile = new File(FilenameUtils.concat(masdir, agentFile.getPath()));
            }
            try {
                proposeToCreate(this, newFile, Extension.GOAL);
                this.platform.parseGOALFile(newFile, mas.getKRInterface(newFile));
            } catch (GOALUserError ignore) {
                // this file does not really exist. #2692
                // We want to continue here to handle all other GOAL files,
                // even if user cancelled creation of one of these or IO
                // error happened.
            } catch (ParserException e) {
                // Even in case of serious parse errors we simply skip
                // the current agent file and continue with the next.
                // We want to process as many agent files as we can.
                continue;
            }
        }
        if (!currentFiles.contains(agentFile)) {
            FileNode newNode;
            if (Extension.getFileExtension(agentFile) == Extension.EMOTION) {
                newNode = new EmotionNode(agentFile);
            } else {
                newNode = new GOALNode(agentFile);
            }
            this.allFiles.add(newNode);
            // GOALNode newNode = insertGOALfile(agentFile.getAgentFile());
            appendNode(masNode, newNode);
            // also let the tree scroll to the newly added node
            this.fileTree.scrollPathToVisible(new TreePath(masNode.getPath()));
        }
    }

    refreshSpuriousList();

}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.JavaAutConfigComponent.java

/**
 * handle the browse request locally//  ww  w.java 2  s.  co  m
 * 
 * @param extensionFilters Only files with one of the 
 *                         provided extensions will be shown in the dialog.
 *                         May be <code>null</code>, in which case all 
 *                         files will be shown.
 * @param configVarKey key for storing the result
 * @param textField control for visualizing the value
 * @param title window title
 */
void browseLocal(String[] extensionFilters, String title, Text textField, String configVarKey) {
    String directory;
    FileDialog fileDialog = new FileDialog(getShell(), SWT.APPLICATION_MODAL | SWT.ON_TOP);
    if (extensionFilters != null) {
        fileDialog.setFilterExtensions(extensionFilters);
    }
    fileDialog.setText(title);
    String filterPath = Utils.getLastDirPath();
    File path = new File(textField.getText());
    if (!path.isAbsolute()) {
        path = new File(getConfigValue(AutConfigConstants.WORKING_DIR), textField.getText());
    }
    if (path.exists()) {
        try {
            if (path.isDirectory()) {
                filterPath = path.getCanonicalPath();
            } else {
                filterPath = new File(path.getParent()).getCanonicalPath();
            }
        } catch (IOException e) {
            // Just use the default filter path which is already set
        }
    }
    fileDialog.setFilterPath(filterPath);
    directory = fileDialog.open();
    if (directory != null) {
        textField.setText(directory);
        Utils.storeLastDirPath(fileDialog.getFilterPath());
        putConfigValue(configVarKey, directory);
    }
}

From source file:org.apache.maven.plugin.eclipse.EclipsePlugin.java

final void extractResourceDirs(Set directories, List resources, File basedir, File workspaceProjectBaseDir,
        boolean test, final String output) throws MojoExecutionException {
    for (Iterator it = resources.iterator(); it.hasNext();) {
        Resource resource = (Resource) it.next();

        getLog().debug("Processing resource dir: " + resource.getDirectory());

        List excludes = new ArrayList(resource.getExcludes());
        // automatically exclude java files: eclipse doesn't have the concept of resource directory so it will
        // try to compile any java file found in maven resource dirs
        excludes.add(JAVA_FILE_PATTERN);

        // TODO: figure out how to merge if the same dir is specified twice
        // with different in/exclude patterns.

        File resourceDirectory = new File( /* basedir, */resource.getDirectory());

        if (!resourceDirectory.exists() || !resourceDirectory.isDirectory()) {
            getLog().debug("Resource dir: " + resourceDirectory + " either missing or not a directory.");
            continue;
        }/*from   ww w.  j a v  a  2  s.  co m*/

        String resourcePath = IdeUtils.toRelativeAndFixSeparator(workspaceProjectBaseDir, resourceDirectory,
                !workspaceProjectBaseDir.equals(basedir));
        String thisOutput = output;
        if (thisOutput != null) {
            // sometimes thisOutput is already an absolute path
            File outputFile = new File(thisOutput);
            if (!outputFile.isAbsolute()) {
                outputFile = new File(workspaceProjectBaseDir, thisOutput);
            }
            // create output dir if it doesn't exist
            outputFile.mkdirs();

            if (!StringUtils.isEmpty(resource.getTargetPath())) {
                outputFile = new File(outputFile, resource.getTargetPath());
                // create output dir if it doesn't exist
                outputFile.mkdirs();
            }

            getLog().debug("Making relative and fixing separator: { " + workspaceProjectBaseDir + ", "
                    + outputFile + ", false }.");
            thisOutput = IdeUtils.toRelativeAndFixSeparator(workspaceProjectBaseDir, outputFile, false);
        }

        EclipseSourceDir resourceDir = new EclipseSourceDir(resourcePath, thisOutput, true, test,
                resource.getIncludes(), excludes, resource.isFiltering());

        if (!directories.add(resourceDir)) {
            EclipseSourceDir originalDir = (EclipseSourceDir) get(directories, resourceDir);
            getLog().info(
                    "Resource directory's path matches an existing source directory. Resources will be merged with the source directory "
                            + originalDir.getPath());
            originalDir.merge(resourceDir);
        }
    }
}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.JavaAutConfigComponent.java

/**
 * The action of the working directory field.
 * @return <code>null</code> if the new value is valid. Otherwise, returns
 *         a status parameter indicating the cause of the problem.
 */// w w w  .j a  v a 2  s.  c o m
DialogStatusParameter modifyExecTextField() {
    DialogStatusParameter error = null;
    m_isExecFieldValid = true;
    isExecFieldEmpty = m_execTextField.getText().length() == 0;
    String filename = m_execTextField.getText();
    if (isValid(m_execTextField, true) && !isExecFieldEmpty) {
        if (checkLocalhostServer()) {
            File file = new File(filename);
            if (!file.isAbsolute()) {
                String workingDirString = getConfigValue(AutConfigConstants.WORKING_DIR);
                if (workingDirString != null && workingDirString.length() != 0) {

                    filename = workingDirString + "/" + filename; //$NON-NLS-1$
                    file = new File(filename);
                }
            }

            try {
                if (!file.isFile()) {
                    error = createWarningStatus(
                            NLS.bind(Messages.AUTConfigComponentFileNotFound, file.getCanonicalPath()));
                } else {
                    // Make sure that the user has not entered an executable
                    // JAR file in the wrong field.
                    new JarFile(file);
                    error = createErrorStatus(
                            NLS.bind(Messages.AUTConfigComponentFileJar, file.getCanonicalPath()));
                }
            } catch (ZipException ze) {
                // Expected. This occurs if the given file exists but is not 
                // a JAR file.
            } catch (IOException e) {
                // could not find file
                error = createWarningStatus(NLS.bind(Messages.AUTConfigComponentFileNotFound, filename));
            }
        }
    } else if (!isExecFieldEmpty) {
        error = createErrorStatus(Messages.AUTConfigComponentWrongExecutable);
    }
    if (error != null) {
        m_isExecFieldValid = false;
    }
    putConfigValue(AutConfigConstants.EXECUTABLE, m_execTextField.getText());
    executablePath = filename;

    return error;
}

From source file:com.izforge.izpack.util.os.Unix_Shortcut.java

/**
 * Creates and stores the shortcut-files.
 *
 * @throws java.lang.Exception error occured
 * @see com.izforge.izpack.util.os.Shortcut#save()
 *//*from   w  w  w .  j a  v  a  2  s.  c o  m*/
@Override
public void save() throws Exception {
    String shortCutDef = this.build();

    boolean rootUser4All = this.getUserType() == Shortcut.ALL_USERS;
    boolean create4All = this.getCreateForAll();

    // Create The Desktop Shortcuts
    if ("".equals(this.programGroup) && (this.getLinkType() == Shortcut.DESKTOP)) {

        this.itsFileName = null;

        // read the userdefined / overridden / wished Shortcut Location
        // This can be an absolute Path name or a relative Path to the InstallPath
        File shortCutLocation = null;
        File ApplicationShortcutPath;
        String ApplicationShortcutPathName = installData.getVariable("ApplicationShortcutPath"/*
                                                                                              TODO
                                                                                              <-- Put in Docu and in Un/InstallerConstantsClass
                                                                                              */
        );
        if (null != ApplicationShortcutPathName && !ApplicationShortcutPathName.equals("")) {
            ApplicationShortcutPath = new File(ApplicationShortcutPathName);

            if (ApplicationShortcutPath.isAbsolute()) {
                // I know :-) Can be m"ORed" elegant :)
                if (!ApplicationShortcutPath.exists() && ApplicationShortcutPath.mkdirs()
                        && ApplicationShortcutPath.canWrite()) {
                    shortCutLocation = ApplicationShortcutPath;
                }
                if (ApplicationShortcutPath.exists() && ApplicationShortcutPath.isDirectory()
                        && ApplicationShortcutPath.canWrite()) {
                    shortCutLocation = ApplicationShortcutPath;
                }
            } else {
                File relativePath = new File(installData.getInstallPath() + FS + ApplicationShortcutPath);
                //noinspection ResultOfMethodCallIgnored
                relativePath.mkdirs();
                shortCutLocation = new File(relativePath.toString());
            }
        }

        if (shortCutLocation == null)
            shortCutLocation = new File(installData.getInstallPath());

        // write the App ShortCut
        File writtenDesktopFile = writeAppShortcutWithOutSpace(shortCutLocation.toString(), this.linkName,
                shortCutDef);
        uninstaller.addFile(writtenDesktopFile.toString(), true);

        // Now install my Own with xdg-if available // Note the The reverse Uninstall-Task is on
        // TODO: "WHICH another place"

        String cmd = getXdgDesktopIconCmd();
        if (cmd != null) {
            createExtXdgDesktopIconCmd(shortCutLocation);
            // / TODO: DELETE the ScriptFiles
            myInstallScript.appendln(new String[] { makeFilenameScriptable(myXdgDesktopIconCmd), "install",
                    "--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString()) });
            ShellScript myUninstallScript = new ShellScript();
            myUninstallScript.appendln(new String[] { makeFilenameScriptable(myXdgDesktopIconCmd), "uninstall",
                    "--novendor", StringTool.escapeSpaces(writtenDesktopFile.toString()) });
            uninstaller.addUninstallScript(myUninstallScript.getContentAsString());
        } else {
            // otherwise copy to my desktop and add to uninstaller
            File myDesktopFile;
            do {
                myDesktopFile = new File(myHome + FS + "Desktop" + writtenDesktopFile.getName() + "-"
                        + System.currentTimeMillis() + DESKTOP_EXT);
            } while (myDesktopFile.exists());

            FileUtils.copyFile(writtenDesktopFile, myDesktopFile, false);
            uninstaller.addFile(myDesktopFile.toString(), true);
        }

        // If I'm root and this Desktop.ShortCut should be for all other users
        if (rootUser4All && create4All) {
            if (cmd != null) {
                installDesktopFileToAllUsersDesktop(writtenDesktopFile);
            } else
            // OLD ( Backward-Compatible/hardwired-"Desktop"-Foldername Styled Mechanic )
            {
                copyDesktopFileToAllUsersDesktop(writtenDesktopFile);
            }
        }
    }

    // This is - or should be only a Link in the [K?]-Menu
    else {
        // the following is for backwards compatibility to older versions of KDE!
        // on newer versions of KDE the icons will appear duplicated unless you set
        // the category=""

        // removed because of compatibility issues
        /*
         * Object categoryobject = props.getProperty($Categories); if(categoryobject != null &&
         * ((String)categoryobject).length()>0) { File kdeHomeShareApplnk =
         * getKdeShareApplnkFolder(this.getUserType()); target = kdeHomeShareApplnk.toString() +
         * FS + this.itsGroupName + FS + this.itsName + DESKTOP_EXT; this.itsFileName = target;
         * File kdemenufile = writeShortCut(target, shortCutDef);
         *
         * uninstaller.addFile(kdemenufile.toString(), true); }
         */

        if (rootUser4All && create4All) {
            {
                // write the icon pixmaps into /usr/share/pixmaps

                File theIcon = new File(this.getIconLocation());
                File commonIcon = new File("/usr/share/pixmaps/" + theIcon.getName());

                try {
                    FileUtils.copyFile(theIcon, commonIcon, false);
                    uninstaller.addFile(commonIcon.toString(), true);
                } catch (Exception e) {
                    logger.log(Level.WARNING,
                            "Could not copy " + theIcon + " to " + commonIcon + " (" + e.getMessage() + ")", e);
                }

                // write *.desktop

                this.itsFileName = null;
                File writtenFile = writeAppShortcut("/usr/share/applications/", this.linkName, shortCutDef);
                setWrittenFileName(writtenFile.getName());
                uninstaller.addFile(writtenFile.toString(), true);

            }
        } else
        // create local XDG shortcuts
        {
            // System.out.println("Creating gnome shortcut");
            String localApps = myHome + "/.local/share/applications/";
            String localPixmaps = myHome + "/.local/share/pixmaps/";
            // System.out.println("Creating "+localApps);
            try {
                java.io.File file = new java.io.File(localApps);
                //noinspection ResultOfMethodCallIgnored
                file.mkdirs();

                file = new java.io.File(localPixmaps);
                //noinspection ResultOfMethodCallIgnored
                file.mkdirs();
            } catch (Exception ignore) {
                // System.out.println("Failed creating "+localApps + " or " + localPixmaps);
                logger.warning("Failed creating " + localApps + " or " + localPixmaps);
            }

            // write the icon pixmaps into ~/share/pixmaps

            File theIcon = new File(this.getIconLocation());
            File commonIcon = new File(localPixmaps + theIcon.getName());

            try {
                FileUtils.copyFile(theIcon, commonIcon, false);
                uninstaller.addFile(commonIcon.toString(), true);
            } catch (Exception e) {
                logger.log(Level.WARNING,
                        "Could not copy " + theIcon + " to " + commonIcon + " (" + e.getMessage() + ")", e);
            }

            // write *.desktop in the local folder

            this.itsFileName = null;
            File writtenFile = writeAppShortcut(localApps, this.linkName, shortCutDef);
            setWrittenFileName(writtenFile.getName());
            uninstaller.addFile(writtenFile.toString(), true);
        }

    }
}

From source file:maspack.fileutil.FileManager.java

/**
 * Uploads a file, according to options. Works with absolute paths and
 * destination URIs, otherwise combines path and dest URI with downloadDir and
 * remoteSource, respectively. If the destination is null or a directory,
 * then the filename of source is appended.
 * /*  ww  w. j a  va2 s . co m*/
 * If there is any internal problem, (such as failing to obtain a hash, or
 * failing to download a file), the function will log the error message and
 * continue.
 * 
 * @param source
 * the source file to upload
 * @param dest
 * the remote URI to upload to
 * @param options
 * set of options, either FORCE_REMOTE or CHECK_HASH
 * @throws FileTransferException if the upload fails
 */
public void put(File source, URIx dest, int options) throws FileTransferException {

    // default destination if none provided
    if (dest == null) {
        if (!source.isAbsolute()) {
            dest = new URIx(source.getPath());
        } else {
            dest = new URIx(source.getName());
        }
    } else if (isDirectory(dest)) {
        if (!source.isAbsolute()) {
            dest = new URIx(dest, source.getPath());
        } else {
            dest = new URIx(dest, source.getName());
        }
    }

    // convert to absolute
    dest = getAbsoluteURI(dest);
    source = getAbsoluteFile(source);

    // XXX TODO: check if we need to actually upload file
    boolean push = true;

    //      if ((options & FORCE_REMOTE) == 0) {
    //         // check if file exists
    //         if (dest.canRead()) {
    //
    //            // check hash if options say so
    //            if ((options & CHECK_HASH) != 0) {
    //               try {
    //                  fetch = !equalsHash(dest, source);
    //                  if (fetch) {
    //                     logger.debug("Hash matches");
    //                  }
    //               } catch (FileTransferException e) {
    //                  logger.debug(
    //                     "Cannot obtain hash, assuming it doesn't match, "
    //                     + e.getMessage());
    //                  exceptionStack.add(e);
    //                  fetch = true;
    //               }
    //            } else {
    //               // file exists, so let it be
    //               fetch = false;
    //            }
    //         }
    //      }

    // download file if we need to
    if (push) {
        putRemote(source, dest);
    } else {
        logger.debug("File '" + dest + "' exists and does not need to be uploaded.");
    }

}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.JavaAutConfigComponent.java

/**
 * Handles the button event.//w w w . ja v  a 2s . c  o m
 * @param fileDialog The file dialog.
 */
void handleExecButtonEvent(FileDialog fileDialog) {
    String directory;
    fileDialog.setText(Messages.AUTConfigComponentSelectExecutable);
    String filterPath = Utils.getLastDirPath();
    File path = new File(getConfigValue(AutConfigConstants.EXECUTABLE));
    if (!path.isAbsolute()) {
        path = new File(getConfigValue(AutConfigConstants.WORKING_DIR),
                getConfigValue(AutConfigConstants.EXECUTABLE));
    }
    if (path.exists()) {
        try {
            if (path.isDirectory()) {
                filterPath = path.getCanonicalPath();
            } else {
                filterPath = new File(path.getParent()).getCanonicalPath();
            }
        } catch (IOException e) {
            // Just use the default filter path which is already set
        }
    }
    fileDialog.setFilterPath(filterPath);
    directory = fileDialog.open();
    if (directory != null) {
        m_execTextField.setText(directory);
        Utils.storeLastDirPath(fileDialog.getFilterPath());
        putConfigValue(AutConfigConstants.EXECUTABLE, directory);
        executablePath = directory;

        setWorkingDirToExecFilePath(executablePath);
    }
}