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

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

Introduction

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

Prototype

public static boolean contentEquals(File file1, File file2) throws IOException 

Source Link

Document

Compares the contents of two files to determine if they are equal or not.

Usage

From source file:com.itextpdf.tool.xml.net.FileRetrieveTest.java

@Test
public void retrieveFile() throws MalformedURLException, IOException {
    final FileOutputStream out = new FileOutputStream(actual);
    retriever.addRootDir(new File("./src/test/resources"));
    retriever.processFromHref("/css/test.css", new ReadingProcessor() {

        public void process(final int inbit) {
            try {
                out.write((char) inbit);
            } catch (IOException e) {
                throw new RuntimeWorkerException(e);
            }//  w  w w .  java  2  s.c  o m
        }
    });
    out.close();
    Assert.assertTrue(FileUtils.contentEquals(expected, actual));
}

From source file:com.ftb2om2.view.ConverterNGTest.java

@Test(enabled = true)
public void FtbAirReaderTreeToOsuMania() throws Exception {
    System.out.println("Testing conversion between FtBAir and o!m");
    String x = getClass().getResource("/").getPath();
    String inputFilePath = getClass().getResource("/ftbAirTest1.txt").getPath();
    String outputFilePath = getClass().getResource("/").getPath();
    String name = "osuTestOutput1";
    Integer volume = 100;/*  w  w w. j a  v  a 2s .c o  m*/
    Metadata metadata = new Metadata("", "", "", "", "", "");
    Converter instance = new Converter(new FtbAirReaderTree(), new OsuManiaV14Writer());
    instance.convert(inputFilePath, outputFilePath, name, volume, metadata);
    // TODO review the generated test code and remove the default call to fail.
    File correctOutput = new File(getClass().getResource("/osuCorrectOutput1.osu").getPath());
    File generatedOutput = new File(getClass().getResource("/osuTestOutput1.osu").getPath());
    assertTrue(FileUtils.contentEquals(correctOutput, generatedOutput));
}

From source file:com.admc.jcreole.CreoleParseTest.java

