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:de.extra.client.plugins.outputplugin.mtomws.WsCxfIT.java

/**
 * @return/*  w  ww . j a  v a  2s .  c o m*/
 * @throws XmlMappingException
 * @throws IOException
 */
private List<RequestTransport> createTestsTransportsWithFileAttachment()
        throws XmlMappingException, IOException {
    logger.info("Looking for Inptut into the Directory: " + inputDirectory.getAbsolutePath());
    final List<RequestTransport> transports = new ArrayList<RequestTransport>();
    final Collection<File> listFiles = FileUtils.listFiles(inputDirectory, TrueFileFilter.INSTANCE, null);
    for (final File inputFile : listFiles) {
        final RequestTransport requestTransport = createDummyRequestTransport();
        final RequestTransport filledTransport = fillInputFile(requestTransport, inputFile);
        transports.add(filledTransport);
        logger.info("Find File to send: " + inputFile.getName());
        logger.info("ChecksumCRC32: " + FileUtils.checksumCRC32(inputFile));
        logger.info("Filesize: " + FileUtils.sizeOf(inputFile));
    }
    return transports;
}

From source file:it.geosolutions.geostore.services.rest.auditing.AuditingTemplates.java

private long checksum(File file) {
    try {//w  ww  . j  av a  2s  . com
        return FileUtils.checksumCRC32(file);
    } catch (Exception exception) {
        throw new AuditingException(exception, "Error computign checksum of file '%s'.", file.getPath());
    }
}

From source file:algorithm.TarPackagingTest.java

