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:com.cyberway.issue.crawler.frontier.AbstractFrontier.java

public void importRecoverLog(String pathToLog, boolean retainFailures) throws IOException {
    File source = new File(pathToLog);
    if (!source.isAbsolute()) {
        source = new File(getSettingsHandler().getOrder().getController().getDisk(), pathToLog);
    }//from   w w w  . j av a  2  s  .  c  om
    RecoveryJournal.importRecoverLog(source, controller, retainFailures);
}

From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    //Force the use of slf4j logger in all JBoss log uses in this wars context!!!
    jboss = ContainerUtils.isJBoss();//from   www  .j a va 2s . c om
    if (jboss) {
        oldJBoss = ContainerUtils.isOldJBoss();
    }
    if (oldJBoss) {
        System.setProperty("org.jboss.logging.provider", "slf4j");
    }

    failOver = servletContextEvent.getServletContext().getRealPath("/");
    MaintenanceFilter.siteDown.start();
    context = servletContextEvent.getServletContext();

    configManager = new ConfigManager(context);

    Properties cadmiumProperties = configManager.getPropertiesByContext(context, "/WEB-INF/cadmium.properties");

    Properties configProperties = new Properties();
    configProperties = configManager.getSystemProperties();
    configProperties.putAll(cadmiumProperties);

    sharedContentRoot = sharedContextRoot(configProperties, context, log);

    // compute the directory for this application, based on the war name.
    warName = WarUtils.getWarName(context);

    vHostName = getVHostName(context);

    applicationContentRoot = applicationContentRoot(sharedContentRoot, warName, log);

    executor = new ScheduledThreadPoolExecutor(1);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    executor.setKeepAliveTime(5, TimeUnit.MINUTES);
    executor.setMaximumPoolSize(Math.min(Runtime.getRuntime().availableProcessors(), 4));

    configProperties = configManager.appendProperties(configProperties,
            new File(applicationContentRoot, CONFIG_PROPERTIES_FILE));

    configManager.setDefaultProperties(configProperties);
    configManager.setDefaultPropertiesFile(new File(applicationContentRoot, CONFIG_PROPERTIES_FILE));

    try {
        LogUtils.configureLogback(servletContextEvent.getServletContext(), applicationContentRoot,
                getVHostName(servletContextEvent.getServletContext()), log);
    } catch (IOException e) {
        log.error("Failed to reconfigure logging", e);
    }

    if ((sshDir = getSshDir(configProperties, sharedContentRoot, log)) != null) {
        GitService.setupSsh(sshDir.getAbsolutePath());
    }

    String repoDir = servletContextEvent.getServletContext().getInitParameter("repoDir");
    if (repoDir != null && repoDir.trim().length() > 0) {
        this.repoDir = repoDir;
    }
    String contentDir = servletContextEvent.getServletContext().getInitParameter("contentDir");
    if (contentDir != null && contentDir.trim().length() > 0) {
        this.contentDir = contentDir;
    }
    if (configProperties.containsKey(LAST_UPDATED_DIR)) {
        File cntDir = new File(configProperties.getProperty(LAST_UPDATED_DIR));
        if (cntDir.exists() && cntDir.canRead()) {
            this.contentDir = cntDir.getName();
        }
    }
    File repoFile = new File(this.applicationContentRoot, this.repoDir);
    if (repoFile.isDirectory() && repoFile.canWrite()) {
        this.repoDir = repoFile.getAbsoluteFile().getAbsolutePath();
    } else {
        log.warn("The repo directory may not have been initialized yet.");
        this.repoDir = repoFile.getAbsoluteFile().getAbsolutePath();
    }

    File contentFile = new File(this.applicationContentRoot, this.contentDir);
    if (contentFile.exists() && contentFile.isDirectory() && contentFile.canWrite()) {
        this.contentDir = contentFile.getAbsoluteFile().getAbsolutePath();
    } else {
        log.warn("The content directory may not have been initialized yet.");
        this.contentDir = contentFile.getAbsoluteFile().getAbsolutePath();
    }

    String channelCfgUrl = configProperties.getProperty(JGROUPS_CHANNEL_CONFIG_URL);
    //String channelCfgUrl = System.getProperty(JGROUPS_CHANNEL_CONFIG_URL);
    if (channelCfgUrl != null) {
        File channelCfgFile = null;
        URL fileUrl = null;
        try {
            fileUrl = new URL(channelCfgUrl);
        } catch (Exception e) {
            channelCfgFile = new File(channelCfgUrl);
        }
        if (fileUrl == null && channelCfgFile != null) {
            if (!channelCfgFile.isAbsolute() && !channelCfgFile.exists()) {
                channelCfgFile = new File(this.sharedContentRoot, channelCfgUrl);
                if (channelCfgFile.exists()) {
                    this.channelConfigUrl = "file://" + channelCfgFile.getAbsoluteFile().getAbsolutePath();
                }
            } else {
                this.channelConfigUrl = "file://" + channelCfgFile.getAbsoluteFile().getAbsolutePath();
            }
        } else if (fileUrl != null) {
            this.channelConfigUrl = fileUrl.toString();
        }
    }
    Vfs.addDefaultURLTypes(new JBossVfsUrlType());
    reflections = Reflections.collect();
    Module modules[] = new Module[] { createServletModule(), createModule() };
    InternalInjectorCreator guiceCreator = new InternalInjectorCreator().stage(Stage.DEVELOPMENT)
            .addModules(Arrays.asList(modules));
    try {
        injector = guiceCreator.build();

        //injector = Guice.createInjector(createServletModule(), createModule());

        // run the postConstruct methods.
        jsr250Executor = Jsr250Utils.createJsr250Executor(injector, log, Scopes.SINGLETON);
        jsr250Executor.postConstruct();

        super.contextInitialized(servletContextEvent);
        File graphFile = new File(applicationContentRoot, "injector.dot");
        graphGood(graphFile, injector);
    } catch (Throwable t) {
        try {
            log.error("Failed to initialize...", t);
            Method primaryInjector = InternalInjectorCreator.class.getDeclaredMethod("primaryInjector");
            primaryInjector.setAccessible(true);
            injector = (Injector) primaryInjector.invoke(guiceCreator);
            if (injector == null) {
                log.error("Injector must not have been created.");
            } else {
                log.error("Found injector {}", injector);
            }
        } catch (Throwable e) {
            log.error("Failed to retrieve injector that failed to initialize.", e);
        }
        throw new RuntimeException("Failed to Initialize", t);
    }
}

