Example usage for org.apache.commons.io FileUtils readFileToString

List of usage examples for org.apache.commons.io FileUtils readFileToString

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToString.

Prototype

public static String readFileToString(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a String using the default encoding for the VM.

Usage

From source file:eu.seaclouds.platform.dashboard.proxy.MonitorProxyTest.java

@Test
public void testListMonitoringRules() throws Exception {
    URL resource = Resources.getResource(TestFixtures.MONITORING_RULES_PATH);
    String xml = FileUtils.readFileToString(new File(resource.getFile()));

    getMockWebServer().enqueue(new MockResponse().setBody(xml).setHeader("Accept", MediaType.APPLICATION_XML)
            .setHeader("Content-Type", MediaType.APPLICATION_XML));
    assertEquals(ObjectMapperHelpers.XmlToObject(xml, MonitoringRules.class), getProxy().listMonitoringRules());
}

From source file:de.tudarmstadt.ukp.dkpro.tc.features.readability.LexicalVariationExtractorTest.java

@Ignore
public void testLexicalVariationExtractor() throws Exception {
    String text = FileUtils.readFileToString(new File("src/test/resources/test_document_en.txt"));

    AnalysisEngineDescription desc = createEngineDescription(createEngineDescription(OpenNlpSegmenter.class),
            createEngineDescription(OpenNlpPosTagger.class), createEngineDescription(ClearNlpLemmatizer.class));
    AnalysisEngine engine = createEngine(desc);
    JCas jcas = engine.newJCas();/*w  w  w .j av  a2  s  .  c o m*/
    jcas.setDocumentLanguage("en");
    jcas.setDocumentText(text);
    engine.process(jcas);

    LexicalVariationExtractor extractor = new LexicalVariationExtractor();
    List<Feature> features = extractor.extract(jcas);

    Assert.assertEquals(14, features.size());

    Assert.assertEquals((double) features.get(0).getValue(), 4.2, 0.1);
    Assert.assertEquals((double) features.get(1).getValue(), 1.6, 0.1);
    Assert.assertEquals((double) features.get(2).getValue(), 0.9, 0.1);
    Assert.assertEquals((double) features.get(3).getValue(), 3.7, 0.1);
    Assert.assertEquals((double) features.get(4).getValue(), 0.4, 0.1);
    Assert.assertEquals((double) features.get(5).getValue(), 0.4, 0.1);
    Assert.assertEquals((double) features.get(6).getValue(), 1.75, 0.1);
    Assert.assertEquals((double) features.get(7).getValue(), 7.4, 0.1);
    Assert.assertEquals((double) features.get(8).getValue(), 0.15, 0.1);
    Assert.assertEquals((double) features.get(9).getValue(), 0.1, 0.1);
    Assert.assertEquals((double) features.get(10).getValue(), 0.2, 0.1);
    Assert.assertEquals((double) features.get(11).getValue(), 0.6, 0.1);
    Assert.assertEquals((double) features.get(12).getValue(), 1.5, 0.1);
    Assert.assertEquals((double) features.get(13).getValue(), 110.3, 0.1);
}

From source file:io.github.sn0cr.rapidRunner.testRunner.StdInOutMatcher.java

/**
 * @throws IOException/*from ww  w .j a va 2s .  c  o  m*/
 *
 */
public StdInOutMatcher(Pair<Path, Path> stdinOutFiles, Path workingDirectory, String[] arguments)
        throws IOException {
    this.stdErr = new LinkedList<String>();
    this.stdOut = new LinkedList<String>();
    this.input = FileUtils.readFileToString(stdinOutFiles.getA().toFile());
    this.expectedOutput = FileUtils.readFileToString(stdinOutFiles.getB().toFile());
    this.commandRunner = new CommandRunner(arguments, this.input, workingDirectory);
}

From source file:io.fabric8.kubernetes.pipeline.devops.ApplyTest.java

@Test
public void testRegistryNotAddedIfAlreadyPresent() throws Exception {
    String json = FileUtils.readFileToString(
            new File(this.getClass().getResource("/kubernetesJsonWithRegistry.json").toURI()));

    String registry = "MY-REGISTRY:5000";
    String expectedImageName = "myexternalregistry.io:5000/TEST_NS/my-test-image:TEST-1.0";
    testAddRegistryToImageName(json, registry, expectedImageName);

}

From source file:de.joinout.criztovyl.tools.json.JSONFile.java

/**
 * Loads JSON data from the given file//from  w ww  .  j a  va  2s. co  m
 * 
 * @param path
 */
public JSONFile(Path path) {

    logger = LogManager.getLogger();

    this.path = path;

    data = new JSONObject().toString();

    try {
        String data = FileUtils.readFileToString(path.getFile());

        if (!data.equals(""))
            this.data = data;

    } catch (final FileNotFoundException e) {
        logger.warn("File {} not found! (Maybe file wasn't created yet)", path.getPath());
        logger.catching(Level.WARN, e);
    } catch (final IOException e) {
        logger.catching(e);
    }

}

From source file:com.baeldung.yarg.DocumentController.java

@RequestMapping(path = "/generate/doc", method = RequestMethod.GET)
public void generateDocument(HttpServletResponse response) throws IOException {
    ReportBuilder reportBuilder = new ReportBuilder();
    ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder()
            .documentPath("./src/main/resources/Letter.docx").documentName("Letter.docx")
            .outputType(ReportOutputType.docx).readFileFromPath();
    reportBuilder.template(reportTemplateBuilder.build());
    BandBuilder bandBuilder = new BandBuilder();
    String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json"));
    ReportBand main = bandBuilder.name("Main").query("Main", "parameter=param1 $.main", "json").build();
    reportBuilder.band(main);//from w ww.jav  a 2  s. c om
    Report report = reportBuilder.build();

    Reporting reporting = new Reporting();
    reporting.setFormatterFactory(new DefaultFormatterFactory());
    reporting.setLoaderFactory(new DefaultLoaderFactory().setJsonDataLoader(new JsonDataLoader()));
    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream());
}

