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.cloudifysource.rest.controllers.ServiceController.java

private File getJarFileFromDir(File serviceFileOrDir, final File serviceDirectory, final String jarName)
        throws IOException {
    if (!serviceFileOrDir.isAbsolute()) {
        serviceFileOrDir = new File(serviceDirectory, serviceFileOrDir.getPath());
    }// www  . j av  a2 s.co m
    final File destJar = new File(serviceDirectory.getParent(), jarName + ".jar");
    FileUtils.deleteQuietly(destJar);
    if (serviceFileOrDir.isDirectory()) {
        final File jarFile = File.createTempFile(serviceFileOrDir.getName(), ".jar");
        ZipUtils.zip(serviceFileOrDir, jarFile);
        // rename the jar so would appear as 'Absolute pu name' in the
        // deploy folder.
        jarFile.renameTo(destJar);
        jarFile.deleteOnExit();
        return destJar;
    } else if (serviceFileOrDir.isFile()) {
        // rename the jar so would appear as 'Absolute pu name' in the
        // deploy folder.
        serviceFileOrDir.renameTo(destJar);
        return destJar;
    }

    throw new FileNotFoundException("The file " + serviceFileOrDir + " was not found in the service folder");
}

From source file:org.apache.catalina.core.StandardContext.java

/** Get the absolute path to the work dir.
 *  To avoid duplication.// www.j  a  va2 s. c om
 * 
 * @return
 */
public String getWorkPath() {
    File workDir = new File(getWorkDir());
    if (!workDir.isAbsolute()) {
        File catalinaHome = engineBase();
        String catalinaHomePath = null;
        try {
            catalinaHomePath = catalinaHome.getCanonicalPath();
            workDir = new File(catalinaHomePath, getWorkDir());
        } catch (IOException e) {
        }
    }
    return workDir.getAbsolutePath();
}

From source file:org.apache.catalina.core.StandardContext.java

/**
 * Get base path./*from   ww  w  .  j  av  a  2s .  co  m*/
 */
private String getBasePath() {
    String docBase = null;
    Container container = this;
    while (container != null) {
        if (container instanceof Host)
            break;
        container = container.getParent();
    }
    File file = new File(getDocBase());
    if (!file.isAbsolute()) {
        if (container == null) {
            docBase = (new File(engineBase(), getDocBase())).getPath();
        } else {
            // Use the "appBase" property of this container
            String appBase = ((Host) container).getAppBase();
            file = new File(appBase);
            if (!file.isAbsolute())
                file = new File(engineBase(), appBase);
            docBase = (new File(file, getDocBase())).getPath();
        }
    } else {
        docBase = file.getPath();
    }
    return docBase;
}

From source file:org.apache.catalina.core.StandardContext.java

/**
 * Set the appropriate context attribute for our work directory.
 *///from  w ww.j  av  a2  s  . c  o m
private void postWorkDirectory() {

    // Acquire (or calculate) the work directory path
    String workDir = getWorkDir();
    if (workDir == null) {

        // Retrieve our parent (normally a host) name
        String hostName = null;
        String engineName = null;
        String hostWorkDir = null;
        Container parentHost = getParent();
        if (parentHost != null) {
            hostName = parentHost.getName();
            if (parentHost instanceof StandardHost) {
                hostWorkDir = ((StandardHost) parentHost).getWorkDir();
            }
            Container parentEngine = parentHost.getParent();
            if (parentEngine != null) {
                engineName = parentEngine.getName();
            }
        }
        if ((hostName == null) || (hostName.length() < 1))
            hostName = "_";
        if ((engineName == null) || (engineName.length() < 1))
            engineName = "_";

        String temp = getPath();
        if (temp.startsWith("/"))
            temp = temp.substring(1);
        temp = temp.replace('/', '_');
        temp = temp.replace('\\', '_');
        if (temp.length() < 1)
            temp = "_";
        if (hostWorkDir != null) {
            workDir = hostWorkDir + File.separator + temp;
        } else {
            workDir = "work" + File.separator + engineName + File.separator + hostName + File.separator + temp;
        }
        setWorkDir(workDir);
    }

    // Create this directory if necessary
    File dir = new File(workDir);
    if (!dir.isAbsolute()) {
        File catalinaHome = engineBase();
        String catalinaHomePath = null;
        try {
            catalinaHomePath = catalinaHome.getCanonicalPath();
            dir = new File(catalinaHomePath, workDir);
        } catch (IOException e) {
        }
    }
    dir.mkdirs();

    // Set the appropriate servlet context attribute
    getServletContext().setAttribute(Globals.WORK_DIR_ATTR, dir);
    if (getServletContext() instanceof ApplicationContext)
        ((ApplicationContext) getServletContext()).setAttributeReadOnly(Globals.WORK_DIR_ATTR);

}

