Example usage for java.io File getCanonicalFile

List of usage examples for java.io File getCanonicalFile

Introduction

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

Prototype

public File getCanonicalFile() throws IOException 

Source Link

Document

Returns the canonical form of this abstract pathname.

Usage

From source file:com.newrelic.agent.AgentCommandLineParser.java

private void installCommand(CommandLine cmd)/* 140:    */ throws Exception
/* 141:    */ {/*from   w  w w .  j  a  v a 2  s . co  m*/
    /* 142:124 */ System.out.println("***** ( ( o))  New Relic Java Agent Installer");
    /* 143:125 */ System.out.println("***** Installing version " + Agent.getVersion() + " ...");
    /* 144:    */
    /* 145:127 */ File newRelicDir = new File(
            getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile();
    /* 146:    */
    /* 147:129 */ File appServerDir = null;
    /* 148:130 */ if (cmd.getOptionValue('s') != null) {
        /* 149:131 */ appServerDir = new File(cmd.getOptionValue('s'));
        /* 150:    */ }
    /* 151:132 */ if ((appServerDir == null) || (!appServerDir.exists()) || (!appServerDir.isDirectory())) {
        /* 152:133 */ appServerDir = newRelicDir.getParentFile();
        /* 153:    */ }
    /* 154:134 */ appServerDir = appServerDir.getCanonicalFile();
    /* 155:    */
    /* 156:136 */ boolean startup_patched = false;
    /* 157:137 */ boolean config_installed = false;
    /* 158:138 */ AppServerIdentifier.AppServerType type = AppServerIdentifier.getAppServerType(appServerDir);
    /* 159:141 */ if ((type == null) || (type == AppServerIdentifier.AppServerType.UNKNOWN))
    /* 160:    */ {
        /* 161:142 */ printUnknownAppServer(appServerDir);
        /* 162:    */ }
    /* 163:    */ else
    /* 164:    */ {
        /* 165:144 */ SelfInstaller installer = SelfInstallerFactory.getSelfInstaller(type);
        /* 166:145 */ if (installer != null) {
            /* 167:146 */ startup_patched = installer.backupAndEditStartScript(appServerDir.toString());
            /* 168:    */ }
        /* 169:    */ }
    /* 170:150 */ if ((newRelicDir.exists()) && (newRelicDir.isDirectory()))
    /* 171:    */ {
        /* 172:151 */ if (ConfigInstaller.isConfigInstalled(newRelicDir))
        /* 173:    */ {
            /* 174:152 */ System.out.println("No need to create New Relic configuration file because:");
            /* 175:153 */ System.out.println(MessageFormat.format(" .:. A config file already exists: {0}",
                    new Object[] { ConfigInstaller.configPath(newRelicDir) }));
            /* 176:    */
            /* 177:155 */ config_installed = true;
            /* 178:    */ }
        /* 179:    */ else
        /* 180:    */ {
            /* 181:    */ try
            /* 182:    */ {
                /* 183:158 */ ConfigInstaller.install(cmd.getOptionValue('l'), newRelicDir);
                /* 184:159 */ config_installed = true;
                /* 185:160 */ System.out.println(
                        "Generated New Relic configuration file " + ConfigInstaller.configPath(newRelicDir));
                /* 186:    */ }
            /* 187:    */ catch (IOException e)
            /* 188:    */ {
                /* 189:163 */ System.err.println(
                        MessageFormat.format("An error occurred generating the configuration file {0} : {1}",
                                new Object[] { ConfigInstaller.configPath(newRelicDir), e.toString() }));
                /* 190:    */
                /* 191:    */
                /* 192:166 */ Agent.LOG.log(Level.FINE, "Config file generation error", e);
                /* 193:    */ }
            /* 194:    */ }
        /* 195:    */ }
    /* 196:    */ else
    /* 197:    */ {
        /* 198:170 */ System.err.println("Could not create New Relic configuration file because:");
        /* 199:171 */ System.err.println(MessageFormat.format(" .:. {0} does not exist or is not a directory",
                new Object[] { newRelicDir.getAbsolutePath() }));
        /* 200:    */ }
    /* 201:176 */ if ((startup_patched) && (config_installed))
    /* 202:    */ {
        /* 203:177 */ printInstallSuccess();
        /* 204:178 */ System.exit(0);
        /* 205:    */ }
    /* 206:    */ else
    /* 207:    */ {
        /* 208:180 */ printInstallIncomplete();
        /* 209:181 */ System.exit(1);
        /* 210:    */ }
    /* 211:    */ }

From source file:org.sonar.batch.scan.DefaultProjectBootstrapper.java

private ProjectDefinition loadChildProject(ProjectDefinition parentProject, Properties moduleProps,
        String moduleId) {/*ww  w  .  jav a2  s . c o m*/
    setProjectKeyAndNameIfNotDefined(moduleProps, moduleId);

    final File baseDir;
    if (moduleProps.containsKey(PROPERTY_PROJECT_BASEDIR)) {
        baseDir = getFileFromPath(moduleProps.getProperty(PROPERTY_PROJECT_BASEDIR),
                parentProject.getBaseDir());
        setProjectBaseDir(baseDir, moduleProps, moduleId);
        try {
            if (!parentProject.getBaseDir().getCanonicalFile().equals(baseDir.getCanonicalFile())) {
                tryToFindAndLoadPropsFile(baseDir, moduleProps, moduleId);
            }
        } catch (IOException e) {
            throw new IllegalStateException("Error when resolving baseDir", e);
        }
    } else if (moduleProps.containsKey(PROPERTY_PROJECT_CONFIG_FILE)) {
        baseDir = loadPropsFile(parentProject, moduleProps, moduleId);
    } else {
        baseDir = new File(parentProject.getBaseDir(), moduleId);
        setProjectBaseDir(baseDir, moduleProps, moduleId);
        tryToFindAndLoadPropsFile(baseDir, moduleProps, moduleId);
    }

    // and finish
    checkMandatoryProperties(moduleProps, MANDATORY_PROPERTIES_FOR_CHILD);
    validateDirectories(moduleProps, baseDir, moduleId);

    mergeParentProperties(moduleProps, parentProject.getProperties());

    prefixProjectKeyWithParentKey(moduleProps, parentProject.getKey());

    return defineProject(moduleProps, parentProject);
}

From source file:de.jwi.jfm.Folder.java

private File getTargetFile(String target) throws IOException {
    File f = null;

    if (target.startsWith(File.separator)) {
        f = new File(target);
    } else {//from   ww  w  . j  a  va 2s .co  m
        f = new File(myFile, target);
    }

    f = f.getCanonicalFile();

    return f;
}

From source file:org.apache.maven.wagon.providers.file.FileWagon.java

public void putDirectory(File sourceDirectory, String destinationDirectory)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    if (getRepository().getBasedir() == null) {
        throw new TransferFailedException("Unable to putDirectory() with a null basedir.");
    }//from w  w w .  j  av a2  s .  c o  m

    File path = resolveDestinationPath(destinationDirectory);

    try {
        /*
         * Done to address issue found in HP-UX with regards to "." directory references. Details found in ..
         * WAGON-30 - wagon-file failed when used by maven-site-plugin WAGON-33 - FileWagon#putDirectory() fails in
         * HP-UX if destinationDirectory is "."
         * http://www.nabble.com/With-maven-2.0.2-site%3Adeploy-doesn%27t-work-t934716.html for details. Using
         * path.getCanonicalFile() ensures that the path is fully resolved before an attempt to create it. TODO:
         * consider moving this to FileUtils.mkdirs()
         */
        File realFile = path.getCanonicalFile();
        realFile.mkdirs();
    } catch (IOException e) {
        // Fall back to standard way if getCanonicalFile() fails.
        path.mkdirs();
    }

    if (!path.exists() || !path.isDirectory()) {
        String emsg = "Could not make directory '" + path.getAbsolutePath() + "'.";

        // Add assistive message in case of failure.
        File basedir = new File(getRepository().getBasedir());
        if (!basedir.canWrite()) {
            emsg += "  The base directory " + basedir + " is read-only.";
        }

        throw new TransferFailedException(emsg);
    }

    try {
        FileUtils.copyDirectoryStructure(sourceDirectory, path);
    } catch (IOException e) {
        throw new TransferFailedException("Error copying directory structure", e);
    }
}