@Test
public void singleTarPackagingTest() {
    try {//w  w  w .j  a va 2  s. c om
        File carrier = TestDataProvider.TXT_FILE;
        File payload = TestDataProvider.XML_FILE;
        TarPackaging algorithm = new TarPackaging();
        // Test encapsulation:
        List<File> carrierList = new ArrayList<File>();
        carrierList.add(carrier);
        List<File> payloadList = new ArrayList<File>();
        payloadList.add(payload);
        File outputFile = algorithm.encapsulate(carrier, payloadList);
        assertNotNull(outputFile);
        // Test restore:
        Hashtable<String, RestoredFile> outputHash = new Hashtable<String, RestoredFile>();
        for (RestoredFile file : algorithm.restore(outputFile)) {
            outputHash.put(file.getName(), file);
        }
        assertEquals(2, outputHash.size());
        RestoredFile restoredCarrier = outputHash.get(carrier.getName());
        RestoredFile restoredPayload = outputHash.get(payload.getName());
        assertNotNull(restoredCarrier);
        assertNotNull(restoredPayload);
        assertEquals(FileUtils.checksumCRC32(carrier), FileUtils.checksumCRC32(restoredCarrier));
        assertEquals(FileUtils.checksumCRC32(payload), FileUtils.checksumCRC32(restoredPayload));

        // check restoration metadata:
        // assertEquals("" + carrier.getAbsolutePath(),
        // restoredCarrier.originalFilePath);
        // assertEquals("" + payload.getAbsolutePath(),
        // restoredPayload.originalFilePath);
        assertEquals(algorithm, restoredCarrier.algorithm);
        assertTrue(restoredCarrier.checksumValid);
        assertTrue(restoredPayload.checksumValid);
        // Every file in a .tar archive is a payload file!
        assertTrue(restoredCarrier.wasPayload);
        assertFalse(restoredCarrier.wasCarrier);
        assertTrue(restoredPayload.wasPayload);
        assertFalse(restoredPayload.wasCarrier);
        assertTrue(restoredCarrier.relatedFiles.contains(restoredPayload));
        assertFalse(restoredCarrier.relatedFiles.contains(restoredCarrier));
        assertTrue(restoredPayload.relatedFiles.contains(restoredCarrier));
        assertFalse(restoredPayload.relatedFiles.contains(restoredPayload));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:algorithm.MetsSubmissionInformationPackage.java

@SuppressWarnings("unchecked")
@Override/*from  ww  w  .  j  a  v a 2  s.  c om*/
public File encapsulate(File carrier, List<File> userPayloadList) throws IOException {
    List<File> payloadList = new ArrayList<File>();
    payloadList.addAll(userPayloadList);
    Mets metsDocument = new Mets();
    metsDocument.setID(carrier.getName() + "_SIP");
    metsDocument.setLABEL("PeriCAT information package");
    metsDocument.setTYPE("digital object and metadata files");
    // HEADER:
    Agent periPack = new Agent();
    periPack.setID("peripack agent");
    periPack.setROLE(Role.PRESERVATION);
    periPack.setOTHERTYPE("SOFTWARE");
    Name name = new Name();
    PCData nameString = new PCData();
    nameString.add("peripack");
    name.getContent().add(nameString);
    periPack.getContent().add(name);
    Note note = new Note();
    PCData noteString = new PCData();
    noteString.add(TOOL_DESCRIPTION);
    note.getContent().add(noteString);
    periPack.getContent().add(note);
    MetsHdr header = new MetsHdr();
    header.setID("mets header");
    header.setCREATEDATE(new Date());
    header.setLASTMODDATE(new Date());
    header.setRECORDSTATUS("complete");
    header.getContent().add(periPack);
    if (truePersonButton.isSelected()) {
        Agent person = new Agent();
        person.setID("peripack user");
        person.setROLE(Role.CREATOR);
        person.setTYPE(Type.INDIVIDUAL);
        Name personName = new Name();
        PCData personNameString = new PCData();
        personNameString.add(personField.getText());
        personName.getContent().add(personNameString);
        person.getContent().add(personName);
        header.getContent().add(person);
    }
    metsDocument.getContent().add(header);
    // FILE SECTION:
    FileSec fileSection = new FileSec();
    FileGrp carrierGroup = new FileGrp();
    carrierGroup.setID("carrier files");
    carrierGroup.setUSE("digital object");
    // carrier div for structural map:
    Div carrierDiv = new Div();
    carrierDiv.setID("carrier list");
    carrierDiv.setTYPE("carrier files");
    // back to file section:
    edu.harvard.hul.ois.mets.File metsCarrier = new edu.harvard.hul.ois.mets.File();
    metsCarrier.setID(carrier.getAbsolutePath());
    metsCarrier.setGROUPID("carrier");
    metsCarrier.setCHECKSUM("" + FileUtils.checksumCRC32(carrier));
    metsCarrier.setMIMETYPE(Files.probeContentType(carrier.toPath()));
    metsCarrier.setOWNERID(Files.getOwner(carrier.toPath(), LinkOption.NOFOLLOW_LINKS).toString());
    metsCarrier.setSIZE(Files.size(carrier.toPath()));
    metsCarrier.setUSE(Files.getPosixFilePermissions(carrier.toPath(), LinkOption.NOFOLLOW_LINKS).toString());
    FLocat fileLocation = new FLocat();
    fileLocation.setXlinkHref(carrier.getAbsolutePath());
    fileLocation.setLOCTYPE(Loctype.OTHER);
    fileLocation.setOTHERLOCTYPE("system file path");
    fileLocation.setXlinkTitle("original file path of the carrier");
    metsCarrier.getContent().add(fileLocation);
    carrierGroup.getContent().add(metsCarrier);
    // add structural map information:
    Fptr carrierFilePointer = new Fptr();
    carrierFilePointer.setFILEID(carrier.getAbsolutePath());
    carrierDiv.getContent().add(carrierFilePointer);
    fileSection.getContent().add(carrierGroup);
    FileGrp payloadGroup = new FileGrp();
    payloadGroup.setID("payload files");
    payloadGroup.setUSE("metadata");

    // payload div for structural map:
    Div payloadDiv = new Div();
    payloadDiv.setID("payload list");
    payloadDiv.setTYPE("payload files");
    // back to file section:
    for (File payload : payloadList) {
        edu.harvard.hul.ois.mets.File metsPayload = new edu.harvard.hul.ois.mets.File();
        metsPayload.setID(payload.getAbsolutePath());
        metsPayload.setGROUPID("payload");
        metsPayload.setCHECKSUM(DigestUtils.md5Hex(new FileInputStream(payload)));
        metsPayload.setCHECKSUMTYPE(Checksumtype.MD5);
        metsPayload.setMIMETYPE(Files.probeContentType(payload.toPath()));
        metsPayload.setOWNERID(Files.getOwner(payload.toPath(), LinkOption.NOFOLLOW_LINKS).toString());
        metsPayload.setSIZE(Files.size(payload.toPath()));
        metsPayload
                .setUSE(Files.getPosixFilePermissions(payload.toPath(), LinkOption.NOFOLLOW_LINKS).toString());
        FLocat fileLocation2 = new FLocat();
        fileLocation2.setXlinkHref(payload.getAbsolutePath());
        fileLocation2.setLOCTYPE(Loctype.OTHER);
        fileLocation2.setOTHERLOCTYPE("system file path");
        fileLocation2.setXlinkTitle("original file path of the payload");
        metsPayload.getContent().add(fileLocation2);
        payloadGroup.getContent().add(metsPayload);
        // add structural map information:
        Fptr payloadFilePointer = new Fptr();
        payloadFilePointer.setFILEID(payload.getAbsolutePath());
        payloadDiv.getContent().add(payloadFilePointer);
    }
    fileSection.getContent().add(payloadGroup);
    metsDocument.getContent().add(fileSection);
    // STRUCTURAL MAP:
    StructMap structuralMap = new StructMap();
    structuralMap.setID("structural map");
    Div encapsulatedFiles = new Div();
    encapsulatedFiles.setID("peripack files");
    encapsulatedFiles.setTYPE("encapsulated files");
    structuralMap.getContent().add(encapsulatedFiles);
    encapsulatedFiles.getContent().add(carrierDiv);
    encapsulatedFiles.getContent().add(payloadDiv);
    metsDocument.getContent().add(structuralMap);
    File metsFile = new File(OUTPUT_DIRECTORY + "mets.xml");
    FileOutputStream outputStream = new FileOutputStream(metsFile);
    try {
        metsDocument.write(new MetsWriter(outputStream));
    } catch (MetsException e) {
    }
    outputStream.close();
    payloadList.add(metsFile);
    File outputFile = null;
    if (zipButton.isSelected()) {
        outputFile = new ZipPackaging().encapsulate(carrier, payloadList);

    } else if (tarButton.isSelected()) {
        outputFile = new TarPackaging().encapsulate(carrier, payloadList);
    }
    metsFile.delete();
    return outputFile;
}

From source file:modmanager.backend.ModificationOption.java

/**
 * Returns if given source file is installed
 *
 * @param file//w w  w .j av a 2 s . com
 * @return
 */
private boolean isInstalled(File file) {
    File destination = getDestinationFile(file);

    if (!destination.exists()) {
        return false;
    }
    if (destination.isDirectory() != file.isDirectory()) {
        return false;
    }

    if (file.length() <= 268435456L) {
        try {
            if (FileUtils.checksumCRC32(destination) != FileUtils.checksumCRC32(file)) {
                return false;
            }
        } catch (IOException ex) {
            Logger.getLogger(ModificationOption.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        logger.log(Level.INFO, "Skipping check file {0}: too large", file.getAbsolutePath());
    }

    //        try
    //        {
    //            if (!FileUtils.contentEquals(file, destination))
    //            {
    //                return false;
    //            }
    //        }
    //        catch (IOException ex)
    //        {
    //            Logger.getLogger(ModificationOption.class.getName()).log(Level.SEVERE, null, ex);
    //        }
    /**
     * more checks, hash, equal?
     */
    return true;
}

From source file:com.yifanlu.PSXperiaTool.Extractor.CrashBandicootExtractor.java

private void patchEmulator() throws IOException {
    Logger.info("Verifying the emulator binary.");
    Properties config = new Properties();
    config.loadFromXML(new FileInputStream(new File(mOutputDir, "/config/config.xml")));
    String emulatorName = config.getProperty("emulator_name", "libjava-activity.so");
    File origEmulator = new File(mOutputDir, "/lib/armeabi/" + emulatorName);
    String emulatorCRC32 = Long.toHexString(FileUtils.checksumCRC32(origEmulator));
    if (!emulatorCRC32.equalsIgnoreCase(config.getProperty("emulator_crc32")))
        throw new UnsupportedOperationException(
                "The emulator checksum is invalid. Cannot patch. CRC32: " + emulatorCRC32);
    File newEmulator = new File(mOutputDir, "/lib/armeabi/libjava-activity-patched.so");
    File emulatorPatch = new File(mOutputDir, "/config/" + config.getProperty("emulator_patch", ""));
    if (emulatorPatch.equals("")) {
        Logger.info("No patch needed.");
        FileUtils.moveFile(origEmulator, newEmulator);
    } else {/*from   ww  w .  j  av  a 2 s  .  c  o  m*/
        Logger.info("Patching emulator.");
        newEmulator.createNewFile();
        JBPatch.bspatch(origEmulator, newEmulator, emulatorPatch);
        emulatorPatch.delete();
    }
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/libjava-activity-wrapper.so"), origEmulator);
}

From source file:de.joinout.criztovyl.tools.directory.DirectoryChanges.java

/**
 * Checks, if two files are really different in the both lists by checking whether the checksums are different.
 * @param path a {@link Path} (should be from <code>current</code> or <code>previous</code>)
 * @return <code>true</code> if checksums are different and <code>false</code> if they are equal or the path is a directory.
 * @throws IOException If an I/O error occurs.
 *///www.ja  v  a  2s.  com
public boolean contentChanged(Path path) throws IOException {

    path = makeRelative(path);

    try {
        return FileUtils.checksumCRC32(current.getDirectory().append(path).realPath().getFile()) != FileUtils
                .checksumCRC32(previous.getDirectory().append(path).realPath().getFile());
    } catch (IllegalArgumentException e) { //Catch if is directory
        logger.warn("Cannot compare file {}, is directory.", path);
        return false;
    }
}

From source file:de.extra.client.plugins.responseprocessplugin.filesystem.FileSystemResultPackageDataResponseProcessPlugin.java

/**
 * @param responseId/*  w ww .  j a va 2s  .  c  o m*/
 * @param responseBody
 * @return fileName
 */
private String saveBodyToFilesystem(final String incomingFileName, final String responseId,
        final DataHandler packageBodyDataHandler) {
    try {

        final String dateiName = buildFilename(incomingFileName, responseId);

        final File responseFile = new File(eingangOrdner, dateiName);

        final FileOutputStream fileOutputStream = new FileOutputStream(responseFile);
        final String dataHandlerName = packageBodyDataHandler.getName();
        logger.info("Receiving File : " + dataHandlerName);

        IOUtils.copy(packageBodyDataHandler.getInputStream(), fileOutputStream);

        IOUtils.closeQuietly(fileOutputStream);

        logger.info("Input file is stored under " + responseFile.getAbsolutePath());
        logger.info("ChecksumCRC32 " + FileUtils.checksumCRC32(responseFile));
        logger.info("Filesize: " + FileUtils.sizeOf(responseFile));

        transportObserver.responseDataForwarded(responseFile.getAbsolutePath(), responseFile.length());

        logger.info("Response gespeichert in File: '" + dateiName + "'");

        return dateiName;
    } catch (final IOException ioException) {
        throw new ExtraResponseProcessPluginRuntimeException(ExceptionCode.UNEXPECTED_INTERNAL_EXCEPTION,
                "Fehler beim schreiben der Antwort", ioException);
    }
}

From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Create a unique identifier of file and it contents.
 *
 * @param file the file to checksum, must not be <code>null</code>
 * @return String identifier/*from w  w  w. j  a va2  s  .  c o  m*/
 * @throws IOException if an IO error occurs reading the file
 */
private static String makeHash(File file) throws IOException {
    return String.valueOf(FileUtils.checksumCRC32(file));
}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    l.info("Add game action activated");
    MainFrame.lockInterface();/*from ww w .j a v a 2s  .c om*/
    MainFrame.updateTask("Adding game...", true);
    AddGameDialog addGameDialog = new AddGameDialog(this, true);
    addGameDialog.setLocationRelativeTo(null);
    //addGameDialog.setVisible(true);
    final Game g = addGameDialog.popupCreateDialog();
    if (g != null) {
        l.trace("Analyzing game: " + g.gameAbsoluteFolderPath);
        MainFrame.updateTask("Adding game...", true);
        final int row = getNextFreeRowNumber();
        addFreeRow();
        jTable1.getModel().setValueAt(g.gameName, row, 0);
        jTable1.getModel().setValueAt(g.gameAbsoluteExecPath, row, 1);
        jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game", true, true);
        final ObjectPlaceholder obj = new ObjectPlaceholder();
        SwingWorker worker = new SwingWorker<Long, Void>() {

            @Override
            public Long doInBackground() throws IOException {
                l.trace("Checking size");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game size", true, true);
                obj.payload = FileUtils.sizeOfDirectory(new File(g.gameAbsoluteFolderPath));
                l.trace("Checking files");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game files", true, true);
                g.gameFileNumber = FileUtils.listFiles(new File(g.gameAbsoluteFolderPath), null, true).size();
                l.trace("Checking CRC32");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game signature", true, true);
                g.gameExecCRC32 = FileUtils.checksumCRC32(new File(g.gameAbsoluteExecPath));
                return ((Long) obj.payload);
            }

            public void done() {
                l.trace("Finishing game check");
                MainFrame.updateProgressBar(0, 0, 0, "Finishing game creation", false, false);
                g.gameSize = ((Long) obj.payload);
                /*
                double mbsize = Math.ceil(g.gameSize / (1024 * 1024));
                jTable1.getModel().setValueAt(mbsize, row, 2);
                 * 
                 */
                jTable1.getModel().setValueAt(FileUtils.byteCountToDisplaySize(g.gameSize), row, 2);
                Shared.lastCreatedGame = null;
                GamelistStorage.addGame(g);
                jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
                g.gameStatus = 0;
                SettingsManager.getStorage().storeGame(g);
                /*
                try {
                SettingsManager.storeCurrentSettings();
                } catch (Exception ex) {
                l.debug(ex.getMessage(), ex);
                }
                 * 
                 */
                l.trace("Done adding game");
                MainFrame.setReportingIdle();
                MainFrame.unlockInterface();
            }
        };
        worker.execute();
    } else {
        l.debug("Add game dialog - null game returned, nothing done");
        MainFrame.setReportingIdle();
        MainFrame.unlockInterface();
    }
    MainFrame.updateGameInterfaceFromStorage();
}