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

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

Introduction

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

Prototype

public static long checksumCRC32(File file) throws IOException 

Source Link

Document

Computes the checksum of a file using the CRC32 checksum routine.

Usage

From source file:org.sipfoundry.sipxconfig.cert.JavaKeyStoreTest.java

@Test
public void storeIfDifferentAuth() throws IOException {
    String cert = IOUtils.toString(getClass().getResourceAsStream("ca.test.crt"));
    JavaKeyStore a = storeFromCert(cert);
    File f = new File(TestHelper.getTestDirectory(), "store-auth-if-different-test.keystore");
    if (f.exists()) {
        f.delete();/*www. j  av a 2  s. com*/
    }

    a.storeIfDifferent(f);
    long checksumBefore = FileUtils.checksumCRC32(f);
    JavaKeyStore b = storeFromCert(cert);
    b.storeIfDifferent(f);
    long checksumAfter = FileUtils.checksumCRC32(f);
    assertEquals(checksumBefore, checksumAfter);
    JavaKeyStore c = storeFromCert(cert);
    c.addAuthority("test2", cert);
    c.storeIfDifferent(f);
    long checksumAfterChange = FileUtils.checksumCRC32(f);
    assertNotSame(checksumBefore, checksumAfterChange);
}

From source file:org.slc.sli.api.resources.BulkExtractTest.java

@Test
public void testGetSampleExtract() throws Exception {
    injector.setEducatorContext();//from  ww w.  j av  a  2 s . co m

    ResponseImpl res = (ResponseImpl) bulkExtract.get(req);
    assertEquals(200, res.getStatus());
    MultivaluedMap<String, Object> headers = res.getMetadata();
    assertNotNull(headers);
    assertTrue(headers.containsKey("content-disposition"));
    assertTrue(headers.containsKey("last-modified"));
    String header = (String) headers.getFirst("content-disposition");
    assertNotNull(header);
    assertTrue(header.startsWith("attachment"));
    assertTrue(header.indexOf("sample-extract.tar") > 0);

    Object entity = res.getEntity();
    assertNotNull(entity);
    StreamingOutput out = (StreamingOutput) entity;
    File file = new File("out.zip");
    FileOutputStream os = new FileOutputStream(file);
    out.write(os);
    os.flush();
    assertTrue(file.exists());

    assertEquals(798669192L, FileUtils.checksumCRC32(file));
    FileUtils.deleteQuietly(file);
}

From source file:org.structr.common.FileHelper.java

/**
 * Calculate CRC32 checksum of given file
 * // ww w .  j av  a 2s . c  o m
 * @param file
 * @return 
 */
public static Long getChecksum(final org.structr.core.entity.File file) {

    String relativeFilePath = file.getRelativeFilePath();

    if (relativeFilePath != null) {

        String filePath = Services.getFilePath(Path.Files, relativeFilePath);
        java.io.File fileOnDisk = new java.io.File(filePath);
        Long checksum;

        try {

            checksum = FileUtils.checksumCRC32(fileOnDisk);

            logger.log(Level.FINE, "Checksum of file {0} ({1}): {2}",
                    new Object[] { file.getUuid(), filePath, checksum });

            return checksum;

        } catch (Exception ex) {

            logger.log(Level.WARNING, "Could not calculate checksum of file " + filePath, ex);

        }

    }

    return null;

}

From source file:org.structr.web.common.FileHelper.java

/**
 * Calculate CRC32 checksum of given file
 *
 * @param file//from  ww w .j av  a 2  s  . c o m
 * @return checksum
 */
public static Long getChecksum(final FileBase file) {

    String relativeFilePath = file.getRelativeFilePath();

    if (relativeFilePath != null) {

        String filePath = getFilePath(relativeFilePath);

        try {

            java.io.File fileOnDisk = new java.io.File(filePath);
            Long checksum = FileUtils.checksumCRC32(fileOnDisk);

            logger.log(Level.FINE, "Checksum of file {0} ({1}): {2}",
                    new Object[] { file.getUuid(), filePath, checksum });

            return checksum;

        } catch (IOException ex) {

            logger.log(Level.WARNING, "Could not calculate checksum of file {0}", filePath);

        }

    }

    return null;

}

From source file:org.structr.web.Importer.java