From source file:org.rhq.plugins.jbossas5.ApplicationServerDiscoveryComponent.java

private Set<DiscoveredResourceDetails> discoverExternalJBossAsProcesses(
        ResourceDiscoveryContext discoveryContext) {
    Set<DiscoveredResourceDetails> resources = new HashSet<DiscoveredResourceDetails>();
    List<ProcessScanResult> autoDiscoveryResults = discoveryContext.getAutoDiscoveredProcesses();

    for (ProcessScanResult autoDiscoveryResult : autoDiscoveryResults) {
        ProcessInfo processInfo = autoDiscoveryResult.getProcessInfo();
        if (log.isDebugEnabled())
            log.debug("Discovered JBoss AS process: " + processInfo);

        JBossInstanceInfo cmdLine;//from ww  w .  j av a2s .  c om
        try {
            cmdLine = new JBossInstanceInfo(processInfo);
        } catch (Exception e) {
            log.error("Failed to process JBoss AS command line: " + Arrays.asList(processInfo.getCommandLine()),
                    e);
            continue;
        }

        // Skip it if it's an AS/EAP/SOA-P version we don't support.
        JBossInstallationInfo installInfo = cmdLine.getInstallInfo();
        if (!isSupportedProduct(installInfo)) {
            continue;
        }

        File installHome = new File(cmdLine.getSystemProperties().getProperty(JBossProperties.HOME_DIR));
        File configDir = new File(cmdLine.getSystemProperties().getProperty(JBossProperties.SERVER_HOME_DIR));

        // The config dir might be a symlink - call getCanonicalFile() to resolve it if so, before
        // calling isDirectory() (isDirectory() returns false for a symlink, even if it points at
        // a directory).
        try {
            if (!configDir.getCanonicalFile().isDirectory()) {
                log.warn("Skipping discovery for JBoss AS process " + processInfo
                        + ", because configuration dir '" + configDir
                        + "' does not exist or is not a directory.");
                continue;
            }
        } catch (IOException e) {
            log.error("Skipping discovery for JBoss AS process " + processInfo + ", because configuration dir '"
                    + configDir + "' could not be canonicalized.", e);
            continue;
        }

        Configuration pluginConfiguration = discoveryContext.getDefaultPluginConfiguration();

        // TODO? Set the connection type - local or remote

        // Set the required props...
        String jnpURL = getJnpURL(cmdLine, installHome, configDir);
        PropertySimple namingUrlProp = new PropertySimple(
                ApplicationServerPluginConfigurationProperties.NAMING_URL, jnpURL);
        if (jnpURL == null) {
            namingUrlProp.setErrorMessage("RHQ failed to discover the naming provider URL.");
        }
        pluginConfiguration.put(namingUrlProp);
        pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.HOME_DIR,
                installHome.getAbsolutePath()));
        pluginConfiguration.put(
                new PropertySimple(ApplicationServerPluginConfigurationProperties.SERVER_HOME_DIR, configDir));

        // Set the optional props...
        pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.SERVER_NAME,
                cmdLine.getSystemProperties().getProperty(JBossProperties.SERVER_NAME)));
        pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.BIND_ADDRESS,
                cmdLine.getSystemProperties().getProperty(JBossProperties.BIND_ADDRESS)));

        JBossASDiscoveryUtils.UserInfo userInfo = JBossASDiscoveryUtils.getJmxInvokerUserInfo(configDir);
        if (userInfo != null) {
            pluginConfiguration.put(new PropertySimple(ApplicationServerPluginConfigurationProperties.PRINCIPAL,
                    userInfo.getUsername()));
            pluginConfiguration.put(new PropertySimple(
                    ApplicationServerPluginConfigurationProperties.CREDENTIALS, userInfo.getPassword()));
        }

        String javaHome = processInfo.getEnvironmentVariable(JAVA_HOME_ENV_VAR);
        if (javaHome == null && log.isDebugEnabled()) {
            log.warn("Unable to determine the JAVA_HOME environment variable for the JBoss AS process - "
                    + " the Agent is probably running as a user that does not have access to the AS process's "
                    + " environment.");
        }
        pluginConfiguration
                .put(new PropertySimple(ApplicationServerPluginConfigurationProperties.JAVA_HOME, javaHome));

        initLogEventSourcesConfigProp(configDir, pluginConfiguration);

        DiscoveredResourceDetails resourceDetails = createResourceDetails(discoveryContext, pluginConfiguration,
                processInfo, installInfo);
        resources.add(resourceDetails);
    }
    return resources;
}

