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.cocoon.servlet.CocoonServlet.java

/**
 * Initialize this <code>CocoonServlet</code> instance.  You will
 * notice that I have broken the init into sub methods to make it
 * easier to maintain (BL).  The context is passed to a couple of
 * the subroutines.  This is also because it is better to explicitly
 * pass variables than implicitely.  It is both more maintainable,
 * and more elegant.//from  www  .j  a  v a2  s .com
 *
 * @param conf The ServletConfig object from the servlet engine.
 *
 * @throws ServletException
 */
public void init(ServletConfig conf) throws ServletException {

    super.init(conf);

    // Check the init-classloader parameter only if it's not already true.
    // This is useful for subclasses of this servlet that override the value
    // initially set by this class (i.e. false).
    if (!this.initClassLoader) {
        this.initClassLoader = getInitParameterAsBoolean("init-classloader", false);
    }

    if (this.initClassLoader) {
        // Force context classloader so that JAXP can work correctly
        // (see javax.xml.parsers.FactoryFinder.findClassLoader())
        try {
            Thread.currentThread().setContextClassLoader(this.classLoader);
        } catch (Exception e) {
            // ignore this
        }
    }

    try {
        // FIXME (VG): We shouldn't have to specify these. Need to override
        // jaxp implementation of weblogic before initializing logger.
        // This piece of code is also required in the Cocoon class.
        String value = System.getProperty("javax.xml.parsers.SAXParserFactory");
        if (value != null && value.startsWith("weblogic")) {
            System.setProperty("javax.xml.parsers.SAXParserFactory",
                    "org.apache.xerces.jaxp.SAXParserFactoryImpl");
            System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                    "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
        }
    } catch (Exception e) {
        // Ignore security exception
        System.out.println("CocoonServlet: Could not check system properties, got: " + e);
    }

    this.servletContext = conf.getServletContext();
    this.appContext.put(Constants.CONTEXT_ENVIRONMENT_CONTEXT, new HttpContext(this.servletContext));
    this.servletContextPath = this.servletContext.getRealPath("/");

    // first init the work-directory for the logger.
    // this is required if we are running inside a war file!
    final String workDirParam = getInitParameter("work-directory");
    if (workDirParam != null) {
        if (this.servletContextPath == null) {
            // No context path : consider work-directory as absolute
            this.workDir = new File(workDirParam);
        } else {
            // Context path exists : is work-directory absolute ?
            File workDirParamFile = new File(workDirParam);
            if (workDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.workDir = workDirParamFile;
            } else {
                // No : consider it relative to context path
                this.workDir = new File(servletContextPath, workDirParam);
            }
        }
    } else {
        this.workDir = (File) this.servletContext.getAttribute("javax.servlet.context.tempdir");
        this.workDir = new File(workDir, "cocoon-files");
    }
    this.workDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_WORK_DIR, workDir);

    String path = this.servletContextPath;
    // these two variables are just for debugging. We can't log at this point
    // as the logger isn't initialized yet.
    String debugPathOne = null, debugPathTwo = null;
    if (path == null) {
        // Try to figure out the path of the root from that of WEB-INF
        try {
            path = this.servletContext.getResource("/WEB-INF").toString();
        } catch (MalformedURLException me) {
            throw new ServletException("Unable to get resource 'WEB-INF'.", me);
        }
        debugPathOne = path;
        path = path.substring(0, path.length() - "WEB-INF".length());
        debugPathTwo = path;
    }
    try {
        if (path.indexOf(':') > 1) {
            this.servletContextURL = path;
        } else {
            this.servletContextURL = new File(path).toURL().toExternalForm();
        }
    } catch (MalformedURLException me) {
        // VG: Novell has absolute file names starting with the
        // volume name which is easily more then one letter.
        // Examples: sys:/apache/cocoon or sys:\apache\cocoon
        try {
            this.servletContextURL = new File(path).toURL().toExternalForm();
        } catch (MalformedURLException ignored) {
            throw new ServletException("Unable to determine servlet context URL.", me);
        }
    }
    try {
        this.appContext.put("context-root", new URL(this.servletContextURL));
    } catch (MalformedURLException ignore) {
        // we simply ignore this
    }

    // Init logger
    initLogger();

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("getRealPath for /: " + this.servletContextPath);
        if (this.servletContextPath == null) {
            getLogger().debug("getResource for /WEB-INF: " + debugPathOne);
            getLogger().debug("Path for Root: " + debugPathTwo);
        }
    }

    this.forceLoadParameter = getInitParameter("load-class", null);
    this.forceSystemProperty = getInitParameter("force-property", null);

    // Output some debug info
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Servlet Context URL: " + this.servletContextURL);
        if (workDirParam != null) {
            getLogger().debug("Using work-directory " + this.workDir);
        } else {
            getLogger().debug("Using default work-directory " + this.workDir);
        }
    }

    final String uploadDirParam = conf.getInitParameter("upload-directory");
    if (uploadDirParam != null) {
        if (this.servletContextPath == null) {
            this.uploadDir = new File(uploadDirParam);
        } else {
            // Context path exists : is upload-directory absolute ?
            File uploadDirParamFile = new File(uploadDirParam);
            if (uploadDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.uploadDir = uploadDirParamFile;
            } else {
                // No : consider it relative to context path
                this.uploadDir = new File(servletContextPath, uploadDirParam);
            }
        }
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using upload-directory " + this.uploadDir);
        }
    } else {
        this.uploadDir = new File(workDir, "upload-dir" + File.separator);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using default upload-directory " + this.uploadDir);
        }
    }
    this.uploadDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_UPLOAD_DIR, this.uploadDir);

    this.enableUploads = getInitParameterAsBoolean("enable-uploads", ENABLE_UPLOADS);

    this.autoSaveUploads = getInitParameterAsBoolean("autosave-uploads", SAVE_UPLOADS_TO_DISK);

    String overwriteParam = getInitParameter("overwrite-uploads", "rename");
    // accepted values are deny|allow|rename - rename is default.
    if ("deny".equalsIgnoreCase(overwriteParam)) {
        this.allowOverwrite = false;
        this.silentlyRename = false;
    } else if ("allow".equalsIgnoreCase(overwriteParam)) {
        this.allowOverwrite = true;
        this.silentlyRename = false; // ignored in this case
    } else {
        // either rename is specified or unsupported value - default to rename.
        this.allowOverwrite = false;
        this.silentlyRename = true;
    }

    this.maxUploadSize = getInitParameterAsInteger("upload-max-size", MAX_UPLOAD_SIZE);

    String cacheDirParam = conf.getInitParameter("cache-directory");
    if (cacheDirParam != null) {
        if (this.servletContextPath == null) {
            this.cacheDir = new File(cacheDirParam);
        } else {
            // Context path exists : is cache-directory absolute ?
            File cacheDirParamFile = new File(cacheDirParam);
            if (cacheDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.cacheDir = cacheDirParamFile;
            } else {
                // No : consider it relative to context path
                this.cacheDir = new File(servletContextPath, cacheDirParam);
            }
        }
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using cache-directory " + this.cacheDir);
        }
    } else {
        this.cacheDir = IOUtils.createFile(workDir, "cache-dir" + File.separator);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("cache-directory was not set - defaulting to " + this.cacheDir);
        }
    }
    this.cacheDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_CACHE_DIR, this.cacheDir);

    this.appContext.put(Constants.CONTEXT_CONFIG_URL, getConfigFile(conf.getInitParameter("configurations")));
    if (conf.getInitParameter("configurations") == null) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("configurations was not set - defaulting to... ?");
        }
    }

    // get allow reload parameter, default is true
    this.allowReload = getInitParameterAsBoolean("allow-reload", ALLOW_RELOAD);

    String value = conf.getInitParameter("show-time");
    this.showTime = BooleanUtils.toBoolean(value) || (this.hiddenShowTime = "hide".equals(value));
    if (value == null) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("show-time was not set - defaulting to false");
        }
    }

    this.showCocoonVersion = getInitParameterAsBoolean("show-cocoon-version", true);

    parentComponentManagerClass = getInitParameter("parent-component-manager", null);
    if (parentComponentManagerClass != null) {
        int dividerPos = parentComponentManagerClass.indexOf('/');
        if (dividerPos != -1) {
            parentComponentManagerInitParam = parentComponentManagerClass.substring(dividerPos + 1);
            parentComponentManagerClass = parentComponentManagerClass.substring(0, dividerPos);
        }
    }

    this.containerEncoding = getInitParameter("container-encoding", "ISO-8859-1");
    this.defaultFormEncoding = getInitParameter("form-encoding", "ISO-8859-1");
    this.appContext.put(Constants.CONTEXT_DEFAULT_ENCODING, this.defaultFormEncoding);

    this.manageExceptions = getInitParameterAsBoolean("manage-exceptions", true);

    this.enableInstrumentation = getInitParameterAsBoolean("enable-instrumentation", false);

    this.requestFactory = new RequestFactory(this.autoSaveUploads, this.uploadDir, this.allowOverwrite,
            this.silentlyRename, this.maxUploadSize, this.containerEncoding);
    // Add the servlet configuration
    this.appContext.put(CONTEXT_SERVLET_CONFIG, conf);
    this.createCocoon();
}

