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.flume.client.avro.ReliableSpoolingFileEventReader.java

/**
 * Create a ReliableSpoolingFileEventReader to watch the given directory.
 *///from  ww w. ja v  a2s  . c  o  m
private ReliableSpoolingFileEventReader(File spoolDirectory, String completedSuffix, String ignorePattern,
        String trackerDirPath, boolean annotateFileName, String fileNameHeader, boolean annotateBaseName,
        String baseNameHeader, String deserializerType, Context deserializerContext, String deletePolicy,
        String inputCharset, DecodeErrorPolicy decodeErrorPolicy, ConsumeOrder consumeOrder)
        throws IOException {

    // Sanity checks
    Preconditions.checkNotNull(spoolDirectory);
    Preconditions.checkNotNull(completedSuffix);
    Preconditions.checkNotNull(ignorePattern);
    Preconditions.checkNotNull(trackerDirPath);
    Preconditions.checkNotNull(deserializerType);
    Preconditions.checkNotNull(deserializerContext);
    Preconditions.checkNotNull(deletePolicy);
    Preconditions.checkNotNull(inputCharset);

    // validate delete policy
    if (!deletePolicy.equalsIgnoreCase(DeletePolicy.NEVER.name())
            && !deletePolicy.equalsIgnoreCase(DeletePolicy.IMMEDIATE.name())) {
        throw new IllegalArgumentException(
                "Delete policies other than " + "NEVER and IMMEDIATE are not yet supported");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Initializing {} with directory={}, metaDir={}, " + "deserializer={}",
                new Object[] { ReliableSpoolingFileEventReader.class.getSimpleName(), spoolDirectory,
                        trackerDirPath, deserializerType });
    }

    // Verify directory exists and is readable/writable
    Preconditions.checkState(spoolDirectory.exists(),
            "Directory does not exist: " + spoolDirectory.getAbsolutePath());
    Preconditions.checkState(spoolDirectory.isDirectory(),
            "Path is not a directory: " + spoolDirectory.getAbsolutePath());

    // Do a canary test to make sure we have access to spooling directory
    try {
        File canary = File.createTempFile("flume-spooldir-perm-check-", ".canary", spoolDirectory);
        Files.write("testing flume file permissions\n", canary, Charsets.UTF_8);
        List<String> lines = Files.readLines(canary, Charsets.UTF_8);
        Preconditions.checkState(!lines.isEmpty(), "Empty canary file %s", canary);
        if (!canary.delete()) {
            throw new IOException("Unable to delete canary file " + canary);
        }
        logger.debug("Successfully created and deleted canary file: {}", canary);
    } catch (IOException e) {
        throw new FlumeException(
                "Unable to read and modify files" + " in the spooling directory: " + spoolDirectory, e);
    }

    this.spoolDirectory = spoolDirectory;
    this.completedSuffix = completedSuffix;
    this.deserializerType = deserializerType;
    this.deserializerContext = deserializerContext;
    this.annotateFileName = annotateFileName;
    this.fileNameHeader = fileNameHeader;
    this.annotateBaseName = annotateBaseName;
    this.baseNameHeader = baseNameHeader;
    this.ignorePattern = Pattern.compile(ignorePattern);
    this.deletePolicy = deletePolicy;
    this.inputCharset = Charset.forName(inputCharset);
    this.decodeErrorPolicy = Preconditions.checkNotNull(decodeErrorPolicy);
    this.consumeOrder = Preconditions.checkNotNull(consumeOrder);

    File trackerDirectory = new File(trackerDirPath);

    // if relative path, treat as relative to spool directory
    if (!trackerDirectory.isAbsolute()) {
        trackerDirectory = new File(spoolDirectory, trackerDirPath);
    }

    // ensure that meta directory exists
    if (!trackerDirectory.exists()) {
        if (!trackerDirectory.mkdir()) {
            throw new IOException("Unable to mkdir nonexistent meta directory " + trackerDirectory);
        }
    }

    // ensure that the meta directory is a directory
    if (!trackerDirectory.isDirectory()) {
        throw new IOException("Specified meta directory is not a directory" + trackerDirectory);
    }

    this.metaFile = new File(trackerDirectory, metaFileName);
    if (metaFile.exists() && metaFile.length() == 0) {
        deleteMetaFile();
    }
}