@org.junit.Test
public void parseTest() throws IOException {
    if (htmlExpectFile != null)
        assertNotNull("Missing expect file: " + htmlExpectFile.getAbsolutePath(), htmlFile);
    Object retVal = null;/*from  ww w. ja va2  s. c om*/
    try {
        CreoleParser parser = new CreoleParser();
        parser.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
        /* Replace the statement above with something like this to test
         * privileges:
        parser.setPrivileges(EnumSet.of(
            JCreolePrivilege.ENUMFORMATS,
            JCreolePrivilege.TOC,
            JCreolePrivilege.RAWHTML,
            JCreolePrivilege.STYLESHEET,
            JCreolePrivilege.JCXBLOCK,
            JCreolePrivilege.JCXSPAN,
            JCreolePrivilege.STYLER
        ));
        */
        parser.setInterWikiMapper(new InterWikiMapper() {
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        retVal = parser.parse(CreoleScanner.newCreoleScanner(creoleFile, false, null));
    } catch (Exception e) {
        if (!shouldSucceed)
            return; // A ok.  No output file to write.
        AssertionError ae = new AssertionError("Failed to parse '" + creoleFile + "'");
        ae.initCause(e);
        throw ae;
    }
    FileUtils.writeStringToFile(htmlFile, ((retVal == null) ? "" : (((WashedSymbol) retVal).toString())),
            "UTF-8");
    if (!shouldSucceed)
        fail("Should have failed, but generated '" + htmlFile + "'");
    assertTrue("From '" + creoleFile + "':  '" + htmlFile + "' != '" + htmlExpectFile + "'",
            FileUtils.contentEquals(htmlExpectFile, htmlFile));
    htmlFile.delete();
}

From source file:de.clusteval.utils.TestRepositoryObject.java

/**
 * Test method for//  w  w  w  .j av a 2  s .c o m
 * {@link framework.repository.RepositoryObject#copyTo(java.io.File)}.
 * 
 * @throws IOException
 * @throws RegisterException
 * 
 */
@Test
public void testCopyToFile() throws IOException, RegisterException {
    File f = new File("testCaseRepository/data/goldstandards/DS1/Zachary_karate_club_gold_standard.txt")
            .getAbsoluteFile();
    this.repositoryObject = new StubRepositoryObject(this.getRepository(), false, f.lastModified(), f);
    File destF = new File(
            "testCaseRepository/data/goldstandards/DS1/Zachary_karate_club_gold_standard_copy.txt")
                    .getAbsoluteFile();
    if (destF.exists())
        file.FileUtils.delete(destF);
    this.repositoryObject.copyTo(destF);
    Assert.assertTrue(destF.exists());
    FileUtils.contentEquals(f, destF);
    file.FileUtils.delete(destF);
}

From source file:edu.cornell.med.icb.goby.modes.TestReformatCompactReadsMode.java

/**
 * Validates that a file can be reformatted to change the chunk size.
 *
 * @throws IOException if there is a problem reading or writing to the files
 *//*w  w  w.jav a  2 s .  c  o m*/
@Test
public void reformatChunkSize() throws IOException {
    final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode();

    final String inputFilename = "test-data/compact-reads/s_1_sequence_short.compact-reads";
    reformat.setInputFilenames(inputFilename);
    reformat.setSequencePerChunk(1);
    final String outputFilename = "test-results/reformat-test-chunk-size.compact-reads";
    reformat.setOutputFile(outputFilename);
    reformat.execute();

    final File inputFile = new File(inputFilename);
    final File outputFile = new File(outputFilename);
    assertFalse("The reformatted file should not be the same as the original",
            FileUtils.contentEquals(inputFile, outputFile));

    final ReadsReader inputReader = new ReadsReader(FileUtils.openInputStream(inputFile));
    assertTrue("There should be reads in this file", inputReader.hasNext());

    final List<Reads.ReadEntry> inputEntries = new ArrayList<Reads.ReadEntry>(73);
    for (final Reads.ReadEntry entry : inputReader) {
        inputEntries.add(entry);
    }

    final ReadsReader outputReader = new ReadsReader(FileUtils.openInputStream(outputFile));
    assertTrue("There should be reads in this file", outputReader.hasNext());

    final List<Reads.ReadEntry> outputEntries = new ArrayList<Reads.ReadEntry>(73);
    for (final Reads.ReadEntry entry : outputReader) {
        outputEntries.add(entry);
    }

    assertEquals("The entries of both files should be equal", inputEntries, outputEntries);
}

From source file:functionaltests.RestSchedulerPushPullFileTest.java

public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception {
    File testPushFile = RestFuncTHelper.getDefaultJobXmlfile();
    // you can test pushing pulling a big file :
    // testPushFile = new File("path_to_a_big_file");
    File destFile = new File(new File(spacePath, destPath), testPushFile.getName());
    if (destFile.exists()) {
        destFile.delete();/*from  w  w w . java2s  . c  o m*/
    }

    // PUSHING THE FILE
    String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));
    // either we encode or we test human readable path (with no special character inside)

    HttpPost reqPush = new HttpPost(pushfileUrl);
    setSessionHeader(reqPush);
    // we push a xml job as a simple test

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("fileName", new StringBody(testPushFile.getName()));
    multipartEntity.addPart("fileContent", new InputStreamBody(FileUtils.openInputStream(testPushFile),
            MediaType.APPLICATION_OCTET_STREAM, null));
    reqPush.setEntity(multipartEntity);
    HttpResponse response = executeUriRequest(reqPush);

    System.out.println(response.getStatusLine());
    assertHttpStatusOK(response);
    Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists());

    Assert.assertTrue("Original file and result are equals for " + spaceName,
            FileUtils.contentEquals(testPushFile, destFile));

    // LISTING THE TARGET DIRECTORY
    String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));

    HttpGet reqPullList = new HttpGet(pullListUrl);
    setSessionHeader(reqPullList);

    HttpResponse response2 = executeUriRequest(reqPullList);

    System.out.println(response2.getStatusLine());
    assertHttpStatusOK(response2);

    InputStream is = response2.getEntity().getContent();
    List<String> lines = IOUtils.readLines(is);
    HashSet<String> content = new HashSet<>(lines);
    System.out.println(lines);
    Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName()));

    // PULLING THE FILE
    String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(), "UTF-8")
                    : destPath.replace("\\", "/") + "/" + testPushFile.getName()));

    HttpGet reqPull = new HttpGet(pullfileUrl);
    setSessionHeader(reqPull);

    HttpResponse response3 = executeUriRequest(reqPull);

    System.out.println(response3.getStatusLine());
    assertHttpStatusOK(response3);

    InputStream is2 = response3.getEntity().getContent();

    File answerFile = tmpFolder.newFile();
    FileUtils.copyInputStreamToFile(is2, answerFile);

    Assert.assertTrue("Original file and result are equals for " + spaceName,
            FileUtils.contentEquals(answerFile, testPushFile));

    // DELETING THE HIERARCHY
    String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length());
    String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/"
            + (encode ? URLEncoder.encode(rootPath, "UTF-8") : rootPath.replace("\\", "/")));
    HttpDelete reqDelete = new HttpDelete(deleteUrl);
    setSessionHeader(reqDelete);

    HttpResponse response4 = executeUriRequest(reqDelete);

    System.out.println(response4.getStatusLine());

    assertHttpStatusOK(response4);

    Assert.assertTrue(destFile + " still exist", !destFile.exists());
}

