Example usage for java.io File getCanonicalFile

List of usage examples for java.io File getCanonicalFile

Introduction

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

Prototype

public File getCanonicalFile() throws IOException 

Source Link

Document

Returns the canonical form of this abstract pathname.

Usage

From source file:org.obiba.magma.datasource.csv.CsvValueTableWriterTest.java

@Test
public void test_writing_data_only_one_text_variable() throws Exception {
    File tempTestDirectory = new TempTableBuilder("TableDataOnly").addData().build();

    CsvDatasource datasource = new CsvDatasource("csv-datasource").addValueTable("TableDataOnly", //
            null, //
            new File(tempTestDirectory.getCanonicalFile() + "/TableDataOnly", "data.csv"));
    datasource.initialise();/*from www.j av  a2  s. c  o m*/

    VariableEntity variableEntity = new VariableEntityBean("Participant", "1");
    Variable testVariable = Variable.Builder.newVariable("test-variable", TextType.get(), "Participant")
            .build();
    Value secondCup = TextType.get().valueOf("Second Cup");

    try (ValueTableWriter tableWriter = datasource.createWriter("TableDataOnly", "Participant");
            ValueTableWriter.ValueSetWriter valueSetWriter = tableWriter.writeValueSet(variableEntity)) {
        valueSetWriter.writeValue(testVariable, secondCup);
    }

    CsvDatasource readDatasource = new CsvDatasource("read-csv-datasource").addValueTable("TableDataOnly", //
            null, //
            new File(tempTestDirectory.getCanonicalFile() + "/TableDataOnly", "data.csv"));
    readDatasource.initialise();

    ValueTable table = readDatasource.getValueTable("TableDataOnly");

    Variable variable = table.getVariable("test-variable");

    for (ValueSet valueSet : table.getValueSets()) {
        Value value = table.getValue(variable, valueSet);
        assertThat(value.getValue()).isNotNull();
        assertThat(value.getValue().toString()).isEqualTo("Second Cup");
    }
}

From source file:dk.netarkivet.archive.bitarchive.BitarchiveAdmin.java

/**
 * Moves a file from temporary storage to file storage.
 *
 * Note: It is checked, if tempLocation resides in directory
 *  TEMPORARY_DIRECTORY_NAME and whether the parent of tempLocation
 *   is a Bitarchive directory./*w ww .j a  va  2s. c  o m*/
 *
 * @param tempLocation The temporary location where the file was stored.
 *                     This must be a path returned from getTemporaryPath
 *
 * @return The location where the file is now stored
 * @throws IOFailure if tempLocation is not created from getTemporaryPath
 *                   or file cannot be moved to Storage location.
 * @throws ArgumentNotValid If the tempLocation file is null.
 */
public File moveToStorage(File tempLocation) throws IOFailure, ArgumentNotValid {
    ArgumentNotValid.checkNotNull(tempLocation, "tempLocation");
    try {
        tempLocation = tempLocation.getCanonicalFile();
    } catch (IOException e) {
        throw new IOFailure("Could not retrieve the canonical file for '" + tempLocation + "'.", e);
    }
    String arcFileName = tempLocation.getName();

    /**
     * Check, that File tempLocation resides in directory
     * TEMPORARY_DIRECTORY_NAME.
     */
    File arcFilePath = tempLocation.getParentFile();
    if (arcFilePath == null || !arcFilePath.getName().equals(Constants.TEMPORARY_DIRECTORY_NAME)) {
        throw new IOFailure("Location '" + tempLocation + "' is not in " + "tempdir '"
                + Constants.TEMPORARY_DIRECTORY_NAME + "'");
    }
    /**
     * Check, that arcFilePath (now known to be TEMPORARY_DIRECTORY_NAME)
     * resides in a recognised Bitarchive Directory.
     */
    File archivedir = arcFilePath.getParentFile();
    if (archivedir == null || !isBitarchiveDirectory(archivedir)) {
        throw new IOFailure("Location '" + tempLocation + "' is not in " + "recognised archive directory.");
    }
    /**
     * Move File tempLocation to new location: storageFile
     */
    File storagePath = new File(archivedir, Constants.FILE_DIRECTORY_NAME);
    File storageFile = new File(storagePath, arcFileName);
    if (!tempLocation.renameTo(storageFile)) {
        throw new IOFailure(
                "Could not move '" + tempLocation.getPath() + "' to '" + storageFile.getPath() + "'");
    }
    // Update the filelist for the directory with this new file.
    updateFileList(archivedir);
    return storageFile;
}

