Example usage for org.springframework.core.io Resource getFile

List of usage examples for org.springframework.core.io Resource getFile

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getFile.

Prototype

File getFile() throws IOException;

Source Link

Document

Return a File handle for this resource.

Usage

From source file:org.dkpro.similarity.experiments.sts2013baseline.util.Evaluator.java

public static void runEvaluationMetric(Mode mode, EvaluationMetric metric, Dataset... datasets)
        throws IOException {
    StringBuilder sb = new StringBuilder();

    // Compute Pearson correlation for the specified datasets
    for (Dataset dataset : datasets) {
        computePearsonCorrelation(mode, dataset);
    }/*www .j a va2  s . c o  m*/

    if (metric == PearsonAll) {
        List<Double> concatExp = new ArrayList<Double>();
        List<Double> concatGS = new ArrayList<Double>();

        // Concat the scores
        for (Dataset dataset : datasets) {
            File expScoresFile = new File(
                    OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + dataset.toString() + ".csv");

            List<String> lines = FileUtils.readLines(expScoresFile);

            for (String line : lines) {
                concatExp.add(Double.parseDouble(line));
            }
        }

        // Concat the gold standard
        for (Dataset dataset : datasets) {
            String gsScoresFilePath = GOLDSTANDARD_DIR + "/" + mode.toString().toLowerCase() + "/" + "STS.gs."
                    + dataset.toString() + ".txt";

            PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver();
            Resource res = r.getResource(gsScoresFilePath);
            File gsScoresFile = res.getFile();

            List<String> lines = FileUtils.readLines(gsScoresFile);

            for (String line : lines) {
                concatGS.add(Double.parseDouble(line));
            }
        }

        double[] concatExpArray = ArrayUtils.toPrimitive(concatExp.toArray(new Double[concatExp.size()]));
        double[] concatGSArray = ArrayUtils.toPrimitive(concatGS.toArray(new Double[concatGS.size()]));

        PearsonsCorrelation pearson = new PearsonsCorrelation();
        Double correl = pearson.correlation(concatExpArray, concatGSArray);

        sb.append(correl.toString());
    } else if (metric == PearsonMean) {
        List<Double> scores = new ArrayList<Double>();

        for (Dataset dataset : datasets) {
            File resultFile = new File(
                    OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + dataset.toString() + ".txt");
            double score = Double.parseDouble(FileUtils.readFileToString(resultFile));

            scores.add(score);
        }

        double mean = 0.0;
        for (Double score : scores) {
            mean += score;
        }
        mean = mean / scores.size();

        sb.append(mean);
    }

    FileUtils.writeStringToFile(
            new File(OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + metric.toString() + ".txt"),
            sb.toString());
}

From source file:com.edgenius.core.util.FileUtil.java

/**
 * Wrapper of Spring DefaultResourceLoader. 
 * The location must start with "classpath:" or "file://", otherwise, this method
 * may throw file not found exception./*from ww  w  . j a  va  2 s.com*/
 * Important: The file must be in file system. This means it won't work if it is in jar or zip file etc.
 * Please getFileInputStream() to get input stream directly if they are in jar or zip
 *
 * @param location
 * @return
 * @throws IOException 
 */
public static File getFile(String location) throws IOException {
    DefaultResourceLoader loader = new DefaultResourceLoader();
    Resource res = loader.getResource(location);
    try {
        return res.getFile();
    } catch (IOException e) {
        throw (e);
    }
}

From source file:org.dkpro.similarity.experiments.sts2013.util.Evaluator.java