From source file:adalid.commons.velocity.Writer.java

private void executeFile(VelocityContext fileContext, File templatePropertiesFile) {
    Properties properties = mergeProperties(fileContext, templatePropertiesFile);
    String command = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_COMMAND));
    String directory = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_DIRECTORY));
    if (command != null) {
        StrTokenizer tokenizer = new StrTokenizer(command);
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(tokenizer.getTokenArray());
        if (directory != null) {
            File dir = new File(directory);
            if (dir.exists() && dir.isDirectory()) {
                if (dir.isAbsolute()) {
                    processBuilder.directory(dir);
                } else {
                    processBuilder.directory(dir.getAbsoluteFile());
                }/*  w  ww .  ja va2s.com*/
            }
        }
        try {
            Process process = processBuilder.start();
            int w = process.waitFor();
            int x = process.exitValue();
            logger.info(command + " = " + w + "," + x);
        } catch (IOException | InterruptedException ex) {
            error(ex);
        }
    }
}

From source file:com.cyberway.issue.crawler.framework.CrawlController.java

/**
 * Return fullpath to the directory named by <code>key</code>
 * in settings./*  w ww .  j a  v  a 2s  . com*/
 * If directory does not exist, it and all intermediary dirs
 * will be created.
 * @param key Key to use going to settings.
 * @return Full path to directory named by <code>key</code>.
 * @throws AttributeNotFoundException
 */