From source file:FileErrorManager.java

/**
 * Performs the initialization for this object.
 *///from   w  ww.  j  a  v  a 2 s  .c  o m
private void init() {
    if (next == null) {
        throw new NullPointerException(ErrorManager.class.getName());
    }

    File dir = this.emailStore;
    if (dir.getClass() != File.class) { //For security reasons.
        throw new IllegalArgumentException(dir.getClass().getName());
    }

    if (!dir.isDirectory()) {
        throw new IllegalArgumentException("File must be a directory.");
    }

    if (!dir.canWrite()) { //Can throw under a security manager.
        super.error(dir.getAbsolutePath(), new SecurityException("write"), ErrorManager.OPEN_FAILURE);
    }

    //For now, only absolute paths are allowed.
    if (!dir.isAbsolute()) {
        throw new IllegalArgumentException("Only absolute paths are allowed.");
    }

    if (!dir.canRead()) { //Can throw under a security manager.
        super.error(dir.getAbsolutePath(), new SecurityException("read"), ErrorManager.OPEN_FAILURE);
    }
}

From source file:org.geotools.data.complex.config.AppSchemaDataAccessConfigurator.java

/**
 * Resolves any source datastore parameter settled as a file path relative to the location of
 * the xml mappings configuration file as an absolute path and returns a new Map with it.
 * /*from   ww  w.  j a  va 2s.  c o  m*/
 * @param datastoreParams
 * @return parameter map with resolved file url
 */
private Map<String, Serializable> resolveRelativePaths(final Map<String, Serializable> datastoreParams) {
    Map<String, Serializable> resolvedParams = new HashMap<String, Serializable>();

    AppSchemaDataAccessConfigurator.LOGGER.entering(getClass().getName(), "resolveRelativePaths");
    for (Map.Entry<String, Serializable> entry : (Set<Map.Entry<String, Serializable>>) datastoreParams
            .entrySet()) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();

        if (value != null && value.startsWith("file:")) {
            // a parameter prefix of "file:" is the only case that will be resolved
            // any file paths entered without this prefix will remain unchanged
            String oldValue = value;
            String resolvedDataPath = null;
            String inputDataPath = (String) value.substring("file:".length());
            File f = new File(inputDataPath);

            if (!f.isAbsolute()) {
                AppSchemaDataAccessConfigurator.LOGGER
                        .fine("resolving original parameter " + value + " for datastore parameter " + key);
                try {
                    // use of URL here should be safe as the base schema url should
                    // not yet have undergone any conversion to file or
                    // encoding/decoding
                    URL mappingFileUrl = new URL(config.getBaseSchemasUrl());
                    AppSchemaDataAccessConfigurator.LOGGER
                            .finer("mapping file URL is " + mappingFileUrl.toString());

                    String mappingFileDirPath = DataUtilities.urlToFile(mappingFileUrl).getParent();
                    AppSchemaDataAccessConfigurator.LOGGER
                            .finer("mapping file parent directory is " + mappingFileDirPath);

                    // FilenameUtils.concat handles a number of system-dependent issues here
                    // but it might be better to add this method to DataUtilities
                    resolvedDataPath = FilenameUtils.concat(mappingFileDirPath, inputDataPath);
                    if (resolvedDataPath == null) {
                        throw new RuntimeException("Relative path to datastore is incompatible with"
                                + " the base path - check double dot steps.");
                    }
                } catch (Exception e) {
                    AppSchemaDataAccessConfigurator.LOGGER.throwing(getClass().getName(),
                            "resolveRelativePaths", e);
                    throw new RuntimeException(e);
                }
            } else {
                resolvedDataPath = inputDataPath;
            }
            AppSchemaDataAccessConfigurator.LOGGER
                    .finer("Path to data has been resolved to " + resolvedDataPath);

            /*
             * Shapefile expects the protocol "file:" at the beginning of the parameter value,
             * other file-based datastores do not. We can distinguish shapefiles from other
             * cases because the key is "url" and as of 2010-09-25 no other file-based datastore
             * uses this key (properties files use the key "directory"). If a new file-based
             * datastore is created, everything will work fine provided the key "url" is used if
             * and only if the datastore expects a parameter value starting with "file:"
             */
            if ("url".equals(key) || key.startsWith("WSDataStoreFactory")) {
                value = "file:" + resolvedDataPath;
            } else {
                value = resolvedDataPath;
            }
            AppSchemaDataAccessConfigurator.LOGGER.fine("Resolved " + oldValue + " -> " + value);
        }
        resolvedParams.put(key, value);
    }
    return resolvedParams;
}