From source file:cc.arduino.utils.ArchiveExtractor.java

public void extract(File archiveFile, File destFolder, int stripPath, boolean overwrite)
        throws IOException, InterruptedException {

    // Folders timestamps must be set at the end of archive extraction
    // (because creating a file in a folder alters the folder's timestamp)
    Map<File, Long> foldersTimestamps = new HashMap<>();

    ArchiveInputStream in = null;//from   w  w  w . ja  va  2s  .  com
    try {

        // Create an ArchiveInputStream with the correct archiving algorithm
        if (archiveFile.getName().endsWith("tar.bz2")) {
            in = new TarArchiveInputStream(new BZip2CompressorInputStream(new FileInputStream(archiveFile)));
        } else if (archiveFile.getName().endsWith("zip")) {
            in = new ZipArchiveInputStream(new FileInputStream(archiveFile));
        } else if (archiveFile.getName().endsWith("tar.gz")) {
            in = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(archiveFile)));
        } else if (archiveFile.getName().endsWith("tar")) {
            in = new TarArchiveInputStream(new FileInputStream(archiveFile));
        } else {
            throw new IOException("Archive format not supported.");
        }

        String pathPrefix = "";

        Map<File, File> hardLinks = new HashMap<>();
        Map<File, Integer> hardLinksMode = new HashMap<>();
        Map<File, String> symLinks = new HashMap<>();
        Map<File, Long> symLinksModifiedTimes = new HashMap<>();

        // Cycle through all the archive entries
        while (true) {
            ArchiveEntry entry = in.getNextEntry();
            if (entry == null) {
                break;
            }

            // Extract entry info
            long size = entry.getSize();
            String name = entry.getName();
            boolean isDirectory = entry.isDirectory();
            boolean isLink = false;
            boolean isSymLink = false;
            String linkName = null;
            Integer mode = null;
            long modifiedTime = entry.getLastModifiedDate().getTime();

            {
                // Skip MacOSX metadata
                // http://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x
                int slash = name.lastIndexOf('/');
                if (slash == -1) {
                    if (name.startsWith("._")) {
                        continue;
                    }
                } else {
                    if (name.substring(slash + 1).startsWith("._")) {
                        continue;
                    }
                }
            }

            // Skip git metadata
            // http://www.unix.com/unix-for-dummies-questions-and-answers/124958-file-pax_global_header-means-what.html
            if (name.contains("pax_global_header")) {
                continue;
            }

            if (entry instanceof TarArchiveEntry) {
                TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                mode = tarEntry.getMode();
                isLink = tarEntry.isLink();
                isSymLink = tarEntry.isSymbolicLink();
                linkName = tarEntry.getLinkName();
            }

            // On the first archive entry, if requested, detect the common path
            // prefix to be stripped from filenames
            if (stripPath > 0 && pathPrefix.isEmpty()) {
                int slash = 0;
                while (stripPath > 0) {
                    slash = name.indexOf("/", slash);
                    if (slash == -1) {
                        throw new IOException("Invalid archive: it must contain a single root folder");
                    }
                    slash++;
                    stripPath--;
                }
                pathPrefix = name.substring(0, slash);
            }

            // Strip the common path prefix when requested
            if (!name.startsWith(pathPrefix)) {
                throw new IOException("Invalid archive: it must contain a single root folder while file " + name
                        + " is outside " + pathPrefix);
            }
            name = name.substring(pathPrefix.length());
            if (name.isEmpty()) {
                continue;
            }
            File outputFile = new File(destFolder, name);

            File outputLinkedFile = null;
            if (isLink) {
                if (!linkName.startsWith(pathPrefix)) {
                    throw new IOException("Invalid archive: it must contain a single root folder while file "
                            + linkName + " is outside " + pathPrefix);
                }
                linkName = linkName.substring(pathPrefix.length());
                outputLinkedFile = new File(destFolder, linkName);
            }
            if (isSymLink) {
                // Symbolic links are referenced with relative paths
                outputLinkedFile = new File(linkName);
                if (outputLinkedFile.isAbsolute()) {
                    System.err.println(I18n.format(tr("Warning: file {0} links to an absolute path {1}"),
                            outputFile, outputLinkedFile));
                    System.err.println();
                }
            }

            // Safety check
            if (isDirectory) {
                if (outputFile.isFile() && !overwrite) {
                    throw new IOException(
                            "Can't create folder " + outputFile + ", a file with the same name exists!");
                }
            } else {
                // - isLink
                // - isSymLink
                // - anything else
                if (outputFile.exists() && !overwrite) {
                    throw new IOException("Can't extract file " + outputFile + ", file already exists!");
                }
            }

            // Extract the entry
            if (isDirectory) {
                if (!outputFile.exists() && !outputFile.mkdirs()) {
                    throw new IOException("Could not create folder: " + outputFile);
                }
                foldersTimestamps.put(outputFile, modifiedTime);
            } else if (isLink) {
                hardLinks.put(outputFile, outputLinkedFile);
                hardLinksMode.put(outputFile, mode);
            } else if (isSymLink) {
                symLinks.put(outputFile, linkName);
                symLinksModifiedTimes.put(outputFile, modifiedTime);
            } else {
                // Create the containing folder if not exists
                if (!outputFile.getParentFile().isDirectory()) {
                    outputFile.getParentFile().mkdirs();
                }
                copyStreamToFile(in, size, outputFile);
                outputFile.setLastModified(modifiedTime);
            }

            // Set file/folder permission
            if (mode != null && !isSymLink && outputFile.exists()) {
                platform.chmod(outputFile, mode);
            }
        }

        for (Map.Entry<File, File> entry : hardLinks.entrySet()) {
            if (entry.getKey().exists() && overwrite) {
                entry.getKey().delete();
            }
            platform.link(entry.getValue(), entry.getKey());
            Integer mode = hardLinksMode.get(entry.getKey());
            if (mode != null) {
                platform.chmod(entry.getKey(), mode);
            }
        }

        for (Map.Entry<File, String> entry : symLinks.entrySet()) {
            if (entry.getKey().exists() && overwrite) {
                entry.getKey().delete();
            }
            platform.symlink(entry.getValue(), entry.getKey());
            entry.getKey().setLastModified(symLinksModifiedTimes.get(entry.getKey()));
        }

    } finally {
        IOUtils.closeQuietly(in);
    }

    // Set folders timestamps
    for (File folder : foldersTimestamps.keySet()) {
        folder.setLastModified(foldersTimestamps.get(folder));
    }
}