private Linkable downloadFile(String downloadAddress, final URL base) {

    final String uuid = UUID.randomUUID().toString().replaceAll("[\\-]+", "");
    String contentType;//from www  .  java2  s .  c  o  m

    // Create temporary file with new uuid
    // FIXME: This is much too dangerous!
    final String relativeFilePath = File.getDirectoryPath(uuid) + "/" + uuid;
    final String filePath = FileHelper.getFilePath(relativeFilePath);
    final java.io.File fileOnDisk = new java.io.File(filePath);

    fileOnDisk.getParentFile().mkdirs();

    long size;
    long checksum;
    URL downloadUrl;

    try {

        downloadUrl = new URL(base, downloadAddress);

        logger.log(Level.INFO, "Starting download from {0}", downloadUrl);

        copyURLToFile(downloadUrl.toString(), fileOnDisk);

    } catch (IOException ioe) {

        if (originalUrl == null || address == null) {

            logger.log(Level.INFO, "Cannot download from {0} without base address", downloadAddress);
            return null;

        }

        logger.log(Level.WARNING, "Unable to download from {0} {1}",
                new Object[] { originalUrl, downloadAddress });
        ioe.printStackTrace();

        try {
            // Try alternative baseUrl with trailing "/"
            if (address.endsWith("/")) {

                // don't append a second slash!
                logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}",
                        new Object[] { originalUrl, address, downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address), downloadAddress);

            } else {

                // append a slash
                logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}",
                        new Object[] { originalUrl, address.concat("/"), downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address.concat("/")), downloadAddress);
            }

            copyURLToFile(downloadUrl.toString(), fileOnDisk);

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            logger.log(Level.SEVERE, "Could not resolve address {0}", address.concat("/"));
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            logger.log(Level.WARNING, "Unable to download from {0}", address.concat("/"));
            return null;
        }

        logger.log(Level.INFO, "Starting download from alternative URL {0}", downloadUrl);

    }

    downloadAddress = StringUtils.substringBefore(downloadAddress, "?");
    final String fileName = PathHelper.getName(downloadAddress);

    if (StringUtils.isBlank(fileName)) {

        logger.log(Level.WARNING, "Can't figure out filename from download address {0}, aborting.",
                downloadAddress);

        return null;
    }

    // TODO: Add security features like null/integrity/virus checking before copying it to
    // the files repo
    try {

        contentType = FileHelper.getContentMimeType(fileOnDisk, fileName);
        size = fileOnDisk.length();
        checksum = FileUtils.checksumCRC32(fileOnDisk);

    } catch (IOException ioe) {

        logger.log(Level.WARNING, "Unable to determine MIME type, size or checksum of {0}", fileOnDisk);
        return null;
    }

    String httpPrefix = "http://";

    logger.log(Level.INFO, "Download URL: {0}, address: {1}, cleaned address: {2}, filename: {3}",
            new Object[] { downloadUrl, address, StringUtils.substringBeforeLast(address, "/"), fileName });

    String relativePath = StringUtils.substringAfter(downloadUrl.toString(),
            StringUtils.substringBeforeLast(address, "/"));
    if (StringUtils.isBlank(relativePath)) {
        relativePath = downloadAddress;
    }

    final String path = StringUtils.substringBefore(
            ((downloadAddress.contains(httpPrefix)) ? StringUtils.substringAfter(downloadAddress, "http://")
                    : relativePath),
            fileName);

    logger.log(Level.INFO, "Relative path: {0}, final path: {1}", new Object[] { relativePath, path });

    if (contentType.equals("text/plain")) {

        contentType = StringUtils.defaultIfBlank(
                contentTypeForExtension.get(StringUtils.substringAfterLast(fileName, ".")), "text/plain");
    }

    final String ct = contentType;

    try {

        FileBase fileNode = fileExists(fileName, checksum);
        if (fileNode == null) {

            if (ImageHelper.isImageType(fileName)) {

                fileNode = createImageNode(uuid, fileName, ct, size, checksum);
            } else {

                fileNode = createFileNode(uuid, fileName, ct, size, checksum);
            }

            if (fileNode != null) {

                Folder parent = FileHelper.createFolderPath(securityContext, path);

                if (parent != null) {

                    fileNode.setProperty(File.parent, parent);

                }

                if (contentType.equals("text/css")) {

                    processCssFileNode(fileNode, downloadUrl);
                }

                if (!fileNode.validatePath(securityContext, null)) {
                    fileNode.setProperty(AbstractNode.name,
                            fileName.concat("_").concat(FileHelper.getDateString()));
                }

            }

            return fileNode;

        } else {

            fileOnDisk.delete();
            return fileNode;
        }

    } catch (FrameworkException | IOException fex) {

        logger.log(Level.WARNING, "Could not create file node.", fex);

    }

    return null;

}

From source file:org.tat.api.WebAppOptimizerMojo.java

private String getCheckSum(File file) throws IOException {
    Long checksum = FileUtils.checksumCRC32(file);
    return Long.toHexString(checksum) + "." + FilenameUtils.getExtension(file.getName());
}