From source file:org.apache.hadoop.security.KDiag.java

/**
 * Dump a keytab: list all principals.//from w w  w .jav a  2s . c om
 *
 * @param keytabFile the keytab file
 * @throws IOException IO problems
 */
private void dumpKeytab(File keytabFile) throws IOException {
    title("Examining keytab %s", keytabFile);
    File kt = keytabFile.getCanonicalFile();
    verifyFileIsValid(kt, CAT_KERBEROS, "keytab");
    List<KeytabEntry> entries = Keytab.read(kt).getEntries();
    println("keytab entry count: %d", entries.size());
    for (KeytabEntry entry : entries) {
        EncryptionKey key = entry.getKey();
        println(" %s: version=%d expires=%s encryption=%s", entry.getPrincipalName(), entry.getKeyVersion(),
                entry.getTimeStamp(), key.getKeyType());
    }
    endln();
}

From source file:edu.ku.brc.helpers.ZipFileHelper.java

/**
 * @param zipFile//from w w w.j a v  a 2  s. c  o  m
 * @return
 * @throws ZipException
 * @throws IOException
 */
public List<File> unzipToFiles(final File zipFile) throws ZipException, IOException {
    Vector<File> files = new Vector<File>();

    final int bufSize = 65535;

    File dir = UIRegistry.getAppDataSubDir(Long.toString(System.currentTimeMillis()) + "_zip", true);
    dirsToRemoveList.add(dir);

    File outFile = null;
    FileOutputStream fos = null;
    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            if (zin.available() > 0) {
                outFile = new File(dir.getCanonicalPath() + File.separator + entry.getName());
                fos = new FileOutputStream(outFile);

                byte[] bytes = new byte[bufSize]; // 64k
                int bytesRead = zin.read(bytes, 0, bufSize);
                while (bytesRead > 0) {
                    fos.write(bytes, 0, bytesRead);
                    bytesRead = zin.read(bytes, 0, bufSize);
                }

                files.insertElementAt(outFile.getCanonicalFile(), 0);
            }
            entry = zin.getNextEntry();
        }

    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return files;
}