public File getSettingsDir(String key) throws AttributeNotFoundException {
    String path = (String) order.getAttribute(null, key);
    File f = new File(path);
    if (!f.isAbsolute()) {
        f = new File(disk.getPath(), path);
    }
    if (!f.exists()) {
        f.mkdirs();
    }
    return f;
}

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

/** 
 * The action of the JAR name field.//from   w w w . ja  v  a 2 s .c o  m
 * @return <code>null</code> if the new value is valid. Otherwise, returns
 *         a status parameter indicating the cause of the problem.
 */
DialogStatusParameter modifyJarFieldAction() {

    DialogStatusParameter error = null;
    boolean isEmpty = m_jarTextField.getText().length() == 0;
    if (isValid(m_jarTextField, true) && !isEmpty) {
        if (checkLocalhostServer()) {
            String filename = m_jarTextField.getText();
            File file = new File(filename);
            String workingDir = StringUtils.defaultString(getConfigValue(AutConfigConstants.WORKING_DIR));
            if (!file.isAbsolute() && workingDir.length() != 0) {

                filename = workingDir + "/" + filename; //$NON-NLS-1$
                file = new File(filename);
            }
            try {
                if (!file.exists()) {
                    error = createWarningStatus(
                            NLS.bind(Messages.AUTConfigComponentFileNotFound, file.getCanonicalPath()));
                } else {
                    JarFile jarFile = new JarFile(file);
                    Manifest jarManifest = jarFile.getManifest();
                    if (jarManifest == null) {
                        // no manifest for JAR
                        error = createErrorStatus(Messages.AUTConfigComponentNoManifest);
                    } else if (jarManifest.getMainAttributes().getValue(MAIN_CLASS) == null) {

                        // no main class defined in JAR manifest
                        error = createErrorStatus(Messages.AUTConfigComponentNoMainClass);
                    }
                }
            } catch (ZipException ze) {
                // given file is not a jar file
                error = createErrorStatus(NLS.bind(Messages.AUTConfigComponentFileNotJar, filename));
            } catch (IOException e) {
                // could not find jar file
                error = createWarningStatus(NLS.bind(Messages.AUTConfigComponentFileNotFound, filename));
            }
        }
    } else if (!isEmpty) {
        error = createErrorStatus(Messages.AUTConfigComponentWrongJAR);
    }

    putConfigValue(AutConfigConstants.JAR_FILE, m_jarTextField.getText());

    return error;
}