From source file:pl.project13.maven.git.GitCommitIdMojo.java

@VisibleForTesting
File craftPropertiesOutputFile(File base, String propertiesFilename) {
    File returnPath = new File(base, propertiesFilename);

    File currentPropertiesFilepath = new File(propertiesFilename);
    if (currentPropertiesFilepath.isAbsolute()) {
        returnPath = currentPropertiesFilepath;
    }//w  w w  .j  a v a  2  s.co  m

    return returnPath;
}

From source file:org.geotools.coverage.io.util.Utilities.java

/**
 * Creates a human readable message that describe the provided {@link File} object in terms of its properties.
 * /*from   w  w  w  .j  a va 2s  . c o  m*/
 * <p>
 * Useful for creating meaningful log messages.
 * 
 * @param file the {@link File} object to create a descriptive message for
 * @return a {@link String} containing a descriptive message about the provided {@link File}.
 * 
 */
public static String getFileInfo(final File file) {
    final StringBuilder builder = new StringBuilder();
    builder.append("Checking file:").append(FilenameUtils.getFullPath(file.getAbsolutePath())).append("\n");
    builder.append("isHidden:").append(file.isHidden()).append("\n");
    builder.append("exists:").append(file.exists()).append("\n");
    builder.append("isFile").append(file.isFile()).append("\n");
    builder.append("canRead:").append(file.canRead()).append("\n");
    builder.append("canWrite").append(file.canWrite()).append("\n");
    builder.append("canExecute:").append(file.canExecute()).append("\n");
    builder.append("isAbsolute:").append(file.isAbsolute()).append("\n");
    builder.append("lastModified:").append(file.lastModified()).append("\n");
    builder.append("length:").append(file.length());
    final String message = builder.toString();
    return message;
}

From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java

@Override
public void init() throws ServletException {
    String location = this.getServletConfig().getInitParameter("obrLocation");
    if (location == null || location.length() == 0) {
        location = "obr";
    }/*ww w.ja v a2s.  co  m*/

    // ensure absolute path
    File locFile = new File(location);
    if (!locFile.isAbsolute()) {
        String parent = this.ctx.getBundleContext().getProperty("sling.home");
        if (parent == null || parent.length() == 0) {
            parent = System.getProperty("user.dir");
        }
        locFile = new File(parent, location).getAbsoluteFile();
    }

    if (locFile.exists()) {
        if (!locFile.isDirectory()) {
            throw new ServletException(
                    "Repository Location " + locFile.getAbsolutePath() + " is not a directory");
        }
    } else {
        if (!locFile.mkdirs()) {
            throw new ServletException(
                    "Cannot create path to Repository Location " + locFile.getAbsolutePath());
        }
    }

    try {
        String defaultRepoName = this.getServletConfig().getInitParameter("obrName");
        this.repository = new Repository(defaultRepoName, locFile);
    } catch (IOException ioe) {
        throw new ServletException("Cannot load repository properties", ioe);
    }
}

