Example usage for java.util.zip CRC32 update

List of usage examples for java.util.zip CRC32 update

Introduction

In this page you can find the example usage for java.util.zip CRC32 update.

Prototype

@Override
public void update(ByteBuffer buffer) 

Source Link

Document

Updates the CRC-32 checksum with the bytes from the specified buffer.

Usage

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * Operation for fetching data of type FILE.
 * /*from   ww  w .j a  v a  2 s .  com*/
 * @param importSource
 * @param identifier
 * @param listOfFormats
 * @return byte[] of the fetched file, zip file if more than one record was
 *         fetched
 * @throws RuntimeException
 * @throws SourceNotAvailableException
 */
private byte[] fetchData(String identifier, Format[] formats)
        throws SourceNotAvailableException, RuntimeException, FormatNotAvailableException {
    byte[] in = null;
    FullTextVO fulltext = new FullTextVO();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    try {
        // Call fetch file for every given format
        for (int i = 0; i < formats.length; i++) {
            Format format = formats[i];
            fulltext = this.util.getFtObjectToFetch(this.currentSource, format.getName(), format.getType(),
                    format.getEncoding());
            // Replace regex with identifier
            String decoded = java.net.URLDecoder.decode(fulltext.getFtUrl().toString(),
                    this.currentSource.getEncoding());
            fulltext.setFtUrl(new URL(decoded));
            fulltext.setFtUrl(
                    new URL(fulltext.getFtUrl().toString().replaceAll(this.regex, identifier.trim())));
            this.logger.debug("Fetch file from URL: " + fulltext.getFtUrl());

            // escidoc file
            if (this.currentSource.getHarvestProtocol().equalsIgnoreCase("ejb")) {
                in = this.fetchEjbFile(fulltext, identifier);
            }
            // other file
            else {
                in = this.fetchFile(fulltext);
            }

            this.setFileProperties(fulltext);
            // If only one file => return it in fetched format
            if (formats.length == 1) {
                return in;
            }
            // If more than one file => add it to zip
            else {
                // If cone service is not available (we do not get a
                // fileEnding) we have
                // to make sure that the zip entries differ in name.
                String fileName = identifier;
                if (this.getFileEnding().equals("")) {
                    fileName = fileName + "_" + i;
                }
                ZipEntry ze = new ZipEntry(fileName + this.getFileEnding());
                ze.setSize(in.length);
                ze.setTime(this.currentDate());
                CRC32 crc321 = new CRC32();
                crc321.update(in);
                ze.setCrc(crc321.getValue());
                zos.putNextEntry(ze);
                zos.write(in);
                zos.flush();
                zos.closeEntry();
            }
        }
        this.setContentType("application/zip");
        this.setFileEnding(".zip");
        zos.close();

    } catch (SourceNotAvailableException e) {
        this.logger.error("Import Source " + this.currentSource + " not available.", e);
        throw new SourceNotAvailableException(e);
    } catch (FormatNotAvailableException e) {
        throw new FormatNotAvailableException(e.getMessage());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:org.exist.xquery.modules.compression.AbstractCompressFunction.java

/**
 * Adds a element to a archive//w  w w . j a v a 2s  . c o  m
 *
 * @param os
 *            The Output Stream to add the element to
 * @param file
 *            The file to add to the archive
 * @param useHierarchy
 *            Whether to use a folder hierarchy in the archive file that
 *            reflects the collection hierarchy
 */
private void compressFile(OutputStream os, File file, boolean useHierarchy, String stripOffset, String method,
        String name) throws IOException {

    if (file.isFile()) {

        // create an entry in the Tar for the document
        Object entry = null;
        byte[] value = new byte[0];
        CRC32 chksum = new CRC32();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (name != null) {
            entry = newEntry(name);
        } else if (useHierarchy) {
            entry = newEntry(removeLeadingOffset(file.getPath(), stripOffset));
        } else {
            entry = newEntry(file.getName());
        }

        InputStream is = new FileInputStream(file);
        byte[] data = new byte[16384];
        int len = 0;
        while ((len = is.read(data, 0, data.length)) > 0) {
            baos.write(data, 0, len);
        }
        is.close();
        value = baos.toByteArray();
        // close the entry
        if (entry instanceof ZipEntry && "store".equals(method)) {
            ((ZipEntry) entry).setMethod(ZipOutputStream.STORED);
            chksum.update(value);
            ((ZipEntry) entry).setCrc(chksum.getValue());
            ((ZipEntry) entry).setSize(value.length);
        }

        putEntry(os, entry);
        os.write(value);
        closeEntry(os);

    } else {

        for (String i : file.list()) {
            compressFile(os, new File(file, i), useHierarchy, stripOffset, method, null);
        }

    }

}

From source file:org.smartfrog.services.www.bulkio.client.SunJavaBulkIOClient.java

@Override
public long doDownload(long ioSize) throws IOException, InterruptedException {
    validateURL();/*from   w w  w .j av  a  2  s.  c  o  m*/
    URL target = createFullURL(ioSize, format);
    getLog().info("Downloading " + ioSize + " bytes from " + target);
    CRC32 checksum = new CRC32();
    HttpURLConnection connection = openConnection(target);
    connection.setRequestMethod(HttpAttributes.METHOD_GET);
    connection.setDoOutput(false);
    connection.connect();
    checkStatusCode(target, connection, HttpURLConnection.HTTP_OK);
    String contentLengthHeader = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);
    long contentLength = Long.parseLong(contentLengthHeader);
    if (contentLength != ioSize) {
        throw new IOException("Wrong content length returned from " + target + " - expected " + ioSize
                + " but got " + contentLength);
    }
    String formatHeader = connection.getHeaderField(HttpHeaders.CONTENT_TYPE);
    if (!format.equals(formatHeader)) {
        throw new IOException("Wrong content type returned from " + target + " - expected " + format
                + " but got " + formatHeader);
    }
    InputStream stream = connection.getInputStream();
    long bytes = 0;
    try {
        for (bytes = 0; bytes < ioSize; bytes++) {
            int octet = stream.read();
            checksum.update(octet);
            if (interrupted) {
                throw new InterruptedException(
                        "Interrupted after reading" + bytes + " bytes" + " from " + target);
            }
        }
    } finally {
        closeQuietly(stream);
    }
    long actualChecksum = checksum.getValue();
    getLog().info("Download finished after " + bytes + " bytes, checksum=" + actualChecksum);
    if (bytes != ioSize) {
        throw new IOException("Wrong content length downloaded from " + target + " - requested " + ioSize
                + " but got " + bytes);
    }
    if (expectedChecksumFromGet >= 0 && expectedChecksumFromGet != actualChecksum) {
        throw new IOException("Wrong checksum from download of " + ioSize + " bytes " + " from " + target
                + " expected " + expectedChecksumFromGet + " but got " + actualChecksum);
    }
    return bytes;
}

From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java

/**
 * Finishes the addition of entries to this archive, without closing it.
 * /*from w  w w  .j a  va 2s. co  m*/
 * @throws IOException if archive is already closed.
 */
public void finish() throws IOException {
    if (finished) {
        throw new IOException("This archive has already been finished");
    }
    finished = true;

    final long headerPosition = file.getFilePointer();

    final ByteArrayOutputStream headerBaos = new ByteArrayOutputStream();
    final DataOutputStream header = new DataOutputStream(headerBaos);

    writeHeader(header);
    header.flush();
    final byte[] headerBytes = headerBaos.toByteArray();
    file.write(headerBytes);

    final CRC32 crc32 = new CRC32();

    // signature header
    file.seek(0);
    file.write(SevenZFile.sevenZSignature);
    // version
    file.write(0);
    file.write(2);

    // start header
    final ByteArrayOutputStream startHeaderBaos = new ByteArrayOutputStream();
    final DataOutputStream startHeaderStream = new DataOutputStream(startHeaderBaos);
    startHeaderStream.writeLong(Long.reverseBytes(headerPosition - SevenZFile.SIGNATURE_HEADER_SIZE));
    startHeaderStream.writeLong(Long.reverseBytes(0xffffFFFFL & headerBytes.length));
    crc32.reset();
    crc32.update(headerBytes);
    startHeaderStream.writeInt(Integer.reverseBytes((int) crc32.getValue()));
    startHeaderStream.flush();
    final byte[] startHeaderBytes = startHeaderBaos.toByteArray();
    crc32.reset();
    crc32.update(startHeaderBytes);
    file.writeInt(Integer.reverseBytes((int) crc32.getValue()));
    file.write(startHeaderBytes);
}

From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java

@Override
public boolean checkLicenseKey()
        throws DataAccessException, ConnectionException, ParseException, IOException, ParseException {
    // nu cha load config, cn khi to ch  default
    if (mConfig == null)
        mConfig = new PosConfigDefault();
    ActiveKey activeKey = new PosActiveKey();
    if (mConfig.getValue("webpos/general/active_key") == null)
        return false;

    String baseUrl = getHostUrl(POSDataAccessSessionM1.REST_BASE_URL);
    String extensionName = POSDataAccessSessionM1.REST_EXTENSION_NAME;
    String licensekey = (String) mConfig.getValue("webpos/general/active_key");
    if (licensekey.length() < 68)
        return false;
    CRC32 crc = new CRC32();
    String strExtensionName = licensekey.substring(0, 10) + extensionName;
    crc.update(strExtensionName.getBytes());
    int strDataCrc32 = (int) crc.getValue();
    int crc32Pos = (strDataCrc32 & 0x7FFFFFFF % 51) + 10;
    int md5Length = 32;
    String md5String = licensekey.substring(crc32Pos, (crc32Pos + md5Length));
    int md5StringLength = md5String.length();
    String key = licensekey.substring(0, crc32Pos)
            + licensekey.substring((crc32Pos + md5StringLength + 3), licensekey.length());
    try {//from  ww w  .jav  a2  s  .  com
        while ((key.length() % 4) != 0) {
            key += "=";
        }
        String licenseString = decryptRSAToString(key, POSDataAccessSessionM1.REST_PUBLIC_KEY);
        if (StringUtil.isNullOrEmpty(licenseString))
            return false;

        String strlicenseString = licenseString.substring(0, 3);
        String strlicensekey = licensekey.substring((crc32Pos + md5StringLength),
                (crc32Pos + md5StringLength + 3));
        if (!strlicenseString.equals(strlicensekey))
            return false;

        String type = licenseString.substring(0, 1);
        String strexpiredTime = licenseString.substring(1, 3);
        int expiredTime = Integer.parseInt(String.valueOf(strexpiredTime), 16);
        long extensionHash = -1;
        try {
            extensionHash = Long.parseLong(licenseString.substring(3, 13));
        } catch (Exception e) {
        }
        CRC32 crcExtensionName = new CRC32();
        crcExtensionName.update(extensionName.getBytes());
        long crc32ExtensionName = crcExtensionName.getValue();
        if (extensionHash != crc32ExtensionName)
            return false;

        String licenseDomain = licenseString.substring(17, licenseString.length()).replaceAll(" ", "");
        String checkCRc32 = licensekey.substring(0, crc32Pos)
                + licensekey.substring((crc32Pos + md5StringLength),
                        (crc32Pos + md5StringLength) + (licensekey.length() - crc32Pos - md5StringLength))
                + extensionName + licenseDomain;
        //            CRC32 crcCheck = new CRC32();
        //            crcCheck.update(checkCRc32.getBytes());
        //            long lcrc32String = -1;
        //            try {
        //                lcrc32String = Long.parseLong(crc32String);
        //            } catch (Exception e) {
        //            }
        String md5Check = EncryptUntil.HashMD5(checkCRc32);
        if (!md5Check.equals(md5String))
            return false;

        String strDate = licenseString.substring(11, 15);
        int resultDate = Integer.parseInt(String.valueOf(strDate), 16);
        String DATE_FORMAT = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        String createdDate = sdf.format(new Date(resultDate * 24 * 3600 * 1000L));
        if (!checkSameDomain(baseUrl, licenseDomain))
            return false;

        activeKey.setType(type);
        activeKey.setExpiredTime(expiredTime);
        activeKey.setCreatedDate(createdDate);
        activeKey.setLicenseDomain(licenseDomain);
        ConfigUtil.setActiveKey(activeKey);
        ConfigUtil.setIsDevLicense(type.equals("D") ? true : false);
        return true;
    } catch (Exception e) {
        String licenseDomain = "";
        if (baseUrl.contains("https://")) {
            baseUrl = baseUrl.replace("https://", "");
        } else if (baseUrl.contains("http://")) {
            baseUrl = baseUrl.replace("http://", "");
        }
        if (baseUrl.length() > 36) {
            licenseDomain = baseUrl.substring(0, 36);
        } else {
            licenseDomain = baseUrl;
        }
        String checkCRc32 = licensekey.substring(0, crc32Pos)
                + licensekey.substring((crc32Pos + md5StringLength),
                        (crc32Pos + md5StringLength) + (licensekey.length() - crc32Pos - md5StringLength))
                + extensionName + licenseDomain;
        //            CRC32 crcCheck = new CRC32();
        //            crcCheck.update(checkCRc32.getBytes());
        //            long lcrc32String = -1;
        //            try {
        //                lcrc32String = Long.parseLong(crc32String);
        //            } catch (Exception ex) {
        //            }
        String md5Check = EncryptUntil.HashMD5(checkCRc32);
        if (!md5Check.equals(md5String))
            return false;
        String type = licensekey.substring(crc32Pos + md5StringLength, crc32Pos + md5StringLength + 1);
        String strexpiredTime = licensekey.substring(crc32Pos + md5StringLength + 1,
                crc32Pos + md5StringLength + 1 + 2);
        int expiredTime = Integer.parseInt(String.valueOf(strexpiredTime), 16);
        if (!checkSameDomain(baseUrl, licenseDomain))
            return false;
        activeKey.setType(type);
        activeKey.setExpiredTime(expiredTime);
        activeKey.setLicenseDomain(licenseDomain);
        ConfigUtil.setActiveKey(activeKey);
        ConfigUtil.setIsDevLicense(type.equals("D") ? true : false);
        return true;
    }
}

From source file:com.magestore.app.pos.api.m2.config.POSConfigDataAccess.java

@Override
public boolean checkLicenseKey()
        throws DataAccessException, ConnectionException, ParseException, IOException, ParseException {
    // nu cha load config, cn khi to ch  default
    if (mConfig == null)
        mConfig = new PosConfigDefault();
    ActiveKey activeKey = new PosActiveKey();
    if (mConfig.getValue("webpos/general/active_key") == null)
        return false;

    String baseUrl = getHostUrl(POSDataAccessSession.REST_BASE_URL);
    String extensionName = POSDataAccessSession.REST_EXTENSION_NAME;
    String licensekey = (String) mConfig.getValue("webpos/general/active_key");
    if (licensekey.length() < 68)
        return false;
    CRC32 crc = new CRC32();
    String strExtensionName = licensekey.substring(0, 10) + extensionName;
    crc.update(strExtensionName.getBytes());
    int strDataCrc32 = (int) crc.getValue();
    int crc32Pos = (strDataCrc32 & 0x7FFFFFFF % 51) + 10;
    int md5Length = 32;
    String md5String = licensekey.substring(crc32Pos, (crc32Pos + md5Length));
    int md5StringLength = md5String.length();
    String key = licensekey.substring(0, crc32Pos)
            + licensekey.substring((crc32Pos + md5StringLength + 3), licensekey.length());
    try {//  www.j  av  a  2 s.  c  o m
        while ((key.length() % 4) != 0) {
            key += "=";
        }
        String licenseString = decryptRSAToString(key, POSDataAccessSession.REST_PUBLIC_KEY);
        if (StringUtil.isNullOrEmpty(licenseString))
            return false;

        String strlicenseString = licenseString.substring(0, 3);
        String strlicensekey = licensekey.substring((crc32Pos + md5StringLength),
                (crc32Pos + md5StringLength + 3));
        if (!strlicenseString.equals(strlicensekey))
            return false;

        String type = licenseString.substring(0, 1);
        String strexpiredTime = licenseString.substring(1, 3);
        int expiredTime = Integer.parseInt(String.valueOf(strexpiredTime), 16);
        long extensionHash = -1;
        try {
            extensionHash = Long.parseLong(licenseString.substring(3, 13));
        } catch (Exception e) {
        }
        CRC32 crcExtensionName = new CRC32();
        crcExtensionName.update(extensionName.getBytes());
        long crc32ExtensionName = crcExtensionName.getValue();
        if (extensionHash != crc32ExtensionName)
            return false;

        String licenseDomain = licenseString.substring(17, licenseString.length()).replaceAll(" ", "");
        String checkCRc32 = licensekey.substring(0, crc32Pos)
                + licensekey.substring((crc32Pos + md5StringLength),
                        (crc32Pos + md5StringLength) + (licensekey.length() - crc32Pos - md5StringLength))
                + extensionName + licenseDomain;
        //            CRC32 crcCheck = new CRC32();
        //            crcCheck.update(checkCRc32.getBytes());
        //            long lcrc32String = -1;
        //            try {
        //                lcrc32String = Long.parseLong(crc32String);
        //            } catch (Exception e) {
        //            }
        String md5Check = EncryptUntil.HashMD5(checkCRc32);
        if (!md5Check.equals(md5String))
            return false;

        String strDate = licenseString.substring(11, 15);
        int resultDate = Integer.parseInt(String.valueOf(strDate), 16);
        String DATE_FORMAT = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        String createdDate = sdf.format(new Date(resultDate * 24 * 3600 * 1000L));
        if (!checkSameDomain(baseUrl, licenseDomain))
            return false;

        activeKey.setType(type);
        activeKey.setExpiredTime(expiredTime);
        activeKey.setCreatedDate(createdDate);
        activeKey.setLicenseDomain(licenseDomain);
        ConfigUtil.setActiveKey(activeKey);
        ConfigUtil.setIsDevLicense(type.equals("D") ? true : false);
        return true;
    } catch (Exception e) {
        String licenseDomain = "";
        if (baseUrl.contains("https://")) {
            baseUrl = baseUrl.replace("https://", "");
        } else if (baseUrl.contains("http://")) {
            baseUrl = baseUrl.replace("http://", "");
        }
        if (baseUrl.length() > 36) {
            licenseDomain = baseUrl.substring(0, 36);
        } else {
            licenseDomain = baseUrl;
        }
        String checkCRc32 = licensekey.substring(0, crc32Pos)
                + licensekey.substring((crc32Pos + md5StringLength),
                        (crc32Pos + md5StringLength) + (licensekey.length() - crc32Pos - md5StringLength))
                + extensionName + licenseDomain;
        //            CRC32 crcCheck = new CRC32();
        //            crcCheck.update(checkCRc32.getBytes());
        //            long lcrc32String = -1;
        //            try {
        //                lcrc32String = Long.parseLong(crc32String);
        //            } catch (Exception ex) {
        //            }
        String md5Check = EncryptUntil.HashMD5(checkCRc32);
        if (!md5Check.equals(md5String))
            return false;
        String type = licensekey.substring(crc32Pos + md5StringLength, crc32Pos + md5StringLength + 1);
        String strexpiredTime = licensekey.substring(crc32Pos + md5StringLength + 1,
                crc32Pos + md5StringLength + 1 + 2);
        int expiredTime = Integer.parseInt(String.valueOf(strexpiredTime), 16);
        if (!checkSameDomain(baseUrl, licenseDomain))
            return false;
        activeKey.setType(type);
        activeKey.setExpiredTime(expiredTime);
        activeKey.setLicenseDomain(licenseDomain);
        ConfigUtil.setActiveKey(activeKey);
        ConfigUtil.setIsDevLicense(type.equals("D") ? true : false);
        return true;
    }
}

From source file:com.nridge.core.base.field.data.DataBag.java

/**
 * Convenience method will calculate a unique type id property for
 * the bag based on each field name using a CRC32 algorithm.
 *///from  w  w w  . jav a 2 s. c  o  m
public void setTypeIdByNames() {
    CRC32 crc32 = new CRC32();
    crc32.reset();
    if (StringUtils.isNotEmpty(mName))
        crc32.update(mName.getBytes());
    else {
        for (DataField dataField : mFields)
            crc32.update(dataField.getName().getBytes());
    }
    setTypeId(crc32.getValue());
}

From source file:org.openbravo.erpCommon.obps.ActivationKey.java

public String getOpsLogId() {
    CRC32 crc = new CRC32();
    crc.update(getPublicKey().getBytes());
    return Long.toHexString(crc.getValue());
}

From source file:org.exist.xquery.modules.compression.AbstractCompressFunction.java

/**
* Adds a element to a archive/*from w w w  . j a  v  a2 s .  c om*/
* 
* @param os
*            The Output Stream to add the element to
* @param element
*            The element to add to the archive
* @param useHierarchy
*            Whether to use a folder hierarchy in the archive file that
*            reflects the collection hierarchy
*/
private void compressElement(OutputStream os, Element element, boolean useHierarchy, String stripOffset)
        throws XPathException {

    if (!(element.getNodeName().equals("entry") || element.getNamespaceURI().length() > 0))
        throw new XPathException(this, "Item must be type of xs:anyURI or element entry.");

    if (element.getChildNodes().getLength() > 1)
        throw new XPathException(this, "Entry content is not valid XML fragment.");

    String name = element.getAttribute("name");
    //            if(name == null)
    //                throw new XPathException(this, "Entry must have name attribute.");

    String type = element.getAttribute("type");

    if ("uri".equals(type)) {
        compressFromUri(os, URI.create(element.getFirstChild().getNodeValue()), useHierarchy, stripOffset,
                element.getAttribute("method"), name);
        return;
    }

    if (useHierarchy) {
        name = removeLeadingOffset(name, stripOffset);
    } else {
        name = name.substring(name.lastIndexOf("/") + 1);
    }

    if ("collection".equals(type))
        name += "/";

    Object entry = null;

    try {

        entry = newEntry(name);

        if (!"collection".equals(type)) {
            byte[] value;
            CRC32 chksum = new CRC32();
            Node content = element.getFirstChild();

            if (content == null) {
                value = new byte[0];
            } else {
                if (content.getNodeType() == Node.TEXT_NODE) {
                    String text = content.getNodeValue();
                    Base64Decoder dec = new Base64Decoder();
                    if ("binary".equals(type)) {
                        //base64 binary
                        dec.translate(text);
                        value = dec.getByteArray();
                    } else {
                        //text
                        value = text.getBytes();
                    }
                } else {
                    //xml
                    Serializer serializer = context.getBroker().getSerializer();
                    serializer.setUser(context.getUser());
                    serializer.setProperty("omit-xml-declaration", "no");
                    getDynamicSerializerOptions(serializer);
                    value = serializer.serialize((NodeValue) content).getBytes();
                }
            }

            if (entry instanceof ZipEntry && "store".equals(element.getAttribute("method"))) {
                ((ZipEntry) entry).setMethod(ZipOutputStream.STORED);
                chksum.update(value);
                ((ZipEntry) entry).setCrc(chksum.getValue());
                ((ZipEntry) entry).setSize(value.length);
            }
            putEntry(os, entry);

            os.write(value);
        }
    } catch (IOException ioe) {
        throw new XPathException(this, ioe.getMessage(), ioe);
    } catch (SAXException saxe) {
        throw new XPathException(this, saxe.getMessage(), saxe);
    } finally {
        if (entry != null)
            try {
                closeEntry(os);
            } catch (IOException ioe) {
                throw new XPathException(this, ioe.getMessage(), ioe);
            }
    }
}

From source file:com.redskyit.scriptDriver.RunTests.java

private boolean compareStrings(String s1, String s2, boolean checksum) {
    if (checksum) {
        CRC32 crc = new CRC32();
        crc.update(s1.getBytes());
        return ("crc32:" + crc.getValue()).equals(s2);
    }//from   w  ww  .  j  a  v  a2 s. co m
    return s1.equals(s2);
}