From source file:org.apache.sysml.parser.pydml.PydmlSyntacticValidator.java

@Override
public void exitImportStatement(ImportStatementContext ctx) {
    //prepare import filepath
    String filePath = ctx.filePath.getText();
    String namespace = DMLProgram.DEFAULT_NAMESPACE;
    if (ctx.namespace != null && ctx.namespace.getText() != null && !ctx.namespace.getText().isEmpty()) {
        namespace = ctx.namespace.getText();
    }//w w w .  j  a v  a 2  s  . com
    if ((filePath.startsWith("\"") && filePath.endsWith("\""))
            || filePath.startsWith("'") && filePath.endsWith("'")) {
        filePath = filePath.substring(1, filePath.length() - 1);
    }

    File file = new File(filePath);
    if (!file.isAbsolute()) {
        //concatenate working directory to filepath
        filePath = _workingDir + File.separator + filePath;
    }
    validateNamespace(namespace, filePath, ctx);
    String scriptID = DMLProgram.constructFunctionKey(namespace, filePath);

    DMLProgram prog = null;
    if (!_scripts.get().containsKey(scriptID)) {
        _scripts.get().put(scriptID, namespace);
        try {
            prog = (new PyDMLParserWrapper()).doParse(filePath, null, getQualifiedNamespace(namespace),
                    argVals);
        } catch (ParseException e) {
            notifyErrorListeners(e.getMessage(), ctx.start);
            return;
        }
        // Custom logic whether to proceed ahead or not. Better than the current exception handling mechanism
        if (prog == null) {
            notifyErrorListeners("One or more errors found during importing a program from file " + filePath,
                    ctx.start);
            return;
        } else {
            ctx.info.namespaces = new HashMap<String, DMLProgram>();
            ctx.info.namespaces.put(getQualifiedNamespace(namespace), prog);
            ctx.info.stmt = new ImportStatement();
            ((ImportStatement) ctx.info.stmt).setCompletePath(filePath);
            ((ImportStatement) ctx.info.stmt).setFilePath(ctx.filePath.getText());
            ((ImportStatement) ctx.info.stmt).setNamespace(namespace);
        }
    } else {
        // Skip redundant parsing (to prevent potential infinite recursion) and
        // create empty program for this context to allow processing to continue.
        prog = new DMLProgram();
        ctx.info.namespaces = new HashMap<String, DMLProgram>();
        ctx.info.namespaces.put(getQualifiedNamespace(namespace), prog);
        ctx.info.stmt = new ImportStatement();
        ((ImportStatement) ctx.info.stmt).setCompletePath(filePath);
        ((ImportStatement) ctx.info.stmt).setFilePath(ctx.filePath.getText());
        ((ImportStatement) ctx.info.stmt).setNamespace(namespace);
    }
}

From source file:com.eviware.soapui.impl.wsdl.WsdlProject.java

protected File getBackupFile(File projectFile) {
    String backupFolderName = getSettings().getString(UISettings.BACKUP_FOLDER, "");

    File backupFolder = new File(backupFolderName);
    if (!backupFolder.isAbsolute()) {
        backupFolder = new File(projectFile.getParentFile(), backupFolderName);
    }//from  ww  w . ja v  a2s  .co  m

    if (!backupFolder.exists())
        backupFolder.mkdirs();

    File backupFile = new File(backupFolder, projectFile.getName() + ".backup");
    return backupFile;
}

From source file:com.alibaba.citrus.maven.eclipse.base.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  av  a  2 s . c o  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);

            boolean merged = originalDir.merge(resourceDir);
            if (merged) {
                getLog().info(
                        "Resource directory's path matches an existing source directory. Resources have been merged with the source directory "
                                + originalDir.getPath());
            } else {
                getLog().info(
                        "Resource directory's path matches an existing source directory but \"test\", \"filtering\" or \"output\" were different."
                                + "The resulting eclipse configuration may not accurately reflect the project configuration for "
                                + originalDir.getPath());
            }
        }
    }
}