From source file:com.planet57.gshell.internal.FileSystemAccessImpl.java

@Override
public File resolveFile(@Nullable File baseDir, @Nullable final String path) throws IOException {
    File userDir = getUserDir();//from w  ww . j av  a  2  s  .c o m

    if (baseDir == null) {
        baseDir = userDir;
    }

    File file;
    if (path == null) {
        file = baseDir;
    } else if (path.startsWith("~")) {
        File userHome = getUserHomeDir();
        file = new File(userHome.getPath() + path.substring(1));
    } else {
        file = new File(path);
    }

    // support paths like "<drive>:" and "/" on windows
    if (OperatingSystem.WINDOWS) {
        if (path != null && path.equals("/")) {
            // Get the current canonical path to access drive root
            String tmp = new File(".").getCanonicalPath().substring(0, 2);
            return new File(tmp + "/").getCanonicalFile();
        }

        String tmp = file.getPath();
        if (tmp.length() == 2 && tmp.charAt(1) == ':') {
            // Have to append "/" on windows it seems to get the right root
            return new File(tmp + "/").getCanonicalFile();
        }
    }

    if (!file.isAbsolute()) {
        file = new File(baseDir, file.getPath());
    }

    return file.getCanonicalFile();
}

From source file:catalina.startup.ContextConfig.java