From source file:de.nbi.ontology.test.OntologyMatchTest.java

/**
 * Test, if terms are properly match to concept labels. The a list of terms
 * contains a term in each line./*from   w  w  w  .  j av a  2  s .co  m*/
 * 
 * @param inFile
 *            a list of terms
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Test(dataProviderClass = TestFileProvider.class, dataProvider = "childTestFiles", groups = { "functest" })
public void children(File inFile) throws IOException {
    log.info("Processing " + inFile.getName());
    String basename = FilenameUtils.removeExtension(inFile.getAbsolutePath());
    File outFile = new File(basename + ".out");
    File resFile = new File(basename + ".res");

    List<String> terms = FileUtils.readLines(inFile);
    PrintWriter w = new PrintWriter(new FileWriter(outFile));
    for (String term : terms) {
        log.trace("** matching " + term);
        OntClass clazz = index.getModel().getOntClass(term);
        w.println(index.getChildren(clazz));
    }
    w.flush();
    w.close();

    Assert.assertTrue(FileUtils.contentEquals(outFile, resFile));
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.text.TokenizedTextWriterTest.java

@Test
public void testStopwords() throws UIMAException, IOException {
    File targetFile = new File(context.getTestOutputFolder(), "TokenizedTextWriterNoStopwords.out");
    targetFile.deleteOnExit();//from   w w  w  . j av a  2s .  com
    File tokenized = new File("src/test/resources/tokenizedTexts/textTokenizedNoStopwords.txt");
    String text = "This is the 1st sentence .\nHere is another sentence .";
    String stopwordsFile = "src/test/resources/stopwords_en.txt";

    AnalysisEngineDescription writer = createEngineDescription(TokenizedTextWriter.class,
            TokenizedTextWriter.PARAM_TARGET_LOCATION, targetFile, TokenizedTextWriter.PARAM_STOPWORDS_FILE,
            stopwordsFile, TokenizedTextWriter.PARAM_SINGULAR_TARGET, true, TokenizedTextWriter.PARAM_OVERWRITE,
            true);
    TestRunner.runTest("id", writer, "en", text);
    assertTrue(FileUtils.contentEquals(tokenized, targetFile));
}

From source file:com.innoq.ldap.connector.Utils.java

public static boolean compareFiles(final File file1, final File file2) {
    try {//from   ww  w  .  j  ava 2s  . com
        return FileUtils.contentEquals(file1, file2);
    } catch (IOException ex) {
        LOG.log(Level.WARNING, ex.getLocalizedMessage(), ex);
        return false;
    }
}

From source file:avantssar.aslanpp.testing.TranslationInstance.java

private void filesCompared(PrintStream out, File f, File ref, String label, boolean odd) {
    out.print("<td");
    boolean different = false;
    if (f != null && ref != null) {
        try {/*from  www.j ava2s .  c o m*/
            different = !FileUtils.contentEquals(f, ref);
            out.print(" style='background-color: ");
            if (different) {
                out.print(TranslationReport.RED(odd));
            } else {
                out.print(TranslationReport.GREEN(odd));
            }
            out.print(";'");
        } catch (IOException e) {
            Debug.logger.error("Failed to compare files '" + f.getAbsolutePath() + "' and '"
                    + ref.getAbsolutePath() + "'.", e);
        }
    }
    out.print(">");
    HTMLHelper.fileOrDash(out, outputDir, f, null);
    if (ref != null && different) {
        out.print(" ");
        HTMLHelper.fileOrDash(out, outputDir, ref, label);
    }
    out.println("</td>");
}