From source file:com.meyling.telnet.shell.PwtsShell.java

/**
 * Execute external process./* ww  w. j ava 2 s  .co  m*/
 *
 * @param   commandLineParameters   Comand line parameters. The first parameter must be an
 *                 executable program.
 * @return  Exit code of external program.
 * @throws     IOException  External call failed.
 */
private int execSynchronized(String[] commandLineParameters) throws IOException {
    final StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < commandLineParameters.length; i++) {
        if (i > 0) {
            buffer.append(" ");
        }
        buffer.append(commandLineParameters[i]);
    }
    try {
        trace.info("executing: " + buffer.toString());
        final File startDir = new File("/");
        process = Runtime.getRuntime().exec(commandLineParameters, (String[]) null,
                startDir.getCanonicalFile());
    } catch (IOException e) {
        throw e;
    }
    // thread for process error stream
    final ErrorStreamGobbler errorGobbler = new ErrorStreamGobbler(process.getErrorStream());

    // thread for process output stream
    outputGobbler = new OutputStreamGobbler(process.getInputStream());

    // thread for process input stream
    final InputStreamGobbler inputGobbler = new InputStreamGobbler(process.getOutputStream());

    // start them all
    errorGobbler.start();
    outputGobbler.start();
    inputGobbler.start();

    try {
        shellThread = Thread.currentThread();
        process.waitFor();
        trace.debug("exit code: " + process.exitValue());
        return process.exitValue();
    } catch (InterruptedException e) {
        trace.fatal("execution interupted. Called was: " + buffer);
        throw new IOException("process execution interrupted.");
    } finally {
        // close all those streams
        try {
            process.getInputStream().close();
        } catch (IOException e) {
            // ignore
        }
        try {
            process.getErrorStream().close();
        } catch (IOException e) {
            // ignore
        }
        try {
            process.getOutputStream().close();
        } catch (IOException e) {
            // ignore
        }
        process.destroy();
    }
}

From source file:org.apache.james.smtpserver.fastfail.JDBCGreylistHandler.java

/**
 * Initializes the sql query environment from the SqlResources file. Will
 * look for conf/sqlResources.xml./*from w w  w.  ja  v a2 s. co  m*/
 * 
 * @param conn
 *            The connection for accessing the database
 * @param sqlFileUrl
 *            The url which we use to get the sql file
 * @throws Exception
 *             If any error occurs
 */