@SuppressWarnings("unchecked")
public static void runEvaluationMetric(Mode mode, EvaluationMetric metric, Dataset... datasets)
        throws IOException {
    StringBuilder sb = new StringBuilder();

    // Compute Pearson correlation for the specified datasets
    for (Dataset dataset : datasets) {
        computePearsonCorrelation(mode, dataset);
    }//from w  w  w  .jav  a  2s .c o m

    if (metric == PearsonAll) {
        List<Double> concatExp = new ArrayList<Double>();
        List<Double> concatGS = new ArrayList<Double>();

        // Concat the scores
        for (Dataset dataset : datasets) {
            File expScoresFile = new File(
                    OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + dataset.toString() + ".csv");

            List<String> lines = FileUtils.readLines(expScoresFile);

            for (String line : lines) {
                concatExp.add(Double.parseDouble(line));
            }
        }

        // Concat the gold standard
        for (Dataset dataset : datasets) {
            String gsScoresFilePath = GOLDSTANDARD_DIR + "/" + mode.toString().toLowerCase() + "/" + "STS.gs."
                    + dataset.toString() + ".txt";

            PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver();
            Resource res = r.getResource(gsScoresFilePath);
            File gsScoresFile = res.getFile();

            List<String> lines = FileUtils.readLines(gsScoresFile);

            for (String line : lines) {
                concatGS.add(Double.parseDouble(line));
            }
        }

        double[] concatExpArray = ArrayUtils.toPrimitive(concatExp.toArray(new Double[concatExp.size()]));
        double[] concatGSArray = ArrayUtils.toPrimitive(concatGS.toArray(new Double[concatGS.size()]));

        PearsonsCorrelation pearson = new PearsonsCorrelation();
        Double correl = pearson.correlation(concatExpArray, concatGSArray);

        sb.append(correl.toString());
    } else if (metric == PearsonMean) {
        List<Double> scores = new ArrayList<Double>();

        for (Dataset dataset : datasets) {
            File resultFile = new File(
                    OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + dataset.toString() + ".txt");
            double score = Double.parseDouble(FileUtils.readFileToString(resultFile));

            scores.add(score);
        }

        double mean = 0.0;
        for (Double score : scores) {
            mean += score;
        }
        mean = mean / scores.size();

        sb.append(mean);
    } else if (metric == PearsonWeightedMean) {
        List<Double> scores = new ArrayList<Double>();
        List<Integer> weights = new ArrayList<Integer>();

        for (Dataset dataset : datasets) {
            File resultFile = new File(
                    OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + dataset.toString() + ".txt");
            double score = Double.parseDouble(FileUtils.readFileToString(resultFile));

            File scoresFile = new File(
                    OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + dataset.toString() + ".csv");
            int weight = FileUtils.readLines(scoresFile).size();

            scores.add(score);
            weights.add(weight);
        }

        double mean = 0.0;
        int weightsum = 0;
        for (int i = 0; i < scores.size(); i++) {
            Double score = scores.get(i);
            Integer weight = weights.get(i);

            mean += weight * score;
            weightsum += weight;
        }
        mean = mean / weightsum;

        sb.append(mean);
    }

    FileUtils.writeStringToFile(
            new File(OUTPUT_DIR + "/" + mode.toString().toLowerCase() + "/" + metric.toString() + ".txt"),
            sb.toString());
}

From source file:org.jahia.modules.external.test.db.WriteableMappedDatabaseProvider.java

