Example usage for java.io File getCanonicalPath

List of usage examples for java.io File getCanonicalPath

Introduction

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

Prototype

public String getCanonicalPath() throws IOException 

Source Link

Document

Returns the canonical pathname string of this abstract pathname.

Usage

From source file:com.nary.io.FileUtils.java

public static String getRealPath(File root, File file) throws IOException {
    String rtn = null;/*from w  w w  .  ja  va 2 s.  c  o m*/
    String rootAbs = root.getCanonicalPath();
    String abs = file.getCanonicalPath();
    if (abs.startsWith(rootAbs)) {
        if (abs.equals(rootAbs))
            return "";
        abs = abs.substring(rootAbs.length());
        if (abs.startsWith(File.separator)) {
            abs = abs.substring(File.separator.length());
        }
        rtn = abs;
    }
    return rtn;
}

From source file:com.tesora.dve.common.PEFileUtils.java

private static String getCanonicalPathFromURL(final URL url) throws PEException {
    File resourceFile;
    try {//from w  w  w  .  ja  va  2 s.c  o m
        final String os = System.getProperty("os.name");
        if (StringUtils.containsIgnoreCase(os, "win")) {
            return url.getFile();
        }

        resourceFile = new File(url.toURI());
    } catch (final URISyntaxException e) {
        resourceFile = new File(url.getPath());
    }

    try {
        return resourceFile.getCanonicalPath();
    } catch (final IOException e) {
        throw new PEException("Could not canonicalize the path '" + resourceFile.getAbsolutePath() + "'", e);
    }
}

From source file:it.univpm.deit.semedia.musicuri.core.Toolset.java

/**
 * Extracts/encodes the AudioSignatureDS for a given audio file
 * @param file the audio file to encode 
 * @return a string containing the whole XML-formatted MPEG-7 description document
 *///  w w w. j a v a2 s . c o  m
public static String createMPEG7Description(File file) throws IOException {
    if (isSupportedAudioFile(file)) {
        System.out.println("Extracting Query Audio Signature");
        String xmlString = null;
        Config configuration = new ConfigDefault();
        configuration.enableAll(false);
        configuration.setValue("AudioSignature", "enable", true);
        configuration.setValue("AudioSignature", "decimation", 32);
        //System.out.println("File: " + file.getName());

        AudioInputStream ais = null;
        try {
            ais = AudioSystem.getAudioInputStream(file);
            AudioFormat f = ais.getFormat();
            if (f.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
                System.out.println("Converting Audio stream format");
                ais = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, ais);
                f = ais.getFormat();
            }

            String workingDir = getCWD();
            String tempFilename = workingDir + "/temp.wav";
            AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(tempFilename));

            File tmpFile = new File(tempFilename);
            AudioInFloatSampled audioin = new AudioInFloatSampled(tmpFile);

            String str = tmpFile.getCanonicalPath();
            String[] ar = { str };
            //xmlString = Encoder.fromWAVtoXML(ar);

            // gather information about audio file
            MP7MediaInformation media_info = new MP7MediaInformation();
            media_info.setFileSize(tmpFile.length());

            AudioFormat format = audioin.getSourceFormat();
            media_info.setSample(format.getSampleRate(), format.getSampleSizeInBits());
            media_info.setNumberOfChannels(audioin.isMono() ? 1 : 2);

            // create mpeg-7 writer
            MP7Writer mp7writer = new MP7Writer();
            mp7writer.setMediaInformation(media_info);

            // create encoder
            Encoder encoder = null;

            Config config = new ConfigDefault();
            config.enableAll(false);
            config.setValue("AudioSignature", "enable", true);
            config.setValue("AudioSignature", "decimation", 32);
            encoder = new Encoder(audioin.getSampleRate(), mp7writer, config);
            //encoder.addTimeElapsedListener(new Ticker(System.err));

            // copy audio signal from source to encoder
            long oldtime = System.currentTimeMillis();
            float[] audio;
            while ((audio = audioin.get()) != null) {
                if (!audioin.isMono())
                    audio = AudioInFloat.getMono(audio);
                encoder.put(audio);
            }
            encoder.flush();
            System.out.println("Extraction Time     : " + (System.currentTimeMillis() - oldtime) + " ms");

            // whole MPEG-7 description into a string
            xmlString = mp7writer.toString();
            //System.out.println( xmlString )

        } catch (Exception e) {
            e.printStackTrace(System.err);
        } finally {
            //ais.close();
        }

        return xmlString;
    } else {
        System.out.println("Unsupported audio file format");
        return null;
    }
}

From source file:com.ms.commons.test.common.FileUtil.java