From source file:org.apache.maven.plugin.javadoc.AbstractJavadocMojo.java

/**
 * @param link not null//from w ww . java2  s.  c  om
 * @return <code>true</code> if the link has a <code>/package-list</code>, <code>false</code> otherwise.
 * @see <a href="http://docs.oracle.com/javase/1.4.2/docs/tooldocs/solaris/javadoc.html#package-list">
 *      package-list spec</a>
 * @since 2.6
 */
private boolean isValidJavadocLink(String link) {
    try {
        URI linkUri;
        if (link.trim().toLowerCase(Locale.ENGLISH).startsWith("http:")
                || link.trim().toLowerCase(Locale.ENGLISH).startsWith("https:")
                || link.trim().toLowerCase(Locale.ENGLISH).startsWith("ftp:")
                || link.trim().toLowerCase(Locale.ENGLISH).startsWith("file:")) {
            linkUri = new URI(link + "/package-list");
        } else {
            // links can be relative paths or files
            File dir = new File(link);
            if (!dir.isAbsolute()) {
                dir = new File(getOutputDirectory(), link);
            }
            if (!dir.isDirectory()) {
                getLog().error("The given File link: " + dir + " is not a dir.");
            }
            linkUri = new File(dir, "package-list").toURI();
        }

        if (!JavadocUtil.isValidPackageList(linkUri.toURL(), settings, validateLinks)) {
            if (getLog().isErrorEnabled()) {
                getLog().error("Invalid link: " + link + "/package-list. Ignored it.");
            }

            return false;
        }

        return true;
    } catch (URISyntaxException e) {
        if (getLog().isErrorEnabled()) {
            getLog().error("Malformed link: " + link + "/package-list. Ignored it.");
        }
        return false;
    } catch (IOException e) {
        if (getLog().isErrorEnabled()) {
            getLog().error("Error fetching link: " + link + "/package-list. Ignored it.");
        }
        return false;
    }
}

From source file:org.apache.catalina.core.StandardContext.java

/**
 * Start this Context component.//from  w w w. j ava2s .  c o  m
 *
 * @exception LifecycleException if a startup error occurs
 */