private static void extract(JahiaTemplatesPackage p, org.springframework.core.io.Resource r, File f)
        throws Exception {
    if ((r instanceof BundleResource && r.contentLength() == 0)
            || (!(r instanceof BundleResource) && r.getFile().isDirectory())) {
        f.mkdirs();//from   www  .  jav  a 2  s  .co  m
        String path = r.getURI().getPath();
        for (org.springframework.core.io.Resource resource : p
                .getResources(path.substring(path.indexOf("/toursdb")))) {
            extract(p, resource, new File(f, resource.getFilename()));
        }
    } else {
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(f);
            IOUtils.copy(r.getInputStream(), output);
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:org.red5.server.stream.RecordingListener.java

/**
 * Get the file we'd be recording to based on scope and given name.
 *
 * @param scope//  w  w  w .j  a v a 2 s .  co m
 *            scope
 * @param name
 *            name
 * @return file
 */
public static File getRecordFile(IScope scope, String name) {
    // get stream filename generator
    IStreamFilenameGenerator generator = (IStreamFilenameGenerator) ScopeUtils.getScopeService(scope,
            IStreamFilenameGenerator.class, DefaultStreamFilenameGenerator.class);
    // generate filename
    String fileName = generator.generateFilename(scope, name, ".flv", GenerationType.RECORD);
    File file = null;
    if (generator.resolvesToAbsolutePath()) {
        file = new File(fileName);
    } else {
        Resource resource = scope.getContext().getResource(fileName);
        if (resource.exists()) {
            try {
                file = resource.getFile();
                log.debug("File exists: {} writable: {}", file.exists(), file.canWrite());
            } catch (IOException ioe) {
                log.error("File error: {}", ioe);
            }
        } else {
            String appScopeName = ScopeUtils.findApplication(scope).getName();
            file = new File(
                    String.format("%s/webapps/%s/%s", System.getProperty("red5.root"), appScopeName, fileName));
        }
    }
    return file;
}

From source file:io.servicecomb.foundation.common.utils.Log4jUtils.java

private static void outputFile(List<Resource> resList, Properties properties)
        throws IOException, URISyntaxException {
    //??class???outputFile??log???
    //must create org.slf4j.impl.Log4jLoggerAdapter by LoggerExtFactory
    //in order to redefine Log4jLoggerAdapter before other class load Log4jLoggerAdapter
    Logger log = LoggerFactory.getLogger(Log4jUtils.class);

    String content = genFileContext(resList, properties);
    //????,??//from ww w.j  a  va  2s. c o m
    //log.info("Merged log4j:\n{}", content);

    Resource res = resList.get(resList.size() - 1);
    // ?res.getFilejar??getFile
    File file = new File(res.getURL().getPath());
    if (!file.getParentFile().canWrite()) {
        log.error("Can not output {},because can not write to directory of file {}", MERGED_FILE,
                res.getURL().getPath());
        return;
    }

    File mergedfile = new File(res.getFile().getParentFile(), MERGED_FILE);
    FileUtils.writeStringToFile(mergedfile, content);
    log.info("Write merged log4j config file to {}", mergedfile.getAbsolutePath());
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

protected static Resource getDefaultWaveMakerHome() {

    Resource userHome = null;// w  w  w  .  j av  a2  s. c  o  m
    if (SystemUtils.IS_OS_WINDOWS) {
        String userProfileEnvVar = System.getenv("USERPROFILE");
        if (StringUtils.hasText(userProfileEnvVar)) {
            userProfileEnvVar = userProfileEnvVar.endsWith("/") ? userProfileEnvVar : userProfileEnvVar + "/";
            userHome = new FileSystemResource(System.getenv("USERPROFILE"));
        }
    }
    if (userHome == null) {
        String userHomeProp = System.getProperty("user.home");
        userHomeProp = userHomeProp.endsWith("/") ? userHomeProp : userHomeProp + "/";
        userHome = new FileSystemResource(userHomeProp);
    }

    String osVersionStr = System.getProperty("os.version");
    if (osVersionStr.contains(".")) {
        String sub = osVersionStr.substring(osVersionStr.indexOf(".") + 1);
        if (sub.contains(".")) {
            osVersionStr = osVersionStr.substring(0, osVersionStr.indexOf('.', osVersionStr.indexOf('.') + 1));
        }
    }

    try {
        if (SystemUtils.IS_OS_WINDOWS) {
            userHome = new FileSystemResource(
                    javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory());
        } else if (SystemUtils.IS_OS_MAC) {
            userHome = userHome.createRelative("Documents/");
        }

        if (!userHome.exists()) {
            throw new WMRuntimeException(MessageResource.PROJECT_USERHOMEDNE, userHome);
        }

        Resource wmHome = userHome.createRelative(WAVEMAKER_HOME);
        if (!wmHome.exists()) {
            wmHome.getFile().mkdir();
        }
        return wmHome;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:com.netxforge.oss2.core.xml.CastorUtils.java

/**
 * Marshal a Castor XML configuration file.
 *
 * @param obj the object representing the objected to be marshalled to XML
 * @throws org.springframework.dao.DataAccessException if the underlying Castor
 *      Marshaller.marshal() call throws a MarshalException or
 *      ValidationException.  The underlying exception will be translated
 *      using MarshallingExceptionTranslator.
 * @param resource a {@link org.springframework.core.io.Resource} object.
 *//* w  ww  .j  a  va2s .co m*/
public static void marshalWithTranslatedExceptionsViaString(Object obj, Resource resource)
        throws DataAccessException {
    Writer fileWriter = null;
    try {
        StringWriter writer = new StringWriter();
        marshal(obj, writer);

        fileWriter = new OutputStreamWriter(new FileOutputStream(resource.getFile()), "UTF-8");
        fileWriter.write(writer.toString());
        fileWriter.flush();

    } catch (IOException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("marshalling XML file", e);
    } catch (MarshalException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("marshalling XML file", e);
    } catch (ValidationException e) {
        throw CASTOR_EXCEPTION_TRANSLATOR.translate("marshalling XML file", e);
    } finally {
        IOUtils.closeQuietly(fileWriter);
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

public static void setWaveMakerHome(Resource wmHome) throws FileAccessException {
    Assert.isInstanceOf(FileSystemResource.class, wmHome, "Expected a FileSystemResource");

    try {// w  ww. j a  v a 2  s.  c  o m
        ConfigurationStore.setVersionedPreference(LocalStudioConfiguration.class, WMHOME_KEY,
                wmHome.getFile().getCanonicalPath());
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }

    if (!wmHome.exists()) {
        ((FileSystemResource) wmHome).getFile().mkdirs();
    }
}

From source file:com.seer.datacruncher.utils.generic.CommonUtils.java

public static File getResourceFile(String path) throws IOException {
    ApplicationContext context = AppContext.getApplicationContext();
    Resource r = context.getResource(path);
    if (r.exists()) {
        return r.getFile();
    } else {/*from w w  w .  ja va2s.c o m*/
        return new File(AppContext.getApplicationContext().getResource("/").getFile().getAbsolutePath() + path);
    }
}