public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate, FileFilter filter)
        throws IOException {
    if (srcDir == null) {
        throw new NullPointerException("Source must not be null");
    }//from  w  w  w . java  2  s. c om
    if (destDir == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (srcDir.exists() == false) {
        throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
    }
    if (srcDir.isDirectory() == false) {
        throw new IOException("Source '" + srcDir + "' exists but is not a directory");
    }
    if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
        throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
    }
    doCopyDirectory(srcDir, destDir, preserveFileDate, filter);
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

/**
 * Looks for an extension, which is the last dot '.' in a file name, but only if the characters are alpha to
 * distinguish it from DicomUIDs./*from w ww  .  j a va2 s  .  co  m*/
 * 
 * @param f File ex. ./dir1/dir2/SomeFileName.ext
 * @return String - ./dir1/dir2/SomeFileName
 */
public static String fileAbsolutePathWithoutExtension(File f) {
    String fullPath;
    try {
        fullPath = f.getCanonicalPath();
    } catch (IOException ioe) {
        fullPath = f.getAbsolutePath();
    }
    return removeExtension(fullPath);
}

From source file:net.ftb.util.OSUtils.java

public static void createStorageLocations() {
    File cacheDir = new File(OSUtils.getCacheStorageLocation());
    File dynamicDir = new File(OSUtils.getDynamicStorageLocation());

    if (!cacheDir.exists()) {
        cacheDir.mkdirs();/*from w ww.j a  va 2s.  c  o m*/

        if (dynamicDir.exists() && !cacheDir.equals(dynamicDir)) {
            // Migrate cached archives from the user's roaming profile to their local cache

            Logger.logInfo("Migrating cached Maps from Roaming to Local storage");
            FTBFileUtils.move(new File(dynamicDir, "Maps"), new File(cacheDir, "Maps"));

            Logger.logInfo("Migrating cached Modpacks from Roaming to Local storage");
            FTBFileUtils.move(new File(dynamicDir, "ModPacks"), new File(cacheDir, "ModPacks"));

            Logger.logInfo("Migrating cached Texturepacks from Roaming to Local storage");
            FTBFileUtils.move(new File(dynamicDir, "TexturePacks"), new File(cacheDir, "TexturePacks"));

            Logger.logInfo("Migration complete.");
        }
    }

    if (!dynamicDir.exists()) {
        dynamicDir.mkdirs();
    }

    if (getCurrentOS() == OS.WINDOWS) {
        File oldLoginData = new File(dynamicDir, "logindata");
        File newLoginData = new File(cacheDir, "logindata");
        try {
            if (oldLoginData.exists()
                    && !oldLoginData.getCanonicalPath().equals(newLoginData.getCanonicalPath())) {
                newLoginData.delete();
            }
        } catch (Exception e) {
            Logger.logError("Error deleting login data", e);
        }
    }
}

From source file:JaqlShell.java

/**
 * @param mrc/*from  w ww . j  ava2s . c  om*/
 * @param conf
 * @throws Exception
 */
private static void setupOverride(MiniMRCluster mrc, Configuration conf) throws Exception {
    File overrideDir = new File(System.getProperty("hadoop.conf.override"));
    if (!overrideDir.exists()) {
        overrideDir.mkdirs();
    }

    // write out the JobConf from MiniMR to the override dir
    JobConf jc = mrc.createJobConf();
    conf.set("mapred.job.tracker", jc.get("mapred.job.tracker", null));
    String name = "mapred.job.tracker.info.port";
    String addr = jc.get(name, null);
    if (addr == null) {
        name = "mapred.job.tracker.http.address";
        addr = jc.get(name, null);
    }
    conf.set(name, addr);
    OutputStream outCore = new FileOutputStream(
            overrideDir.getCanonicalPath() + File.separator + "core-default.xml");
    OutputStream outMapred = new FileOutputStream(
            overrideDir.getCanonicalPath() + File.separator + "mapred-default.xml");
    OutputStream outHdfs = new FileOutputStream(
            overrideDir.getCanonicalPath() + File.separator + "hdfs-default.xml");
    conf.writeXml(outCore);
    conf.writeXml(outMapred);
    conf.writeXml(outHdfs);
    outCore.close();
    outMapred.close();
    outHdfs.close();
}

From source file:edu.kit.dama.staging.util.StagingUtils.java

/**
 * Get the temporary directory of the transfer associated with the provided
 * transfer container. This directory is located in the user home directory
 * under ~/.lsdf/<TID>, where <TID> stands for the transfer ID of this
 * transfer. To avoid problems with invalid pathnames, the TID gets UTF-8
 * URL-encoded. Within the temporary directory the transfer can store status
 * information or checkpoint data to be able to resume failed transfers.
 *
 * @param pContainer The transfer container for which the temp dir should be
 * returned./*from   w  w w  .j ava 2 s  .c  o m*/
 *
 * @return The transfer's temporary directory
 *
 * @throws IOException If there was not set any TID for this transfer or if
 * there are problems getting the users home directory
 */
public static String getTempDir(TransferTaskContainer pContainer) throws IOException {
    if (pContainer != null) {
        LOGGER.debug("Determining transfer tmp directory.");
        File userHome = SystemUtils.getUserHome();
        if (!isAccessibleDirectory(userHome)) {
            //user home not usable (maybe no home directory available). Try system temp dir...
            userHome = SystemUtils.getJavaIoTmpDir();
            if (!isAccessibleDirectory(userHome)) {
                throw new IOException("Failed to obtain valid temp directory. UserHome ("
                        + SystemUtils.getUserHome() + ") and TmpDir (" + userHome + ") are not usable.");
            } else {
                LOGGER.debug("Using tmp directory.");
            }
        } else {
            LOGGER.debug("Using user home directory.");
        }

        return FilenameUtils.concat(FilenameUtils.concat(userHome.getCanonicalPath(), ".lsdf"),
                URLEncoder.encode(pContainer.getUniqueTransferIdentifier(), "UTF-8"));
    } else {
        throw new IOException(
                "Failed to obtain temporary transfer directory. Transfer container must not be 'null'");
    }
}

From source file:com.meltmedia.cadmium.core.util.LogUtils.java

/**
 * <p>Reconfigures the logging context.</p>
 * <p>The LoggerContext gets configured with "/WEB-INF/context-logback.xml". There is a <code>logDir</code> property set here which is expected to be the directory that the log file is written to.</p>
 * <p>The <code>logDir</code> property gets set on the LoggerContext with the following logic.</p>
 * <ul>//  w w w .j  a v a 2  s  .c o  m
 *   <li>{@link LOG_DIR_INIT_PARAM} context parameter will be created and checked if it is writable.</li>
 *   <li>The File object passed in is used as a fall-back if it can be created and written to.</li>
 * </ul>    
 * @see {@link LoggerContext}
 * @param servletContext The current servlet context.
 * @param logDirFallback The fall-back directory to log to.
 * @param vHostName
 * @param log
 * @throws FileNotFoundException Thrown if no logDir can be written to.
 * @throws MalformedURLException 
 * @throws IOException
 */
public static void configureLogback(ServletContext servletContext, File logDirFallback, String vHostName,
        Logger log) throws FileNotFoundException, MalformedURLException, IOException {
    log.debug("Reconfiguring Logback!");
    String systemLogDir = System.getProperty(LOG_DIRECTORY_OVERRIDE, System.getProperty(JBOSS_LOG_DIR));
    if (systemLogDir != null) {
        systemLogDir += "/" + vHostName;
    }
    File logDir = FileSystemManager.getWritableDirectoryWithFailovers(systemLogDir,
            servletContext.getInitParameter(LOG_DIR_INIT_PARAM), logDirFallback.getAbsolutePath());
    if (logDir != null) {
        log.debug("Resetting logback context.");
        URL configFile = servletContext.getResource("/WEB-INF/context-logback.xml");
        log.debug("Configuring logback with file, {}", configFile);
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            context.stop();
            context.reset();
            context.putProperty("logDir", logDir.getCanonicalPath());
            configurator.doConfigure(configFile);
        } catch (JoranException je) {
            // StatusPrinter will handle this
        } finally {
            context.start();
            log.debug("Done resetting logback.");
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
    }
}

From source file:com.wingnest.play2.origami.plugin.OrigamiPlugin.java

private static void runEmbeddedOrientDB() {
    FileInputStream fis = null;//from  www .  j a v a  2  s  .  co m
    try {
        /* orient server */ {
            final String cfile = Play.application().configuration().getString(CONF_ORIENT_DB_CONFIG_FILE);
            final InputStream is;
            if (cfile != null) {
                final File aFile = new File(cfile);
                OrigamiLogger.info("db.config in application was used : " + aFile.getAbsolutePath());
                fis = new FileInputStream(new File(cfile));
                is = fis;
            } else {
                OrigamiLogger.info("default db.config in Origami Plugin was used");
                is = OrigamiPlugin.class.getClassLoader().getResourceAsStream("db.config");
            }
            server = OServerMain.create();
            server.startup(is);
            info("OrientDB of embedded mode was started");
        }
        /* web server */ {
            final String orientDBWwwPath = Play.application().configuration()
                    .getString(CONF_ORIENT_DB_WWW_PATH);
            if (System.getProperty(ORIENTDB_WWW_PATH) == null && orientDBWwwPath != null) {
                final File wwwPath = new File(orientDBWwwPath);
                if (!wwwPath.exists() || !wwwPath.isDirectory()) {
                    final String mes = String.format("www directory not found : %s", wwwPath.getAbsolutePath());
                    OrigamiLogger.error(mes);
                    throw new IllegalStateException(mes);
                }
                System.setProperty(ORIENTDB_WWW_PATH, wwwPath.getCanonicalPath());
            }
            if (System.getProperty(ORIENTDB_WWW_PATH) != null) {
                server.activate();
                OrigamiLogger.info("WWW Server was just activated : %s", System.getProperty(ORIENTDB_WWW_PATH));
            } else {
                OrigamiLogger.info(
                        "WWW Server is not activated : application.conf's %s property was not provided",
                        CONF_ORIENT_DB_WWW_PATH);
            }
        }
    } catch (Exception e) {
        throw new OrigamiUnexpectedException(e);
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (Exception dummy) {
            }
    }
}