From source file:ch.sbb.releasetrain.config.ConfigAccessorImpl.java

@Override
public ReleaseConfig readConfig(String name) {
    if (!name.contains("-type")) {
        name = name + "-type";
    }/*w  w w.  j a  va  2s.com*/
    File dir = git.getRepo().directory();
    File file = new File(dir, "/" + name + ".yml");
    if (!file.exists()) {
        return null;
    }
    try {
        return accessorRelease.convertEntry(FileUtils.readFileToString(file));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return null;
}

From source file:de.tudarmstadt.ukp.dkpro.keyphrases.core.wrapper.CooccurrenceGraphExtractorTest.java

@Ignore
@Test//  w ww .  j  av a 2s  .c  o  m
public void cooccurrenceGraphExtractorTest() throws Exception {

    String testDoc = FileUtils.readFileToString(new File("src/test/resources/keyphrase/extractor/test.txt"));

    KeyphraseExtractor textRank = CooccurrenceGraphExtractor.createTextRankExtractor();

    System.out.println(textRank.getConfigurationDetails());
    for (Keyphrase keyphrase : getTopRankedUniqueKeyphrases(textRank.extract(testDoc), 5)) {
        System.out.println(keyphrase.getKeyphrase());
    }

    String textrankKeyphrases = StringUtils
            .join(keyphraseList2StringList(getTopRankedUniqueKeyphrases(textRank.extract(testDoc), 5)), ",");

    assertEquals("variable temporal rates,temporal rates,different temporal rates,"
            + "video object-based rate allocation,multiple video objects", textrankKeyphrases);

    CooccurrenceGraphExtractor cooccExtractor = new CooccurrenceGraphExtractor();
    cooccExtractor.setMinKeyphraseLength(2);
    cooccExtractor.setCandidate(new Candidate(CandidateType.Token, PosType.N));

    List<Keyphrase> keyphrases = cooccExtractor.extract(testDoc);
    assertEquals(28, keyphrases.size());

    List<Keyphrase> top5Keyphrases = getTopRankedUniqueKeyphrases(keyphrases, 5);
    assertEquals(5, top5Keyphrases.size());

    String cooccKeyphrases = StringUtils.join(keyphraseList2StringList(top5Keyphrases), ",");
    for (Keyphrase keyphrase : top5Keyphrases) {
        System.out.println(keyphrase);
    }

    System.out.println(cooccKeyphrases);
    assertEquals("rate allocation,target bit rate,algorithm deals,bit allocation,object level",
            cooccKeyphrases);
}

From source file:launcher.workflow.update.UpdateWorkflow.java

public static void begin(final Settings launcherCfg, final String license) {
    WorkflowStep prepare = new WorkflowStep("Preparing to launch the game", new WorkflowAction() {
        @Override// www . j  a  v  a  2  s.c  o  m
        public boolean act() {
            return true;
        }
    });
    WorkflowStep checkLicense = new WorkflowStep("Checking to see if a license has been entered.",
            new WorkflowAction() {
                @Override
                public boolean act() throws Exception {
                    if (license == null || license.isEmpty()) {
                        LaunchLogger.error(LaunchLogger.Tab + "No valid license found.");
                        return false;
                    }

                    WorkflowWindowManager.setProgressVisible(true);
                    URL licenseCheckUrl = new URL(launcherCfg.licenseCall(license));
                    String response = IOUtils.toString(licenseCheckUrl.openStream());
                    WorkflowWindowManager.setProgressVisible(false);
                    if (response.contains("true")) {
                        LaunchLogger.info(LaunchLogger.Tab + "License is valid.");
                        return true;
                    } else {
                        if (License.isCached()) {
                            LaunchLogger
                                    .info("Invalid license was found. Deleting the locally cached license.");
                            License.deleteCache();
                            return false;
                        }
                    }
                    return false;
                }
            });

    WorkflowStep checkVersion = new WorkflowStep("Checking for updates.", new WorkflowAction() {
        @Override
        public boolean act() throws Exception {
            File versionPath = new File("assets/data/version.dat");
            String myVersion = "0.0.0";
            if (versionPath.exists()) {
                myVersion = FileUtils.readFileToString(versionPath);
                LaunchLogger.info("Detected version: " + myVersion);
            }
            WorkflowWindowManager.setProgressVisible(true);
            URL versionCheckUrl = new URL(launcherCfg.versionCall(myVersion));

            String result = IOUtils.toString(versionCheckUrl.openStream());
            WorkflowWindowManager.setProgressVisible(false);
            if (result.contains("true")) {
                LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is out of date.");
                return true;
            }
            LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is up to date. No update required.");
            return false;
        }
    });

    WorkflowStep downloadUpdate = new WorkflowStep("Preparing the update location", new WorkflowAction() {
        @Override
        public boolean act() throws Exception {
            if (UpdateWorkflowData.UpdateArchive.exists()) {
                FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive);
            }

            int responseTimeoutMs = launcherCfg.responseTimeoutMilliseconds;
            int downloadTimeoutMs = launcherCfg.downloadTimeoutMilliseconds;
            LaunchLogger.info("Attempting to download an update using license: [" + license + "]");

            WorkflowWindowManager.setProgressVisible(true);
            String downloadUrl = launcherCfg.downloadCall(license, "update");
            LaunchLogger.info("Downloading latest stable edition");
            FileUtils.copyURLToFile(new URL(downloadUrl), UpdateWorkflowData.UpdateArchive, responseTimeoutMs,
                    downloadTimeoutMs);
            WorkflowWindowManager.setProgressVisible(false);

            LaunchLogger.info(LaunchLogger.Tab + "Update downloaded successfully.");
            return true;
        }
    });

    WorkflowStep applyUpdate = new WorkflowStep("Unpacking update archive", new WorkflowAction() {
        @Override
        public boolean act() throws IOException {
            WorkflowWindowManager.setProgressVisible(true);
            Archive.unzip(UpdateWorkflowData.UpdateArchive, UpdateWorkflowData.UpdateWorkingDirectory);
            LaunchLogger.info("Replacing old content");
            File game = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/game.jar");
            File gameTarget = new File("./");
            LaunchLogger.info("Attempting to copy: " + game + " to " + gameTarget);
            FileUtils.copyFileToDirectory(game, gameTarget);

            File assets = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/assets");
            File assetsTarget = new File("./assets");
            LaunchLogger.info("Attempting to copy: " + assets + " to " + assetsTarget);
            FileUtils.copyDirectory(assets, assetsTarget);
            WorkflowWindowManager.setProgressVisible(false);

            LaunchLogger.info(LaunchLogger.Tab + "Update applied successfully.");
            return true;
        }
    });

    WorkflowStep clean = new WorkflowStep("Cleaning up temporary files", new WorkflowAction() {
        @Override
        public boolean act() throws IOException {
            if (UpdateWorkflowData.UpdateArchive.exists()) {
                FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive);
            }
            if (UpdateWorkflowData.UpdateWorkingDirectory.exists()) {
                FileUtils.deleteDirectory(UpdateWorkflowData.UpdateWorkingDirectory);
            }
            return true;
        }
    });

    prepare.setOnSuccess(checkLicense);
    checkLicense.setOnSuccess(checkVersion);
    checkVersion.setOnSuccess(downloadUpdate);
    downloadUpdate.setOnSuccess(applyUpdate);
    applyUpdate.setOnSuccess(clean);

    prepare.setOnFailure(clean);
    checkLicense.setOnFailure(clean);
    checkVersion.setOnFailure(clean);
    downloadUpdate.setOnFailure(clean);
    applyUpdate.setOnFailure(clean);

    prepare.execute();
}

