Example usage for java.util.zip CRC32 getValue

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

Introduction

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

Prototype

@Override
public long getValue() 

Source Link

Document

Returns CRC-32 value.

Usage

From source file:com.indeed.lsmtree.recordlog.BasicRecordFile.java

private Option<E> readAndCheck(long address, MutableLong nextElementStart) throws IOException {
    if (address + 4 > memory.length()) {
        throw new ConsistencyException("not enough bytes in file");
    }/*from   www.j  a v  a  2s.c o m*/
    final int length = memory.getInt(address);
    if (length < 0) {
        return Option.none();
    }
    if (address + 8 > memory.length()) {
        throw new ConsistencyException("not enough bytes in file");
    }
    if (address + 8 + length > memory.length()) {
        throw new ConsistencyException("not enough bytes in file");
    }
    final int checksum = memory.getInt(address + 4);
    MemoryDataInput in = new MemoryDataInput(memory);
    in.seek(address + 8);
    CRC32 crc32 = new CRC32();
    crc32.update(CRC_SEED);
    byte[] bytes = new byte[length];
    in.readFully(bytes);
    crc32.update(bytes);
    if ((int) crc32.getValue() != checksum) {
        throw new ConsistencyException("checksum for record does not match: expected " + checksum + " actual "
                + (int) crc32.getValue());
    }
    E ret = serializer.read(ByteStreams.newDataInput(bytes));
    if (nextElementStart != null)
        nextElementStart.setValue(address + 8 + length);
    return Option.some(ret);
}

From source file:com.bitbreeds.webrtc.stun.StunMessage.java

/**
 * @return array of bytes representing message
 *///from  w  ww.  j  av a 2  s. c  o m
public byte[] toBytes() {
    final List<byte[]> bt = new ArrayList<>();

    attributeSet.values().stream().forEach(i -> bt.add(i.toBytes()));

    StunHeader hd1 = withIntegrity ? header.updateMessageLength(header.getMessageLength() + 24) : header;
    if (withIntegrity) {
        byte[] macData = SignalUtil.joinBytesArrays(hd1.toBytes(), SignalUtil.joinBytesArrays(bt));

        byte[] mac = SignalUtil.hmacSha1(macData, password.getBytes());

        StunAttribute integrity = new StunAttribute(StunAttributeTypeEnum.MESSAGE_INTEGRITY, mac);
        bt.add(integrity.toBytes());
    }

    StunHeader hd2 = withFingerprint ? hd1.updateMessageLength(hd1.getMessageLength() + 8) : hd1;
    if (withFingerprint) {
        //Generate fingerprint
        final CRC32 crc = new CRC32();
        crc.update(hd2.toBytes());
        bt.forEach(crc::update);
        byte[] xorCRC32 = SignalUtil.xor(SignalUtil.fourBytesFromInt((int) crc.getValue()),
                new byte[] { 0x53, 0x54, 0x55, 0x4e });

        StunAttribute finger = new StunAttribute(StunAttributeTypeEnum.FINGERPRINT, xorCRC32);
        bt.add(finger.toBytes());
    }

    return SignalUtil.joinBytesArrays(hd2.toBytes(), SignalUtil.joinBytesArrays(bt));
}

From source file:org.apache.isis.objectstore.nosql.db.file.FileServerDb.java

private String checkData(final String data) {
    final String objectData = data.substring(8);

    final CRC32 inputChecksum = new CRC32();
    inputChecksum.update(objectData.getBytes());
    final long actualChecksum = inputChecksum.getValue();

    final String encodedChecksum = data.substring(0, 8);
    final long expectedChecksum = Long.valueOf(encodedChecksum, 16);

    if (actualChecksum != expectedChecksum) {
        throw new NoSqlStoreException("Data integrity error; checksums different");
    }/*from   w w w  . ja  v a  2 s. com*/

    return objectData;
}

From source file:it.jnrpe.net.JNRPEProtocolPacket.java

/**
 * Updates the CRC value.//from  w  ww  .  j  a  va  2 s .co  m
 */
void updateCRC() {
    setCRC(0);
    CRC32 crcAlg = new CRC32();
    crcAlg.update(toByteArray());

    setCRC((int) crcAlg.getValue());
}

From source file:com.haulmont.cuba.core.app.FoldersServiceBean.java