From source file:com.hp.flume.plugins.source.ReliableSpoolingFileEventReader.java

/**
 * Create a ReliableSpoolingFileEventReader to watch the given directory.
 *//* ww  w  .j  a  v a  2s  .com*/
private ReliableSpoolingFileEventReader(File spoolDirectory, String completedSuffix, String ignorePattern,
        String trackerDirPath, boolean annotateFileName, String fileNameHeader, boolean annotateBaseName,
        String baseNameHeader, String deserializerType, Context deserializerContext, String deletePolicy,
        String inputCharset, DecodeErrorPolicy decodeErrorPolicy, ConsumeOrder consumeOrder)
        throws IOException {

    // Sanity checks
    Preconditions.checkNotNull(spoolDirectory);
    Preconditions.checkNotNull(completedSuffix);
    Preconditions.checkNotNull(ignorePattern);
    Preconditions.checkNotNull(trackerDirPath);
    Preconditions.checkNotNull(deserializerType);
    Preconditions.checkNotNull(deserializerContext);
    Preconditions.checkNotNull(deletePolicy);
    Preconditions.checkNotNull(inputCharset);

    // validate delete policy
    if (!deletePolicy.equalsIgnoreCase(DeletePolicy.NEVER.name())
            && !deletePolicy.equalsIgnoreCase(DeletePolicy.IMMEDIATE.name())) {
        throw new IllegalArgumentException(
                "Delete policies other than " + "NEVER and IMMEDIATE are not yet supported");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Initializing {} with directory={}, metaDir={}, " + "deserializer={}",
                new Object[] { ReliableSpoolingFileEventReader.class.getSimpleName(), spoolDirectory,
                        trackerDirPath, deserializerType });
    }

    // Verify directory exists and is readable/writable
    Preconditions.checkState(spoolDirectory.exists(),
            "Directory does not exist: " + spoolDirectory.getAbsolutePath());
    Preconditions.checkState(spoolDirectory.isDirectory(),
            "Path is not a directory: " + spoolDirectory.getAbsolutePath());

    // Do a canary test to make sure we have access to spooling directory
    try {
        File canary = File.createTempFile("flume-spooldir-perm-check-", ".canary", spoolDirectory);
        Files.write("testing flume file permissions\n", canary, Charsets.UTF_8);
        List<String> lines = Files.readLines(canary, Charsets.UTF_8);
        Preconditions.checkState(!lines.isEmpty(), "Empty canary file %s", canary);
        if (!canary.delete()) {
            throw new IOException("Unable to delete canary file " + canary);
        }
        logger.debug("Successfully created and deleted canary file: {}", canary);
    } catch (IOException e) {
        throw new FlumeException(
                "Unable to read and modify files" + " in the spooling directory: " + spoolDirectory, e);
    }

    this.spoolDirectory = spoolDirectory;
    this.completedSuffix = completedSuffix;
    this.deserializerType = deserializerType;
    this.deserializerContext = deserializerContext;
    this.annotateFileName = annotateFileName;
    this.fileNameHeader = fileNameHeader;
    this.annotateBaseName = annotateBaseName;
    this.baseNameHeader = baseNameHeader;
    this.ignorePattern = Pattern.compile(ignorePattern);
    this.deletePolicy = deletePolicy;
    this.inputCharset = Charset.forName(inputCharset);
    this.decodeErrorPolicy = Preconditions.checkNotNull(decodeErrorPolicy);
    this.consumeOrder = Preconditions.checkNotNull(consumeOrder);

    File trackerDirectory = new File(trackerDirPath);

    // if relative path, treat as relative to spool directory
    if (!trackerDirectory.isAbsolute()) {
        trackerDirectory = new File(spoolDirectory, trackerDirPath);
    }

    // ensure that meta directory exists
    if (!trackerDirectory.exists()) {
        if (!trackerDirectory.mkdir()) {
            throw new IOException("Unable to mkdir nonexistent meta directory " + trackerDirectory);
        }
    }

    // ensure that the meta directory is a directory
    if (!trackerDirectory.isDirectory()) {
        throw new IOException("Specified meta directory is not a directory" + trackerDirectory);
    }

    this.metaFile = new File(trackerDirectory, metaFileName);
}