private void initSqlQueries(Connection conn, String sqlFileUrl) throws Exception {
    try {

        File sqlFile;

        try {
            sqlFile = fileSystem.getFile(sqlFileUrl);
            sqlFileUrl = null;
        } catch (Exception e) {
            serviceLog.error(e.getMessage(), e);
            throw e;
        }

        sqlQueries.init(sqlFile.getCanonicalFile(), "GreyList", conn, sqlParameters);

        selectQuery = sqlQueries.getSqlString("selectQuery", true);
        insertQuery = sqlQueries.getSqlString("insertQuery", true);
        deleteQuery = sqlQueries.getSqlString("deleteQuery", true);
        deleteAutoWhiteListQuery = sqlQueries.getSqlString("deleteAutoWhitelistQuery", true);
        updateQuery = sqlQueries.getSqlString("updateQuery", true);

    } finally {
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:org.tinygroup.jspengine.compiler.JspRuntimeContext.java

/**
 * Method used to initialize SecurityManager data.
 *///from   ww  w . j a  v a  2  s.c  o  m
private void initSecurity() {

    // Setup the PermissionCollection for this web app context
    // based on the permissions configured for the root of the
    // web app context directory, then add a file read permission
    // for that directory.
    Policy policy = Policy.getPolicy();
    if (policy != null) {
        try {
            // Get the permissions for the web app context
            String docBase = context.getRealPath("/");
            if (docBase == null) {
                docBase = options.getScratchDir().toString();
            }
            String codeBase = docBase;
            if (!codeBase.endsWith(File.separator)) {
                codeBase = codeBase + File.separator;
            }
            File contextDir = new File(codeBase);
            URL url = contextDir.getCanonicalFile().toURL();
            codeSource = new CodeSource(url, (Certificate[]) null);
            permissionCollection = policy.getPermissions(codeSource);

            // Create a file read permission for web app context directory
            if (!docBase.endsWith(File.separator)) {
                permissionCollection.add(new FilePermission(docBase, "read"));
                docBase = docBase + File.separator;
            } else {
                permissionCollection
                        .add(new FilePermission(docBase.substring(0, docBase.length() - 1), "read"));
            }
            docBase = docBase + "-";
            permissionCollection.add(new FilePermission(docBase, "read"));

            // Create a file read permission for web app tempdir (work)
            // directory
            String workDir = options.getScratchDir().toString();
            if (!workDir.endsWith(File.separator)) {
                permissionCollection.add(new FilePermission(workDir, "read"));
                workDir = workDir + File.separator;
            }
            workDir = workDir + "-";
            permissionCollection.add(new FilePermission(workDir, "read"));

            // Allow the JSP to access
            // org.tinygroup.jspengine.runtime.HttpJspBase
            permissionCollection
                    .add(new RuntimePermission("accessClassInPackage.org.tinygroup.jspengine.runtime"));

            if (parentClassLoader instanceof URLClassLoader) {
                URL[] urls = ((URLClassLoader) parentClassLoader).getURLs();
                String jarUrl = null;
                String jndiUrl = null;
                for (int i = 0; i < urls.length; i++) {
                    if (jndiUrl == null && urls[i].toString().startsWith("jndi:")) {
                        jndiUrl = urls[i].toString() + "-";
                    }
                    if (jarUrl == null && urls[i].toString().startsWith("jar:jndi:")) {
                        jarUrl = urls[i].toString();
                        jarUrl = jarUrl.substring(0, jarUrl.length() - 2);
                        jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('/')) + "/-";
                    }
                }
                if (jarUrl != null) {
                    permissionCollection.add(new FilePermission(jarUrl, "read"));
                    permissionCollection.add(new FilePermission(jarUrl.substring(4), "read"));
                }
                if (jndiUrl != null)
                    permissionCollection.add(new FilePermission(jndiUrl, "read"));
            }
        } catch (Exception e) {
            context.log("Security Init for context failed", e);
        }
    }
}

From source file:dk.netarkivet.archive.bitarchive.BitarchiveAdmin.java

/** Return the path used to store files that are removed by
 * RemoveAndGetFileMessage.//w w w .  j ava 2 s.c  om
 *
 * @param existingFile a File object for an existing file in the bitarchive
 * 
 * @return The full path of the file in the attic dir
 */
public File getAtticPath(File existingFile) {
    ArgumentNotValid.checkNotNull(existingFile, "File existingFile");
    // Find where the file resides so we can use a dir in the same place.
    try {
        existingFile = existingFile.getCanonicalFile();
    } catch (IOException e) {
        throw new IOFailure("Could not retrieve canonical file for '" + existingFile + "'.", e);
    }
    String arcFileName = existingFile.getName();
    File parentDir = existingFile.getParentFile().getParentFile();
    if (!isBitarchiveDirectory(parentDir)) {
        log.warn("Attempt to get attic path for non-archived file '" + existingFile + "'");
        throw new ArgumentNotValid(
                "File should belong to a bitarchive dir," + " but " + existingFile + " doesn't");
    }
    // Ensure that 'atticdir' exists. If it doesn't, it is created
    File atticdir = new File(parentDir, Constants.ATTIC_DIRECTORY_NAME);
    ApplicationUtils.dirMustExist(atticdir);
    return new File(atticdir, arcFileName);
}

From source file:hudson.scm.subversion.CheckoutUpdater.java

@Override
public UpdateTask createTask() {
    return new UpdateTask() {
        private static final long serialVersionUID = 8349986526712487762L;

        @Override/*from  w  w  w.j a v  a  2s .  c om*/
        public List<External> perform() throws IOException, InterruptedException {
            final SVNUpdateClient svnuc = clientManager.getUpdateClient();
            final List<External> externals = new ArrayList<External>(); // store discovered externals to here

            listener.getLogger().println("Cleaning local Directory " + location.getLocalDir());
            Util.deleteContentsRecursive(new File(ws, location.getLocalDir()));

            // buffer the output by a separate thread so that the update operation
            // won't be blocked by the remoting of the data
            PipedOutputStream pos = new PipedOutputStream();
            StreamCopyThread sct = new StreamCopyThread("svn log copier", new PipedInputStream(pos),
                    listener.getLogger());
            sct.start();

            try {

                SVNRevision r = getRevision(location);

                String revisionName = r.getDate() != null ? fmt.format(r.getDate()) : r.toString();

                listener.getLogger()
                        .println("Checking out " + location.remote + " at revision " + revisionName);

                File local = new File(ws, location.getLocalDir());
                SubversionUpdateEventHandler eventHandler = new SubversionUpdateEventHandler(
                        new PrintStream(pos), externals, local, location.getLocalDir());
                svnuc.setEventHandler(eventHandler);
                svnuc.setExternalsHandler(eventHandler);
                svnuc.setIgnoreExternals(location.isIgnoreExternalsOption());

                SVNDepth svnDepth = getSvnDepth(location.getDepthOption());
                svnuc.doCheckout(location.getSVNURL(), local.getCanonicalFile(), SVNRevision.HEAD, r, svnDepth,
                        true);
            } catch (SVNCancelException e) {
                if (isAuthenticationFailedError(e)) {
                    e.printStackTrace(listener.error("Failed to check out " + location.remote));
                    return null;
                } else {
                    listener.error("Subversion checkout has been canceled");
                    throw (InterruptedException) new InterruptedException().initCause(e);
                }
            } catch (SVNException e) {
                e.printStackTrace(listener.error("Failed to check out " + location.remote));
                throw new IOException("Failed to check out " + location.remote, e);
            } finally {
                try {
                    pos.close();
                } finally {
                    try {
                        sct.join(); // wait for all data to be piped.
                    } catch (InterruptedException e) {
                        throw new IOException2("interrupted", e);
                    }
                }
            }

            return externals;
        }
    };
}

From source file:org.openpnp.model.Configuration.java

public Board getBoard(File file) throws Exception {
    if (!file.exists()) {
        Board board = new Board(file);
        board.setName(file.getName());//ww  w. j a  v  a  2s  .c o  m
        Serializer serializer = createSerializer();
        serializer.write(board, file);
    }
    file = file.getCanonicalFile();
    if (boards.containsKey(file)) {
        return boards.get(file);
    }
    Board board = loadBoard(file);
    boards.put(file, board);
    firePropertyChange("boards", null, boards);
    return board;
}

From source file:org.obiba.magma.datasource.csv.CsvValueTableWriterTest.java

@Test
public void test_writing_data_only_adding_new_value_set() throws Exception {
    File tempTestDirectory = new TempTableBuilder("TableDataOnly").addData().build();

    CsvDatasource setupDatasource = new CsvDatasource("setup-datasource").addValueTable("TableDataOnly", //
            null, //
            new File(tempTestDirectory.getCanonicalFile() + "/TableDataOnly", "data.csv"));
    setupDatasource.initialise();//from w  w w  . j av  a 2  s . c  o  m

    VariableEntity variableEntity = new VariableEntityBean("Participant", "1");

    Variable coffeeVariable = Variable.Builder.newVariable("coffee", TextType.get(), "Participant").build();
    Value secondCup = TextType.get().valueOf("Second Cup");

    Variable teaVariable = Variable.Builder.newVariable("tea", TextType.get(), "Participant").build();
    Value earlGrey = TextType.get().valueOf("Earl Grey");

    Variable biscuitVariable = Variable.Builder.newVariable("biscuit", TextType.get(), "Participant").build();
    Value cheese = TextType.get().valueOf("cheese");

    try (ValueTableWriter tableWriter = setupDatasource.createWriter("TableDataOnly", "Participant");
            ValueTableWriter.ValueSetWriter valueSetWriter = tableWriter.writeValueSet(variableEntity)) {
        valueSetWriter.writeValue(coffeeVariable, secondCup);
        valueSetWriter.writeValue(teaVariable, earlGrey);
        valueSetWriter.writeValue(biscuitVariable, cheese);
    }

    CsvDatasource writeDatasource = new CsvDatasource("csv-datasource").addValueTable("TableDataOnly", //
            null, //
            new File(tempTestDirectory.getCanonicalFile() + "/TableDataOnly", "data.csv"));
    writeDatasource.initialise();

    VariableEntity participantTwoEntity = new VariableEntityBean("Participant", "2");

    Value orangePekoe = TextType.get().valueOf("Orange Pekoe");

    try (ValueTableWriter tableWriter = writeDatasource.createWriter("TableDataOnly", "Participant");
            ValueTableWriter.ValueSetWriter valueSetWriter = tableWriter.writeValueSet(participantTwoEntity)) {
        valueSetWriter.writeValue(teaVariable, orangePekoe);
    }

    CsvDatasource readDatasource = new CsvDatasource("read-datasource").addValueTable("TableDataOnly", //
            null, //
            new File(tempTestDirectory.getCanonicalFile() + "/TableDataOnly", "data.csv"));
    readDatasource.initialise();

    ValueTable table = readDatasource.getValueTable("TableDataOnly");

    Variable verifyCoffeeVariable = table.getVariable("coffee");
    Variable verifyTeaVariable = table.getVariable("tea");
    Variable verifyBiscuitVariable = table.getVariable("biscuit");

    for (ValueSet valueSet : table.getValueSets()) {
        String identifier = valueSet.getVariableEntity().getIdentifier();
        Value coffeeValue = table.getValue(verifyCoffeeVariable, valueSet);
        Value teaValue = table.getValue(verifyTeaVariable, valueSet);
        Value biscuitValue = table.getValue(verifyBiscuitVariable, valueSet);
        switch (identifier) {
        case "1":
            assertThat(coffeeValue.getValue().toString()).isEqualTo("Second Cup");
            assertThat(teaValue.getValue().toString()).isEqualTo("Earl Grey");
            assertThat(biscuitValue.getValue().toString()).isEqualTo("cheese");
            break;
        case "2":
            assertThat(coffeeValue.isNull()).isTrue();
            assertThat(teaValue.getValue().toString()).isEqualTo("Orange Pekoe");
            assertThat(biscuitValue.isNull()).isTrue();
            break;
        }
    }
}

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

/**
 * Scan the JAR file at the specified resource path for TLDs in the
 * <code>META-INF</code> subdirectory, and scan each TLD for application
 * event listeners that need to be registered.
 *
 * @param resourcePath Resource path of the JAR file to scan
 *
 * @exception Exception if an exception occurs while scanning this JAR
 *///from   w  w w . ja  va  2 s.  com
private void tldScanJar(String resourcePath) throws Exception {

    if (log.isDebugEnabled()) {
        log.debug(" Scanning JAR at resource path '" + resourcePath + "'");
    }

    URL url = context.getServletContext().getResource(resourcePath);
    if (url == null) {
        throw new IllegalArgumentException(sm.getString("contextConfig.tldResourcePath", resourcePath));
    }

    File file = new File(url.getFile());
    file = file.getCanonicalFile();
    tldScanJar(file);

}