protected ArchiveEntry newStoredEntry(String name, byte[] data) {
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(name);
    zipEntry.setSize(data.length);//from ww  w.j ava 2  s. com
    zipEntry.setCompressedSize(zipEntry.getSize());
    CRC32 crc32 = new CRC32();
    crc32.update(data);
    zipEntry.setCrc(crc32.getValue());
    return zipEntry;
}

From source file:com.webpagebytes.cms.controllers.PageController.java

public void update(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    try {/*  ww  w.  j a  v a2  s. co m*/
        Long key = Long.valueOf((String) request.getAttribute("key"));
        String jsonRequest = httpServletToolbox.getBodyText(request);
        WPBPage webPage = (WPBPage) jsonObjectConverter.objectFromJSONString(jsonRequest, WPBPage.class);
        webPage.setPrivkey(key);
        Map<String, String> errors = pageValidator.validateUpdate(webPage);

        if (errors.size() > 0) {
            httpServletToolbox.writeBodyResponseAsJson(response, "{}", errors);
            return;
        }
        CRC32 crc = new CRC32();
        crc.update(webPage.getHtmlSource().getBytes());
        webPage.setHash(crc.getValue());

        webPage.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime());
        WPBPage newWebPage = adminStorage.update(webPage);

        WPBResource resource = new WPBResource(newWebPage.getExternalKey(), newWebPage.getName(),
                WPBResource.PAGE_TYPE);
        try {
            adminStorage.update(resource);
        } catch (Exception e) {
            // do not propate further
        }
        org.json.JSONObject returnJson = new org.json.JSONObject();
        returnJson.put(DATA, jsonObjectConverter.JSONFromObject(newWebPage));
        httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null);

    } catch (Exception e) {
        Map<String, String> errors = new HashMap<String, String>();
        errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD);
        httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null),
                errors);
    }
}

From source file:it.jnrpe.net.JNRPEProtocolPacket.java

/**
 * Validates the packet CRC.//ww w  .j a  va  2  s  . c o m
 * 
 * @throws BadCRCException
 *             If the CRC can't be validated 
 */
public void validate() throws BadCRCException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        dout.writeShort(packetVersion);
        dout.writeShort(packetTypeCode);
        dout.writeInt(0); // NO CRC
        dout.writeShort(resultCode);
        dout.write(byteBufferAry);
        dout.write(dummyBytesAry);

        dout.close();

        byte[] vBytes = bout.toByteArray();

        CRC32 crcAlg = new CRC32();
        crcAlg.update(vBytes);

        if (!(((int) crcAlg.getValue()) == crcValue)) {
            throw new BadCRCException("Bad CRC");
        }
    } catch (IOException e) {
        // Never happens...
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:org.apache.hadoop.raid.TestRaidNode.java

static long createOldFile(FileSystem fileSys, Path name, int repl, int numBlocks, long blocksize)
        throws IOException {
    CRC32 crc = new CRC32();
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096),
            (short) repl, blocksize);
    // fill random data into file
    byte[] b = new byte[(int) blocksize];
    for (int i = 0; i < numBlocks; i++) {
        if (i == (numBlocks - 1)) {
            b = new byte[(int) blocksize / 2];
        }/*from ww w  .j a  va2  s . c om*/
        rand.nextBytes(b);
        stm.write(b);
        crc.update(b);
    }

    stm.close();
    return crc.getValue();
}

From source file:org.apache.hadoop.hdfs.TestRaidDfs.java

public static long createTestFile(FileSystem fileSys, Path name, int repl, int numBlocks, long blocksize)
        throws IOException {
    CRC32 crc = new CRC32();
    Random rand = new Random();
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096),
            (short) repl, blocksize);
    // fill random data into file
    final byte[] b = new byte[(int) blocksize];
    for (int i = 0; i < numBlocks; i++) {
        rand.nextBytes(b);/*from w ww  . j a  va2s.c o m*/
        stm.write(b);
        crc.update(b);
    }
    stm.close();
    return crc.getValue();
}

From source file:eu.semlibproject.annotationserver.managers.UtilsManager.java

/**
 * Compute the CRC32 checksum of a String. This can be useful to
 * short an URL./* w  w  w.  ja v  a  2  s .  c  o  m*/
 * 
 * @param text  the text from which the checksum will be computed
 * @return      the CRC32 checksum
 */
public String CRC32(String text) {
    CRC32 checksumer = new CRC32();
    checksumer.update(text.getBytes());
    String finalhash = Long.toHexString(checksumer.getValue());
    // correctly format the finalHash (e.g. number starting with 00 that was stripped)
    return StringUtils.leftPad(finalhash, 8, "0");
}