From source file:axiom.main.Server.java

/**
 *
 *
 * @return .../*from  w  w w.ja  v  a  2 s . co m*/
 */
public File getDbHome() {
    String dbHome = sysProps.getProperty("dbHome", "");
    if (dbHome.trim().length() != 0) {
        File file = new File(dbHome);
        if (!file.isAbsolute()) {
            file = new File(axiomHome, dbHome);
        }
        return file;
    } else {
        return new File(axiomHome, "db");
    }
}

From source file:axiom.main.Server.java

/**
 *
 *
 * @return ...// w ww.jav  a 2  s  .com
 */
public File getAppsHome() {
    String appHome = sysProps.getProperty("appHome", "");
    if (appHome.trim().length() != 0) {
        File file = new File(appHome);
        if (!file.isAbsolute()) {
            file = new File(axiomHome, appHome);
        }
        return file;
    } else {
        return new File(axiomHome, "apps");
    }
}

From source file:org.apache.catalina.servlets.HTMLManagerServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 *//*from  www . j ava 2  s  .c  om*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Identify the request parameters that we need
    String command = request.getPathInfo();

    if (command == null || !command.equals("/upload")) {
        doGet(request, response);
        return;
    }

    // Prepare our output writer to generate the response message
    Locale locale = Locale.getDefault();
    String charset = context.getCharsetMapper().getCharset(locale);
    response.setLocale(locale);
    response.setContentType("text/html; charset=" + charset);

    String message = "";

    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    // Get the tempdir
    File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
    // Set upload parameters
    upload.setSizeMax(-1);
    upload.setRepositoryPath(tempdir.getCanonicalPath());

    // Parse the request
    String war = null;
    FileItem warUpload = null;
    try {
        List items = upload.parseRequest(request);

        // Process the uploaded fields
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                if (item.getFieldName().equals("installWar") && warUpload == null) {
                    warUpload = item;
                } else {
                    item.delete();
                }
            }
        }
        while (true) {
            if (warUpload == null) {
                message = sm.getString("htmlManagerServlet.installUploadNoFile");
                break;
            }
            war = warUpload.getName();
            if (!war.toLowerCase().endsWith(".war")) {
                message = sm.getString("htmlManagerServlet.installUploadNotWar", war);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (war.lastIndexOf('\\') >= 0) {
                war = war.substring(war.lastIndexOf('\\') + 1);
            }
            if (war.lastIndexOf('/') >= 0) {
                war = war.substring(war.lastIndexOf('/') + 1);
            }
            // Identify the appBase of the owning Host of this Context
            // (if any)
            String appBase = null;
            File appBaseDir = null;
            appBase = ((Host) context.getParent()).getAppBase();
            appBaseDir = new File(appBase);
            if (!appBaseDir.isAbsolute()) {
                appBaseDir = new File(System.getProperty("catalina.base"), appBase);
            }
            File file = new File(appBaseDir, war);
            if (file.exists()) {
                message = sm.getString("htmlManagerServlet.installUploadWarExists", war);
                break;
            }
            warUpload.write(file);
            try {
                URL url = file.toURL();
                war = url.toString();
                war = "jar:" + war + "!/";
            } catch (MalformedURLException e) {
                file.delete();
                throw e;
            }
            break;
        }
    } catch (Exception e) {
        message = sm.getString("htmlManagerServlet.installUploadFail", e.getMessage());
        log(message, e);
    } finally {
        if (warUpload != null) {
            warUpload.delete();
        }
        warUpload = null;
    }

    // If there were no errors, install the WAR
    if (message.length() == 0) {
        message = install(null, null, war);
    }

    list(request, response, message);
}