From source file:org.wildfly.core.test.standalone.mgmt.api.ModelPersistenceTestCase.java

@Test
public void testSimpleOperation() throws Exception {

    CfgFileDescription lastBackupDesc = getLatestBackup(currentCfgDir);

    long lastFileHash = Files.exists(lastCfgFile) ? FileUtils.checksumCRC32(lastCfgFile.toFile()) : -1;
    ModelNode op;/*from   w ww .  j  a v a  2  s . co m*/
    CfgFileDescription newBackupDesc;

    try {
        // execute operation so the model gets updated
        op = createOpNode("system-property=test", "add");
        op.get("value").set("test");
        executeOperation(op);

        // check that the automated snapshat has been generated
        newBackupDesc = getLatestBackup(currentCfgDir);
        assertNotNull("Model snapshot not found.", newBackupDesc);
        // check that the version is incremented by one
        assertTrue(lastBackupDesc.version == newBackupDesc.version - 1);

        // check that the last cfg file has changed
        assertTrue(lastFileHash != FileUtils.checksumCRC32(lastCfgFile.toFile()));
    } finally {
        // remove testing attribute
        op = createOpNode("system-property=test", "remove");
        executeOperation(op);
    }

    // check that the snapshot has been updated again
    lastBackupDesc = newBackupDesc;
    newBackupDesc = getLatestBackup(currentCfgDir);
    assertNotNull("Model snapshot not found.", newBackupDesc);
    // check that the version is incremented by one
    assertEquals("Version was not properly incremented", lastBackupDesc.version, newBackupDesc.version - 1);
}

From source file:org.wildfly.core.test.standalone.mgmt.api.ModelPersistenceTestCase.java

@Test
public void testTakeAndDeleteSnapshot() throws Exception {

    // take snapshot

    ModelNode op = createOpNode(null, "take-snapshot");
    ModelNode result = executeOperation(op);

    // check that the snapshot file exists
    String snapshotFileName = result.asString();
    File snapshotFile = new File(snapshotFileName);
    assertTrue(snapshotFile.exists());/* w w w  . j a  va 2 s  .  c  o  m*/

    // compare with current cfg
    long snapshotHash = FileUtils.checksumCRC32(snapshotFile);
    long lastHash = FileUtils.checksumCRC32(lastCfgFile.toFile());
    assertEquals(snapshotHash, lastHash);

    // delete snapshot
    op = createOpNode(null, "delete-snapshot");
    op.get("name").set(snapshotFile.getName());
    executeOperation(op);
    // check that the file is deleted
    assertFalse("Snapshot file still exists.", snapshotFile.exists());

}

From source file:org.wildfly.core.test.standalone.mgmt.api.ModelPersistenceTestCase.java

private CfgFileDescription getLatestBackup(Path dir) throws IOException {

    final int[] lastVersion = { 0 };
    final File[] lastFile = { null };

    if (Files.isDirectory(dir)) {
        try (Stream<Path> files = Files.list(dir)) {
            files.filter(file -> {//  ww w .ja  v a 2  s.co m
                String fileName = file.getFileName().toString();
                String[] nameParts = fileName.split("\\.");
                return !(!nameParts[0].contains("standalone") && !nameParts[2].equals("xml"));
            }).forEach(path -> {
                String fileName = path.getFileName().toString();
                String[] nameParts = fileName.split("\\.");
                if (!nameParts[0].contains("standalone")) {
                    return;
                }
                if (!nameParts[2].equals("xml")) {
                    return;
                }
                int version = Integer.valueOf(nameParts[1].substring(1));
                if (version > lastVersion[0]) {
                    lastVersion[0] = version;
                    lastFile[0] = path.toFile();
                }
            });
        }
    }
    return new CfgFileDescription(lastVersion[0], lastFile[0],
            (lastFile[0] != null) ? FileUtils.checksumCRC32(lastFile[0]) : 0);
}

From source file:resources.ForecastDB.ForecastDataManager.java

private void checkNRestoreDB(String dbLocation, String backupLoc) {
    File backupFile = new File(backupLoc);
    File file = new File(dbLocation);

    try {//w w w  .  j  a  v  a 2  s . c  om
        long backupCSUM = FileUtils.checksumCRC32(backupFile);
        long csum = FileUtils.checksumCRC32(file);
        if (csum == backupCSUM) {//No Problem
            System.out.println("No Prob");
        } else {
            System.out.println("Something is wrong with your file both doesn't match");
            //Resotre file
            FileUtils.copyFile(backupFile, file);

        }

    } catch (IOException ex) {
        Logger.getLogger(ForecastDataManager.class.getName()).log(Level.SEVERE, null, ex);
    }
}