/**
 * Process the default configuration file, if it exists.
 *//*from w w  w  . ja va2  s.  c  om*/
private void defaultConfig() {

    // Open the default web.xml file, if it exists
    File file = new File(Constants.DefaultWebXml);
    if (!file.isAbsolute())
        file = new File(System.getProperty("catalina.base"), Constants.DefaultWebXml);
    FileInputStream stream = null;
    try {
        stream = new FileInputStream(file.getCanonicalPath());
        stream.close();
        stream = null;
    } catch (FileNotFoundException e) {
        log(sm.getString("contextConfig.defaultMissing"));
        return;
    } catch (IOException e) {
        log(sm.getString("contextConfig.defaultMissing"), e);
        return;
    }

    // Process the default web.xml file
    synchronized (webDigester) {
        try {
            InputSource is = new InputSource("file://" + file.getAbsolutePath());
            stream = new FileInputStream(file);
            is.setByteStream(stream);
            webDigester.setDebug(getDebug());
            if (context instanceof StandardContext)
                ((StandardContext) context).setReplaceWelcomeFiles(true);
            webDigester.clear();
            webDigester.push(context);
            webDigester.parse(is);
        } catch (SAXParseException e) {
            log(sm.getString("contextConfig.defaultParse"), e);
            log(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(),
                    "" + e.getColumnNumber()));
            ok = false;
        } catch (Exception e) {
            log(sm.getString("contextConfig.defaultParse"), e);
            ok = false;
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                log(sm.getString("contextConfig.defaultClose"), e);
            }
        }
    }

}

From source file:org.opennms.ng.dao.support.PropertiesGraphDao.java

/**
 * Create a PrefabGraphTypeDao from the properties file in sourceResource
 * If reloadable is true, add the type's reload call back to each graph,
 * otherwise don't If sourceResource is not a file-based resource, then
 * reloadable should be false NB: I didn't want to get into checking for
 * what the implementation class of Resource is, because that could break
 * in future with new classes and types that do have a File underneath
 * them. This way, it's up to the caller, who *should* be able to make a
 * sensible choice as to whether the resource is reloadable or not.
 *
 * @param type/*from w  ww  . java 2 s.  c o m*/
 * @param sourceResource
 * @param reloadable
 * @return
 */