From source file:maspack.fileutil.FileManager.java

/**
 * Uploads a local file to the remote destination if it exists. If dest is null or a
 * directory, appends source filename//  w w  w .  ja va2 s .  c  o m
 * 
 * @param source
 * the source file
 * @param dest
 * the destination uri 
 * @throws FileTransferException
 * if uploading the file fails
 */
public void putRemote(File source, URIx dest) throws FileTransferException {

    // ensure that source is a file, and not a directory
    if (source.isDirectory()) { //|| srcFile.endsWith("/")) {
        throw new IllegalArgumentException("Source file must refer to a file: <" + source + ">");
    }

    if (dest == null) {
        // if source is relative, take that
        if (!source.isAbsolute()) {
            dest = new URIx(source.getPath());
        } else {
            // otherwise, simply extract the file name from source
            dest = new URIx(source.getName());
        }
    } else if (isDirectory(dest)) {
        if (source.isAbsolute()) {
            dest = new URIx(dest, source.getName());
        } else {
            dest = new URIx(dest, source.getPath());
        }
    }

    // make absolute
    dest = getAbsoluteURI(dest);
    source = getAbsoluteFile(source);

    try {
        cacher.initialize();
        logger.debug("Uploading file " + source.getAbsolutePath() + " to " + dest.toString() + "...");
        // download file
        cacher.copy(source, dest, myTransferMonitor);
    } catch (FileSystemException e) {
        String msg = decodeVFSMessage(e);
        throw new FileTransferException(msg, e);
    } finally {
        cacher.release();
    }

}

From source file:org.apache.maven.plugin.invoker.AbstractInvokerMojo.java

/**
 * Relativizes the project paths of the specified build jobs against the directory specified by
 * {@link #projectsDirectory} (if possible). If a project path does not denote a sub path of the projects directory,
 * it is returned as is./*from  w w  w.j a  v  a 2  s  .  co  m*/
 *
 * @param buildJobs The build jobs whose project paths should be relativized, must not be <code>null</code> nor
 *                  contain <code>null</code> elements.
 * @throws java.io.IOException If any path could not be relativized.
 */
private void relativizeProjectPaths(BuildJob[] buildJobs) throws IOException {
    String projectsDirPath = projectsDirectory.getCanonicalPath();

    for (BuildJob buildJob : buildJobs) {
        String projectPath = buildJob.getProject();

        File file = new File(projectPath);

        if (!file.isAbsolute()) {
            file = new File(projectsDirectory, projectPath);
        }

        String relativizedPath = relativizePath(file, projectsDirPath);

        if (relativizedPath == null) {
            relativizedPath = projectPath;
        }

        buildJob.setProject(relativizedPath);
    }
}

From source file:org.apache.cocoon.portlet.CocoonPortlet.java

/**
 * Initialize this <code>CocoonPortlet</code> instance.
 *
 * <p>Uses the following parameters:
 *  portlet-logger//from   www . ja va2  s.  c  o  m
 *  enable-uploads
 *  autosave-uploads
 *  overwrite-uploads
 *  upload-max-size
 *  show-time
 *  container-encoding
 *  form-encoding
 *  manage-exceptions
 *  servlet-path
 *
 * @param conf The PortletConfig object from the portlet container.
 * @throws PortletException
 */