From source file:gds.net.TFTPServer.java

private void launch(File serverReadDirectory, File serverWriteDirectory) throws IOException {
    log_.println("Starting TFTP Server on port " + port_ + ".  Read directory: " + serverReadDirectory
            + " Write directory: " + serverWriteDirectory + " Server Mode is " + mode_);

    serverReadDirectory_ = serverReadDirectory.getCanonicalFile();
    if (!serverReadDirectory_.exists() || !serverReadDirectory.isDirectory()) {
        throw new IOException("The server read directory " + serverReadDirectory_ + " does not exist");
    }//from   ww  w.  j av  a2 s . c  o  m

    serverWriteDirectory_ = serverWriteDirectory.getCanonicalFile();
    if (!serverWriteDirectory_.exists() || !serverWriteDirectory.isDirectory()) {
        throw new IOException("The server write directory " + serverWriteDirectory_ + " does not exist");
    }

    serverTftp_ = new TFTP();

    // This is the value used in response to each client.
    socketTimeout_ = serverTftp_.getDefaultTimeout();

    // we want the server thread to listen forever.
    serverTftp_.setDefaultTimeout(0);

    serverTftp_.open(port_);

    serverThread = new Thread(this);
    serverThread.setDaemon(true);
    serverThread.start();
}

From source file:org.opennms.upgrade.implementations.JmxRrdMigratorOffline.java