private PrefabGraphTypeDao createPrefabGraphType(String type, Resource sourceResource, boolean reloadable) {
    InputStream in = null;
    try {
        in = sourceResource.getInputStream();
        Properties properties = new Properties();
        properties.load(in);
        PrefabGraphTypeDao t = new PrefabGraphTypeDao();
        t.setName(type);

        t.setCommandPrefix(getProperty(properties, "command.prefix"));
        t.setOutputMimeType(getProperty(properties, "output.mime"));

        t.setDefaultReport(properties.getProperty("default.report", "none"));

        String includeDirectoryString = properties.getProperty("include.directory");
        t.setIncludeDirectory(includeDirectoryString);

        if (includeDirectoryString != null) {
            Resource includeDirectoryResource;

            File includeDirectoryFile = new File(includeDirectoryString);
            if (includeDirectoryFile.isAbsolute()) {
                includeDirectoryResource = new FileSystemResource(includeDirectoryString);
            } else {
                includeDirectoryResource = sourceResource.createRelative(includeDirectoryString);
            }

            File includeDirectory = includeDirectoryResource.getFile();

            if (includeDirectory.isDirectory()) {
                t.setIncludeDirectoryResource(includeDirectoryResource);
            } else {
                // Just warn; no need to throw a hissy fit or otherwise fail to load
                LOG.warn("includeDirectory '{}' specified in '{}' is not a directory",
                        includeDirectoryFile.getAbsolutePath(), sourceResource.getFilename());
            }
        }

        // Default to 5 minutes; it's up to users to specify a shorter
        // time if they don't mind OpenNMS spamming on that directory
        int interval;
        try {
            interval = Integer.parseInt(properties.getProperty("include.directory.rescan", "300000"));
        } catch (NumberFormatException e) {
            // Default value if one was specified but it wasn't an integer
            interval = 300000;
            LOG.warn(
                    "The property 'include.directory.rescan' in {} was not able to be parsed as an integer.  Defaulting to {}ms",
                    sourceResource, interval, e);
        }

        t.setIncludeDirectoryRescanInterval(interval);

        List<PrefabGraph> graphs = loadPrefabGraphDefinitions(t, properties);

        for (PrefabGraph graph : graphs) {
            //The graphs list may contain nulls; see loadPrefabGraphDefinitions for reasons
            if (graph != null) {
                FileReloadContainer<PrefabGraph> container;
                if (reloadable) {
                    container = new FileReloadContainer<PrefabGraph>(graph, sourceResource, t.getCallback());
                } else {
                    container = new FileReloadContainer<PrefabGraph>(graph);
                }

                t.addPrefabGraph(container);
            }
        }

        //This *must* come after loading the main graph file, to ensure overrides are correct
        this.scanIncludeDirectory(t);
        return t;

    } catch (IOException e) {
        LOG.error("Failed to load prefab graph configuration of type {} from {}", type, sourceResource, e);
        return null;
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:org.apache.catalina.startup.HostConfig.java

/**
 * Check deployment descriptors last modified date.
 *//* w  w w  .  j  av  a2  s.  co m*/
protected void checkContextLastModified() {

    if (!(host instanceof Deployer))
        return;

    Deployer deployer = (Deployer) host;

    String[] contextNames = deployer.findDeployedApps();

    for (int i = 0; i < contextNames.length; i++) {

        String contextName = contextNames[i];
        Context context = deployer.findDeployedApp(contextName);

        if (!(context instanceof Lifecycle))
            continue;

        try {
            DirContext resources = context.getResources();
            if (resources == null) {
                // This can happen if there was an error initializing
                // the context
                continue;
            }
            ResourceAttributes webXmlAttributes = (ResourceAttributes) resources
                    .getAttributes("/WEB-INF/web.xml");
            ResourceAttributes webInfAttributes = (ResourceAttributes) resources.getAttributes("/WEB-INF");
            long newLastModified = webXmlAttributes.getLastModified();
            long webInfLastModified = webInfAttributes.getLastModified();
            Long lastModified = (Long) webXmlLastModified.get(contextName);
            if (lastModified == null) {
                webXmlLastModified.put(contextName, new Long(newLastModified));
            } else {
                if (lastModified.longValue() != newLastModified) {
                    if (newLastModified > (webInfLastModified + 5000)) {
                        webXmlLastModified.remove(contextName);
                        restartContext(context);
                    } else {
                        webXmlLastModified.put(contextName, new Long(newLastModified));
                    }
                }
            }
        } catch (NamingException e) {
            ; // Ignore
        }

        Long lastModified = (Long) contextXmlLastModified.get(contextName);
        String configBase = configBase().getPath();
        String configFileName = context.getConfigFile();
        if (configFileName != null) {
            File configFile = new File(configFileName);
            if (!configFile.isAbsolute()) {
                configFile = new File(System.getProperty("catalina.base"), configFile.getPath());
            }
            long newLastModified = configFile.lastModified();
            if (lastModified == null) {
                contextXmlLastModified.put(contextName, new Long(newLastModified));
            } else {
                if (lastModified.longValue() != newLastModified) {
                    contextXmlLastModified.remove(contextName);
                    String fileName = configFileName;
                    if (fileName.startsWith(configBase)) {
                        fileName = fileName.substring(configBase.length() + 1);
                        try {
                            deployed.remove(fileName);
                            if (host.findChild(contextName) != null) {
                                ((Deployer) host).remove(contextName);
                            }
                        } catch (Throwable t) {
                            log.error(sm.getString("hostConfig.undeployJar.error", fileName), t);
                        }
                        deployApps();
                    }
                }
            }
        }

    }

    // Check for WAR modification
    if (isUnpackWARs()) {
        File appBase = appBase();
        if (!appBase.exists() || !appBase.isDirectory())
            return;
        String files[] = appBase.list();

        for (int i = 0; i < files.length; i++) {
            if (files[i].endsWith(".war")) {
                File dir = new File(appBase, files[i]);
                Long lastModified = (Long) warLastModified.get(files[i]);
                long dirLastModified = dir.lastModified();
                if (lastModified == null) {
                    warLastModified.put(files[i], new Long(dir.lastModified()));
                } else if (dirLastModified > lastModified.longValue()) {
                    // The WAR has been modified: redeploy
                    String expandedDir = files[i];
                    int period = expandedDir.lastIndexOf(".");
                    if (period >= 0)
                        expandedDir = expandedDir.substring(0, period);
                    File expanded = new File(appBase, expandedDir);
                    String contextPath = "/" + expandedDir;
                    if (contextPath.equals("/ROOT"))
                        contextPath = "";
                    if (dirLastModified > expanded.lastModified()) {
                        try {
                            // Undeploy current application
                            deployed.remove(files[i]);
                            deployed.remove(expandedDir + ".xml");
                            if (host.findChild(contextPath) != null) {
                                ((Deployer) host).remove(contextPath, false);
                                ExpandWar.deleteDir(expanded);
                            }
                        } catch (Throwable t) {
                            log.error(sm.getString("hostConfig.undeployJar.error", files[i]), t);
                        }
                        deployApps();
                    }
                    // If deployment was successful, reset 
                    // the last modified values
                    if (host.findChild(contextPath) != null) {
                        webXmlLastModified.remove(contextPath);
                        warLastModified.put(files[i], new Long(dir.lastModified()));
                    }
                }
            }
        }
    }

}

From source file:com.atlassian.jira.functest.framework.AdministrationImpl.java

public File exportDataToFile(final String fileName) {
    final FuncTestTimer timer = TestInformationKit.pullTimer("XML Export");

    final String realFileName = FilenameUtils.getName(fileName);

    log("Backing up data to '" + realFileName + "'");
    tester.gotoPage("secure/admin/XmlBackup!default.jspa");
    tester.setWorkingForm("jiraform");
    tester.setFormElement("filename", realFileName);
    tester.submit();/*from   ww w  .j av  a 2 s .  c  o m*/
    if (new IdLocator(tester, "replace_submit").exists()) {
        tester.setWorkingForm("jiraform");
        tester.submit();
    }

    final String text = StringUtils.stripToNull(new IdLocator(tester, "backup-file").getText());
    if (text == null) {
        Assert.fail("The restore did not redirect to the result page.");
    }
    timer.end();

    final File file = new File(text);
    Assert.assertTrue("Backup returned '" + text + "' which is not an absolute file.", file.isAbsolute());
    return file;
}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#put(String, String,
 *      String, String, java.util.Map)//from  w  w  w .  j  a  v a  2 s  .  co  m
 */
@Override
public boolean put(String localDirectory, String localFile, String remoteDirectory, String remoteFile,
        Map<String, String> optProperties) throws RemoteManagerException {
    checkConnected();

    boolean result = false;
    FileInputStream input = null;
    try {
        File localPathname = new File(localDirectory, localFile);
        if (!localPathname.isAbsolute()) {
            throw new RemoteManagerException("Local pathname (" + localPathname + ") is NOT absolute.");
        }

        input = new FileInputStream(localPathname);
        logger.debug("Uploading local file " + localPathname
                + (remoteDirectory != null ? " to remote directory " + remoteDirectory
                        : " to current remote working directory")
                + "...");

        if (remoteFile != null) {
            logger.debug("Renaming remote file to " + remoteFile);
        }

        if (remoteDirectory != null) {
            changeWorkingDirectory(remoteDirectory);
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.storeFile((remoteFile != null ? remoteFile : localFile), input);

        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            logger.debug("Local file " + localPathname + " uploaded.");
            result = true;
        } else {
            logger.warn("FTP Server NEGATIVE response: ");
            logServerReply(Level.WARN);
        }
        return result;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException exc) {
                logger.warn("Error while closing local file input stream", exc);
            }
        }
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

From source file:org.apache.solr.core.CoreContainer.java

/**
 * Creates a new core based on a descriptor but does not register it.
 *
 * @param dcore a core descriptor//w w  w.  ja  v  a2  s. co  m
 * @return the newly created core
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public SolrCore create(CoreDescriptor dcore) throws ParserConfigurationException, IOException, SAXException {
    // Make the instanceDir relative to the cores instanceDir if not absolute
    File idir = new File(dcore.getInstanceDir());
    if (!idir.isAbsolute()) {
        idir = new File(solrHome, dcore.getInstanceDir());
    }
    String instanceDir = idir.getPath();

    // Initialize the solr config
    SolrResourceLoader solrLoader = null;

    SolrConfig config = null;
    String zkConfigName = null;
    if (zkController == null) {
        solrLoader = new SolrResourceLoader(instanceDir, libLoader,
                getCoreProps(instanceDir, dcore.getPropertiesName(), dcore.getCoreProperties()));
        config = new SolrConfig(solrLoader, dcore.getConfigName(), null);
    } else {
        try {
            String collection = dcore.getCloudDescriptor().getCollectionName();
            zkController.createCollectionZkNode(dcore.getCloudDescriptor());
            // zkController.createCollectionZkNode(collection);
            zkConfigName = zkController.readConfigName(collection);
            if (zkConfigName == null) {
                log.error("Could not find config name for collection:" + collection);
                throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
                        "Could not find config name for collection:" + collection);
            }
            solrLoader = new ZkSolrResourceLoader(instanceDir, zkConfigName, libLoader,
                    getCoreProps(instanceDir, dcore.getPropertiesName(), dcore.getCoreProperties()),
                    zkController);
            config = getSolrConfigFromZk(zkConfigName, dcore.getConfigName(), solrLoader);
        } catch (KeeperException e) {
            log.error("", e);
            throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
        } catch (InterruptedException e) {
            // Restore the interrupted status
            Thread.currentThread().interrupt();
            log.error("", e);
            throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
        }
    }

    IndexSchema schema = null;
    if (indexSchemaCache != null) {
        if (zkController != null) {
            File schemaFile = new File(dcore.getSchemaName());
            if (!schemaFile.isAbsolute()) {
                schemaFile = new File(
                        solrLoader.getInstanceDir() + "conf" + File.separator + dcore.getSchemaName());
            }
            if (schemaFile.exists()) {
                String key = schemaFile.getAbsolutePath() + ":"
                        + new SimpleDateFormat("yyyyMMddHHmmss", Locale.US)
                                .format(new Date(schemaFile.lastModified()));
                schema = indexSchemaCache.get(key);
                if (schema == null) {
                    log.info("creating new schema object for core: " + dcore.name);
                    schema = new IndexSchema(config, dcore.getSchemaName(), null);
                    indexSchemaCache.put(key, schema);
                } else {
                    log.info("re-using schema object for core: " + dcore.name);
                }
            }
        } else {
            // TODO: handle caching from ZooKeeper - perhaps using ZooKeepers versioning
            // Don't like this cache though - how does it empty as last modified changes?
        }
    }
    if (schema == null) {
        if (zkController != null) {
            try {
                schema = getSchemaFromZk(zkConfigName, dcore.getSchemaName(), config, solrLoader);
            } catch (KeeperException e) {
                log.error("", e);
                throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
            } catch (InterruptedException e) {
                // Restore the interrupted status
                Thread.currentThread().interrupt();
                log.error("", e);
                throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
            }
        } else {
            schema = new IndexSchema(config, dcore.getSchemaName(), null);
        }
    }
    String dataDir = null;

    SolrCore core = new SolrCore(dcore.getName(), dataDir, config, schema, dcore);
    return core;
}