public void init(PortletConfig conf) throws PortletException {

    super.init(conf);

    // Check the init-classloader parameter only if it's not already true.
    // This is useful for subclasses of this portlet that override the value
    // initially set by this class (i.e. false).
    if (!this.initClassLoader) {
        this.initClassLoader = getInitParameterAsBoolean("init-classloader", false);
    }

    if (this.initClassLoader) {
        // Force context classloader so that JAXP can work correctly
        // (see javax.xml.parsers.FactoryFinder.findClassLoader())
        try {
            Thread.currentThread().setContextClassLoader(this.classLoader);
        } catch (Exception e) {
        }
    }

    try {
        // FIXME (VG): We shouldn't have to specify these. Need to override
        // jaxp implementation of weblogic before initializing logger.
        // This piece of code is also required in the Cocoon class.
        String value = System.getProperty("javax.xml.parsers.SAXParserFactory");
        if (value != null && value.startsWith("weblogic")) {
            System.setProperty("javax.xml.parsers.SAXParserFactory",
                    "org.apache.xerces.jaxp.SAXParserFactoryImpl");
            System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                    "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
        }
    } catch (SecurityException e) {
        // Ignore security exception
        System.out.println("CocoonPortlet: Could not check system properties, got: " + e);
    }

    this.portletContext = conf.getPortletContext();
    this.appContext.put(Constants.CONTEXT_ENVIRONMENT_CONTEXT, new PortletContext(this.portletContext));
    this.portletContextPath = this.portletContext.getRealPath("/");

    // first init the work-directory for the logger.
    // this is required if we are running inside a war file!
    final String workDirParam = getInitParameter("work-directory");
    if (workDirParam != null) {
        if (this.portletContextPath == null) {
            // No context path : consider work-directory as absolute
            this.workDir = new File(workDirParam);
        } else {
            // Context path exists : is work-directory absolute ?
            File workDirParamFile = new File(workDirParam);
            if (workDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.workDir = workDirParamFile;
            } else {
                // No : consider it relative to context path
                this.workDir = new File(portletContextPath, workDirParam);
            }
        }
    } else {
        // TODO: Check portlet specification
        this.workDir = (File) this.portletContext.getAttribute("javax.servlet.context.tempdir");
        if (this.workDir == null) {
            this.workDir = new File(this.portletContext.getRealPath("/WEB-INF/work"));
        }
        this.workDir = new File(workDir, "cocoon-files");
    }
    this.workDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_WORK_DIR, workDir);

    String path = this.portletContextPath;
    // these two variables are just for debugging. We can't log at this point
    // as the logger isn't initialized yet.
    String debugPathOne = null, debugPathTwo = null;
    if (path == null) {
        // Try to figure out the path of the root from that of WEB-INF
        try {
            path = this.portletContext.getResource("/WEB-INF").toString();
        } catch (MalformedURLException me) {
            throw new PortletException("Unable to get resource 'WEB-INF'.", me);
        }
        debugPathOne = path;
        path = path.substring(0, path.length() - "WEB-INF".length());
        debugPathTwo = path;
    }

    try {
        if (path.indexOf(':') > 1) {
            this.portletContextURL = path;
        } else {
            this.portletContextURL = new File(path).toURL().toExternalForm();
        }
    } catch (MalformedURLException me) {
        // VG: Novell has absolute file names starting with the
        // volume name which is easily more then one letter.
        // Examples: sys:/apache/cocoon or sys:\apache\cocoon
        try {
            this.portletContextURL = new File(path).toURL().toExternalForm();
        } catch (MalformedURLException ignored) {
            throw new PortletException("Unable to determine portlet context URL.", me);
        }
    }
    try {
        this.appContext.put("context-root", new URL(this.portletContextURL));
    } catch (MalformedURLException ignore) {
        // we simply ignore this
    }

    // Init logger
    initLogger();

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("getRealPath for /: " + this.portletContextPath);
        if (this.portletContextPath == null) {
            getLogger().debug("getResource for /WEB-INF: " + debugPathOne);
            getLogger().debug("Path for Root: " + debugPathTwo);
        }
    }

    this.forceLoadParameter = getInitParameter("load-class", null);
    this.forceSystemProperty = getInitParameter("force-property", null);

    // Output some debug info
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Portlet Context URL: " + this.portletContextURL);
        if (workDirParam != null) {
            getLogger().debug("Using work-directory " + this.workDir);
        } else {
            getLogger().debug("Using default work-directory " + this.workDir);
        }
    }

    final String uploadDirParam = conf.getInitParameter("upload-directory");
    if (uploadDirParam != null) {
        if (this.portletContextPath == null) {
            this.uploadDir = new File(uploadDirParam);
        } else {
            // Context path exists : is upload-directory absolute ?
            File uploadDirParamFile = new File(uploadDirParam);
            if (uploadDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.uploadDir = uploadDirParamFile;
            } else {
                // No : consider it relative to context path
                this.uploadDir = new File(portletContextPath, uploadDirParam);
            }
        }
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using upload-directory " + this.uploadDir);
        }
    } else {
        this.uploadDir = new File(workDir, "upload-dir" + File.separator);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using default upload-directory " + this.uploadDir);
        }
    }
    this.uploadDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_UPLOAD_DIR, this.uploadDir);

    this.enableUploads = getInitParameterAsBoolean("enable-uploads", ENABLE_UPLOADS);

    this.autoSaveUploads = getInitParameterAsBoolean("autosave-uploads", SAVE_UPLOADS_TO_DISK);

    String overwriteParam = getInitParameter("overwrite-uploads", "rename");
    // accepted values are deny|allow|rename - rename is default.
    if ("deny".equalsIgnoreCase(overwriteParam)) {
        this.allowOverwrite = false;
        this.silentlyRename = false;
    } else if ("allow".equalsIgnoreCase(overwriteParam)) {
        this.allowOverwrite = true;
        this.silentlyRename = false; // ignored in this case
    } else {
        // either rename is specified or unsupported value - default to rename.
        this.allowOverwrite = false;
        this.silentlyRename = true;
    }

    this.maxUploadSize = getInitParameterAsInteger("upload-max-size", MAX_UPLOAD_SIZE);

    String cacheDirParam = conf.getInitParameter("cache-directory");
    if (cacheDirParam != null) {
        if (this.portletContextPath == null) {
            this.cacheDir = new File(cacheDirParam);
        } else {
            // Context path exists : is cache-directory absolute ?
            File cacheDirParamFile = new File(cacheDirParam);
            if (cacheDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.cacheDir = cacheDirParamFile;
            } else {
                // No : consider it relative to context path
                this.cacheDir = new File(portletContextPath, cacheDirParam);
            }
        }
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using cache-directory " + this.cacheDir);
        }
    } else {
        this.cacheDir = IOUtils.createFile(workDir, "cache-dir" + File.separator);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("cache-directory was not set - defaulting to " + this.cacheDir);
        }
    }
    this.cacheDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_CACHE_DIR, this.cacheDir);

    this.appContext.put(Constants.CONTEXT_CONFIG_URL, getConfigFile(conf.getInitParameter("configurations")));
    if (conf.getInitParameter("configurations") == null) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("configurations was not set - defaulting to... ?");
        }
    }

    // get allow reload parameter, default is true
    this.allowReload = getInitParameterAsBoolean("allow-reload", ALLOW_RELOAD);

    String value = conf.getInitParameter("show-time");
    this.showTime = BooleanUtils.toBoolean(value) || (this.hiddenShowTime = "hide".equals(value));
    if (value == null) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("show-time was not set - defaulting to false");
        }
    }

    parentComponentManagerClass = getInitParameter("parent-component-manager", null);
    if (parentComponentManagerClass != null) {
        int dividerPos = parentComponentManagerClass.indexOf('/');
        if (dividerPos != -1) {
            parentComponentManagerInitParam = parentComponentManagerClass.substring(dividerPos + 1);
            parentComponentManagerClass = parentComponentManagerClass.substring(0, dividerPos);
        }
    }

    this.containerEncoding = getInitParameter("container-encoding", "ISO-8859-1");
    this.defaultFormEncoding = getInitParameter("form-encoding", "ISO-8859-1");

    this.appContext.put(Constants.CONTEXT_DEFAULT_ENCODING, this.defaultFormEncoding);
    this.manageExceptions = getInitParameterAsBoolean("manage-exceptions", true);

    this.enableInstrumentation = getInitParameterAsBoolean("enable-instrumentation", false);

    this.requestFactory = new RequestFactory(this.autoSaveUploads, this.uploadDir, this.allowOverwrite,
            this.silentlyRename, this.maxUploadSize, this.defaultFormEncoding);

    this.servletPath = getInitParameter("servlet-path", null);
    if (this.servletPath != null) {
        if (this.servletPath.startsWith("/")) {
            this.servletPath = this.servletPath.substring(1);
        }
        if (this.servletPath.endsWith("/")) {
            this.servletPath = servletPath.substring(0, servletPath.length() - 1);
        }
    }

    final String sessionScopeParam = getInitParameter("default-session-scope", "portlet");
    if ("application".equalsIgnoreCase(sessionScopeParam)) {
        this.defaultSessionScope = javax.portlet.PortletSession.APPLICATION_SCOPE;
    } else {
        this.defaultSessionScope = javax.portlet.PortletSession.PORTLET_SCOPE;
    }

    // Add the portlet configuration
    this.appContext.put(CONTEXT_PORTLET_CONFIG, conf);
    this.createCocoon();
}