public synchronized void start() throws LifecycleException {
    //if (lazy ) return;
    if (started) {
        log.info(sm.getString("containerBase.alreadyStarted", logName()));
        return;
    }
    if (!initialized) {
        try {
            init();
        } catch (Exception ex) {
            throw new LifecycleException("Error initializaing ", ex);
        }
    }

    String logName = "tomcat." + getParent().getName() + "." + ("".equals(getName()) ? "ROOT" : getName())
            + ".Context";
    log = org.apache.commons.logging.LogFactory.getLog(logName);

    log.debug("Starting " + logName);

    // Set JMX object name for proper pipeline registration
    preRegisterJMX();

    if ((oname != null) && (Registry.getRegistry().getMBeanServer().isRegistered(oname))) {
        // As things depend on the JMX registration, the context
        // must be reregistered again once properly initialized
        Registry.getRegistry().unregisterComponent(oname);
    }

    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);

    setAvailable(false);
    setConfigured(false);
    boolean ok = true;

    // Set config file name
    File configBase = getConfigBase();
    if (configBase != null) {
        if (getConfigFile() == null) {
            File file = new File(configBase, getDefaultConfigFile());
            setConfigFile(file.getPath());
            // If the docbase is outside the appBase, we should save our
            // config
            try {
                File appBaseFile = new File(getAppBase());
                if (!appBaseFile.isAbsolute()) {
                    appBaseFile = new File(engineBase(), getAppBase());
                }
                String appBase = appBaseFile.getCanonicalPath();
                String basePath = (new File(getBasePath())).getCanonicalPath();
                if (!basePath.startsWith(appBase)) {
                    Server server = ServerFactory.getServer();
                    ((StandardServer) server).storeContext(this);
                }
            } catch (Exception e) {
                log.warn("Error storing config file", e);
            }
        } else {
            try {
                String canConfigFile = (new File(getConfigFile())).getCanonicalPath();
                if (!canConfigFile.startsWith(configBase.getCanonicalPath())) {
                    File file = new File(configBase, getDefaultConfigFile());
                    if (copy(new File(canConfigFile), file)) {
                        setConfigFile(file.getPath());
                    }
                }
            } catch (Exception e) {
                log.warn("Error setting config file", e);
            }
        }
    }

    // Install DefaultContext configuration
    if (!getOverride()) {
        Container host = getParent();
        if (host instanceof StandardHost) {
            ((StandardHost) host).installDefaultContext(this);
            Container engine = host.getParent();
            if (engine instanceof StandardEngine) {
                ((StandardEngine) engine).installDefaultContext(this);
            }
        }
    }

    // Add missing components as necessary
    if (webappResources == null) { // (1) Required by Loader
        if (log.isDebugEnabled())
            log.debug("Configuring default Resources");
        try {
            if ((docBase != null) && (docBase.endsWith(".war")))
                setResources(new WARDirContext());
            else
                setResources(new FileDirContext());
        } catch (IllegalArgumentException e) {
            log.error("Error initializing resources: " + e.getMessage());
            ok = false;
        }
    }
    if (ok) {
        if (!resourcesStart()) {
            log.error("Error in resourceStart()");
            ok = false;
        }
    }

    // Look for a realm - that may have been configured earlier. 
    // If the realm is added after context - it'll set itself.
    if (realm == null) {
        ObjectName realmName = null;
        try {
            realmName = new ObjectName(
                    getEngineName() + ":type=Host,host=" + getHostname() + ",path=" + getPath());
            if (mserver.isRegistered(realmName)) {
                mserver.invoke(realmName, "init", new Object[] {}, new String[] {});
            }
        } catch (Throwable t) {
            log.debug("No realm for this host " + realmName);
        }
    }

    if (getLoader() == null) {
        ClassLoader parent = null;
        if (getPrivileged()) {
            if (log.isDebugEnabled())
                log.debug("Configuring privileged default Loader");
            parent = this.getClass().getClassLoader();
        } else {
            if (log.isDebugEnabled())
                log.debug("Configuring non-privileged default Loader");
            parent = getParentClassLoader();
        }
        WebappLoader webappLoader = new WebappLoader(parent);
        webappLoader.setDelegate(getDelegate());
        setLoader(webappLoader);
    }

    // Initialize character set mapper
    getCharsetMapper();

    // Post work directory
    postWorkDirectory();

    // Validate required extensions
    boolean dependencyCheck = true;
    try {
        ExtensionValidator validator = ExtensionValidator.getInstance();
        dependencyCheck = validator.validateApplication(getResources(), this);
    } catch (IOException ioe) {
        log.error("Error in dependencyCheck", ioe);
        dependencyCheck = false;
    }

    if (!dependencyCheck) {
        // do not make application available if depency check fails
        ok = false;
    }

    // Reading the "catalina.useNaming" environment variable
    String useNamingProperty = System.getProperty("catalina.useNaming");
    if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) {
        useNaming = false;
    }

    if (ok && isUseNaming()) {
        if (namingContextListener == null) {
            namingContextListener = new NamingContextListener();
            namingContextListener.setDebug(getDebug());
            namingContextListener.setName(getNamingContextName());
            addLifecycleListener(namingContextListener);
        }
    }

    // Binding thread
    ClassLoader oldCCL = bindThread();

    // Standard container startup
    if (log.isDebugEnabled())
        log.debug("Processing standard container startup");

    if (ok) {

        boolean mainOk = false;
        try {

            started = true;

            // Start our subordinate components, if any
            if ((loader != null) && (loader instanceof Lifecycle))
                ((Lifecycle) loader).start();
            if ((logger != null) && (logger instanceof Lifecycle))
                ((Lifecycle) logger).start();

            // Unbinding thread
            unbindThread(oldCCL);

            // Binding thread
            oldCCL = bindThread();

            if ((cluster != null) && (cluster instanceof Lifecycle))
                ((Lifecycle) cluster).start();
            if ((realm != null) && (realm instanceof Lifecycle))
                ((Lifecycle) realm).start();
            if ((resources != null) && (resources instanceof Lifecycle))
                ((Lifecycle) resources).start();

            // Start our child containers, if any
            Container children[] = findChildren();
            for (int i = 0; i < children.length; i++) {
                if (children[i] instanceof Lifecycle)
                    ((Lifecycle) children[i]).start();
            }

            // Start the Valves in our pipeline (including the basic),
            // if any
            if (pipeline instanceof Lifecycle)
                ((Lifecycle) pipeline).start();

            // Read tldListeners. XXX Option to disable
            TldConfig tldConfig = new TldConfig();
            tldConfig.setContext(this);
            tldConfig.setXmlValidation(((StandardHost) getParent()).getXmlValidation());
            tldConfig.setXmlNamespaceAware(((StandardHost) getParent()).getXmlNamespaceAware());
            try {
                tldConfig.execute();
            } catch (Exception ex) {
                log.error("Error reading tld listeners " + ex.toString(), ex);
                //ok=false;
            }

            // Notify our interested LifecycleListeners
            lifecycle.fireLifecycleEvent(START_EVENT, null);

            // Start manager
            if ((manager != null) && (manager instanceof Lifecycle)) {
                ((Lifecycle) getManager()).start();
            }

            // Start ContainerBackgroundProcessor thread
            super.threadStart();

            mainOk = true;

        } finally {
            // Unbinding thread
            unbindThread(oldCCL);
            if (!mainOk) {
                // An exception occurred
                // Register with JMX anyway, to allow management
                registerJMX();
            }
        }

    }
    if (!getConfigured()) {
        log.error("Error getConfigured");
        ok = false;
    }

    // We put the resources into the servlet context
    if (ok)
        getServletContext().setAttribute(Globals.RESOURCES_ATTR, getResources());

    // Binding thread
    oldCCL = bindThread();

    // Create context attributes that will be required
    if (ok) {
        if (log.isDebugEnabled())
            log.debug("Posting standard context attributes");
        postWelcomeFiles();
    }

    // Configure and call application event listeners and filters
    if (ok) {
        if (!listenerStart()) {
            log.error("Error listenerStart");
            ok = false;
        }
    }
    if (ok) {
        if (!filterStart()) {
            log.error("Error filterStart");
            ok = false;
        }
    }

    // Load and initialize all "load on startup" servlets
    if (ok) {
        loadOnStartup(findChildren());
    }

    // Unbinding thread
    unbindThread(oldCCL);

    // Initialize associated mapper
    mapper.setContext(getPath(), welcomeFiles, resources);

    // Set available status depending upon startup success
    if (ok) {
        if (log.isDebugEnabled())
            log.debug("Starting completed");
        setAvailable(true);
    } else {
        log.error(sm.getString("standardContext.startFailed"));
        try {
            stop();
        } catch (Throwable t) {
            log.error(sm.getString("standardContext.startCleanup"), t);
        }
        setAvailable(false);
    }

    // JMX registration
    registerJMX();

    if (ok) {
        // Notify our interested LifecycleListeners
        lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
    }

    startTime = System.currentTimeMillis();

    // Send j2ee.state.running notification 
    if (ok && (this.getObjectName() != null)) {
        Notification notification = new Notification("j2ee.state.running", this.getObjectName(),
                sequenceNumber++);
        broadcaster.sendNotification(notification);
    }

    // Close all JARs right away to avoid always opening a peak number 
    // of files on startup
    if (getLoader() instanceof WebappLoader) {
        ((WebappLoader) getLoader()).closeJARs(true);
    }

    // Reinitializing if something went wrong
    if (!ok && started) {
        stop();
    }

    //cacheContext();
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public File getOrCreateWGAFolder(String fileName) {

    // Path variables
    fileName = replaceWGAPathVariables(fileName);

    // Dir links/* w w  w.j  ava 2 s  .c  o m*/
    File file = WGUtils.resolveDirLink(new File(fileName));

    // First try: Use as absolute path
    if (file.exists()) {
        return file;
    } else if (file.isAbsolute()) {
        file.mkdir();
        if (file.exists() && file.isDirectory()) {
            return file;
        } else {
            return null;
        }
    }

    // Second try: Find inside wgaconfig path
    File wgaConfigPath = configFile.getParentFile();
    file = new File(wgaConfigPath, fileName);
    if (file.exists()) {
        return file;
    } else {
        file.mkdir();
        if (file.exists() && file.isDirectory()) {
            return file;
        } else {
            return null;
        }
    }
}