/**
 * Fixes a JMX configuration file.//ww w  . j ava2  s.  c  o  m
 *
 * @param jmxConfigFile the JMX configuration file
 * @throws OnmsUpgradeException the OpenNMS upgrade exception
 */
private void fixJmxConfigurationFile(File jmxConfigFile) throws OnmsUpgradeException {
    try {
        log("Updating JMX metric definitions on %s\n", jmxConfigFile);
        zipFile(jmxConfigFile);
        backupFiles.add(new File(jmxConfigFile.getAbsolutePath() + ZIP_EXT));
        File outputFile = new File(jmxConfigFile.getCanonicalFile() + ".temp");
        FileWriter w = new FileWriter(outputFile);
        Pattern extRegex = Pattern.compile("import-mbeans[>](.+)[<]");
        Pattern aliasRegex = Pattern.compile("alias=\"([^\"]+\\.[^\"]+)\"");
        List<File> externalFiles = new ArrayList<File>();
        LineIterator it = FileUtils.lineIterator(jmxConfigFile);
        while (it.hasNext()) {
            String line = it.next();
            Matcher m = extRegex.matcher(line);
            if (m.find()) {
                externalFiles.add(new File(jmxConfigFile.getParentFile(), m.group(1)));
            }
            m = aliasRegex.matcher(line);
            if (m.find()) {
                String badDs = m.group(1);
                String fixedDs = getFixedDsName(badDs);
                log("  Replacing bad alias %s with %s on %s\n", badDs, fixedDs, line.trim());
                line = line.replaceAll(badDs, fixedDs);
                if (badMetrics.contains(badDs) == false) {
                    badMetrics.add(badDs);
                }
            }
            w.write(line + "\n");
        }
        LineIterator.closeQuietly(it);
        w.close();
        FileUtils.deleteQuietly(jmxConfigFile);
        FileUtils.moveFile(outputFile, jmxConfigFile);
        if (!externalFiles.isEmpty()) {
            for (File configFile : externalFiles) {
                fixJmxConfigurationFile(configFile);
            }
        }
    } catch (Exception e) {
        throw new OnmsUpgradeException("Can't fix " + jmxConfigFile + " because " + e.getMessage(), e);
    }
}

From source file:org.paxle.gui.impl.servlets.ConfigView.java

private void installStyle(IStyleManager styleManager, HttpServletRequest request, Context context)
        throws Exception {

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    @SuppressWarnings("unchecked")
    List<FileItem> items = upload.parseRequest(request);

    // Process the uploaded items
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = iter.next();/*from w w  w. ja  v a 2s .  c  o m*/

        if (!item.isFormField()) {
            if (!item.getFieldName().equals("styleJar")) {
                String errorMsg = String.format("Unknown file-upload field '%s'.", item.getFieldName());
                this.logger.warn(errorMsg);
                context.put("errorMsg", errorMsg);
                continue;
            }

            String fileName = item.getName();
            if (fileName != null) {
                fileName = FilenameUtils.getName(fileName);
            } else {
                String errorMsg = String.format("Fileupload field '%s' has no valid filename.",
                        item.getFieldName());
                this.logger.warn(errorMsg);
                context.put("errorMsg", errorMsg);
                continue;
            }

            // write the bundle to disk
            File targetFile = new File(styleManager.getDataPath(), fileName);
            if (targetFile.exists()) {
                String errorMsg = String.format("Targetfile '%s' already exists.",
                        targetFile.getCanonicalFile().toString());
                this.logger.warn(errorMsg);
                context.put("errorMsg", errorMsg);
                continue;
            }
            item.write(targetFile);

            // cleanup
            item.delete();
        }
    }
}