From source file:ch.medshare.elexis_directories.TestElexisDirectories.java

private List<KontaktEntry> compare_file_to_kontacts(File file, List<KontaktEntry> expectedKontakte)
        throws IOException {
    String content = FileUtils.readFileToString(file);
    DirectoriesContentParser parser = new DirectoriesContentParser(content);
    List<KontaktEntry> kontakte = parser.extractKontakte();
    if (expectedKontakte != null) {
        for (int j = 0; j < expectedKontakte.size(); j++) {
            KontaktEntry soll = expectedKontakte.get(j);
            KontaktEntry ist = kontakte.get(j);
            // we must compare the different fields
            Assert.assertEquals(soll.getName(), ist.getName());
            Assert.assertEquals(soll.getVorname(), ist.getVorname());
            Assert.assertEquals(soll.getZusatz(), ist.getZusatz());
            Assert.assertEquals(soll.getEmail(), ist.getEmail());
            Assert.assertEquals(soll.getAdresse(), ist.getAdresse());
            Assert.assertEquals(soll.getFax(), ist.getFax());
            Assert.assertEquals(soll.getOrt(), ist.getOrt());
            Assert.assertEquals(soll.getPlz(), ist.getPlz());
            Assert.assertEquals(soll.getTelefon(), ist.getTelefon());
        }//from w  w w. j  av a 2s  . co m
    }
    return kontakte;
}