From source file:com.processing.core.PApplet.java

/**
 * Similar to createInput() (formerly openStream), this creates a Java
 * OutputStream for a given filename or path. The file will be created in
 * the sketch folder, or in the same folder as an exported application.
 * <p/>//from  w ww  . j av  a2  s .  c  o  m
 * If the path does not exist, intermediate folders will be created. If an
 * exception occurs, it will be printed to the console, and null will be
 * returned.
 * <p/>
 * Future releases may also add support for handling HTTP POST via this
 * method (for better symmetry with createInput), however that's maybe a
 * little too clever (and then we'd have to add the same features to the
 * other file functions like createWriter). Who you callin' bloated?
 */
public OutputStream createOutput(String filename) {
    try {
        // in spite of appearing to be the 'correct' option, this doesn't allow
        // for paths, so no subfolders, none of that savePath() goodness.
        //      Context context = getApplicationContext();
        //      // MODE_PRIVATE is default, should we use that instead?
        //      return context.openFileOutput(filename, MODE_WORLD_READABLE);

        File file = new File(filename);
        if (!file.isAbsolute()) {
            file = new File(sketchPath(filename));
        }
        FileOutputStream fos = new FileOutputStream(file);
        if (file.getName().toLowerCase().endsWith(".gz")) {
            return new GZIPOutputStream(fos);
        }
        return fos;

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:processing.core.PApplet.java

/**
 * Similar to createInput() (formerly openStream), this creates a Java
 * OutputStream for a given filename or path. The file will be created in
 * the sketch folder, or in the same folder as an exported application.
 * <p/>//w ww .ja va 2 s  .co m
 * If the path does not exist, intermediate folders will be created. If an
 * exception occurs, it will be printed to the console, and null will be
 * returned.
 * <p/>
 * Future releases may also add support for handling HTTP POST via this
 * method (for better symmetry with createInput), however that's maybe a
 * little too clever (and then we'd have to add the same features to the
 * other file functions like createWriter). Who you callin' bloated?
 */
public OutputStream createOutput(String filename) {
    try {
        // in spite of appearing to be the 'correct' option, this doesn't
        // allow
        // for paths, so no subfolders, none of that savePath() goodness.
        // Context context = getApplicationContext();
        // // MODE_PRIVATE is default, should we use that instead?
        // return context.openFileOutput(filename, MODE_WORLD_READABLE);

        File file = new File(filename);
        if (!file.isAbsolute()) {
            file = new File(sketchPath(filename));
        }
        FileOutputStream fos = new FileOutputStream(file);
        if (file.getName().toLowerCase().endsWith(".gz")) {
            return new GZIPOutputStream(fos);
        }
        return fos;

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}