Example usage for java.lang Byte SIZE

List of usage examples for java.lang Byte SIZE

Introduction

In this page you can find the example usage for java.lang Byte SIZE.

Prototype

int SIZE

To view the source code for java.lang Byte SIZE.

Click Source Link

Document

The number of bits used to represent a byte value in two's complement binary form.

Usage

From source file:org.springframework.jdbc.repo.impl.jdbc.RawPropertiesRepoImplTest.java

@Test
public void testFindEntitiesByPropertyValue() {
    final String BASE_ID = "testFindEntitiesByPropertyValue";
    Map<String, Serializable> props = createEntityProperties(BASE_ID);
    List<String> expected = new ArrayList<>();
    for (int index = 0; index < Byte.SIZE; index++) {
        String id = BASE_ID + index;
        repo.setProperties(id, props);/*from   www. j a v a2s  .c  o  m*/
        expected.add(id);
    }

    for (Map.Entry<String, Serializable> pe : props.entrySet()) {
        String propName = pe.getKey();
        Serializable propValue = pe.getValue();
        List<String> actual = repo.findEntities(propName, propValue);
        if (!CollectionUtils.isEqualCollection(expected, actual)) {
            fail("Mismatched results for " + propName + "=" + propValue + ": expected=" + expected + ", actual="
                    + actual);
        }

        // change the type so we know it won't matcj
        if (propValue instanceof String) {
            propValue = Integer.valueOf(propValue.hashCode());
        } else {
            propValue = propValue.toString();
        }

        actual = repo.findEntities(propName, propValue);
        if (ExtendedCollectionUtils.size(actual) > 0) {
            fail("Unexpected results for " + propName + "=" + propValue + ": " + actual);
        }
    }
}

From source file:de.hpi.fgis.hdrs.Triple.java

/**
 * Estimate total IN MEMORY size of this triple.  Including headers and data.
 * This estimate is for 32bit.//  w w w.jav a  2 s. c  o  m
 * @return  Estimated size of this triple in bytes.
 */
public int estimateSize() {
    return (9 * Integer.SIZE) / Byte.SIZE + bufferSize();
}

From source file:com.alfaariss.oa.util.saml2.binding.artifact.ImplementedHTTPArtifactDecoder.java

/**
 * @see org.opensaml.saml2.binding.decoding.HTTPArtifactDecoder#processArtifact(org.opensaml.common.binding.SAMLMessageContext)
 *///from  w  w  w  .  j  a va  2 s.c o m
@SuppressWarnings("unchecked")
protected void processArtifact(SAMLMessageContext samlMsgCtx) throws MessageDecodingException {
    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
    String encodedArtifact = DatatypeHelper.safeTrimOrNullString(inTransport.getParameterValue("SAMLart"));
    if (encodedArtifact == null) {
        _logger.error("URL SAMLart parameter was missing or did not contain a value");
        throw new MessageDecodingException("URL TARGET parameter was missing or did not contain a value");
    }

    ArtifactBuilder artifactBuilder = (ArtifactBuilder) _builderFactory
            .getBuilder(Artifact.DEFAULT_ELEMENT_NAME);
    Artifact artifact = artifactBuilder.buildObject();
    artifact.setArtifact(encodedArtifact);

    ArtifactResolveBuilder artifactResolveBuilder = (ArtifactResolveBuilder) _builderFactory
            .getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME);
    ArtifactResolve artifactResolve = artifactResolveBuilder.buildObject();

    SecureRandomIdentifierGenerator idgen = null;
    try {
        idgen = new SecureRandomIdentifierGenerator();
    } catch (NoSuchAlgorithmException e) {
        String msg = "Could not generate ID for artifact resolve request";
        _logger.debug(msg);
        throw new MessageDecodingException(msg, e);
    }

    String id = idgen.generateIdentifier();

    artifactResolve.setID(id);
    artifactResolve.setVersion(SAMLVersion.VERSION_20);
    artifactResolve.setIssueInstant(new DateTime());
    artifactResolve.setArtifact(artifact);

    IssuerBuilder issuerBuilder = (IssuerBuilder) _builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(samlMsgCtx.getOutboundMessageIssuer());

    artifactResolve.setIssuer(issuer);

    MetadataProvider mp = samlMsgCtx.getMetadataProvider();
    if (mp == null) {
        _logger.debug("No MetadataProvider available in message context");
        throw new MessageDecodingException("No MetadataProvider available in message context");
    }

    String entID = samlMsgCtx.getInboundMessageIssuer();
    String endpoint = null;

    try {
        SSODescriptor rd = null;
        if (_sSSODescriptor != null) {
            if ("sp".equalsIgnoreCase(_sSSODescriptor)) {
                rd = (SPSSODescriptor) mp.getRole(entID, SPSSODescriptor.DEFAULT_ELEMENT_NAME,
                        SAMLConstants.SAML20P_NS);
            } else if ("idp".equalsIgnoreCase(_sSSODescriptor)) {
                rd = (IDPSSODescriptor) mp.getRole(entID, IDPSSODescriptor.DEFAULT_ELEMENT_NAME,
                        SAMLConstants.SAML20P_NS);
            } else {
                StringBuffer sbDebug = new StringBuffer("Unknown SSODescriptor configured '");
                sbDebug.append(_sSSODescriptor);
                sbDebug.append("'; using IDPSSODescriptor");
                _logger.debug(sbDebug.toString());
            }
        }

        if (rd == null) {//default use IDP role
            rd = (IDPSSODescriptor) mp.getRole(entID, IDPSSODescriptor.DEFAULT_ELEMENT_NAME,
                    SAMLConstants.SAML20P_NS);
        }

        if (rd != null) {
            SAML2ArtifactType0004 b = null;
            SAML2ArtifactType0004Builder bf = new SAML2ArtifactType0004Builder();
            b = bf.buildArtifact(Base64.decode(encodedArtifact));

            String defaultEndpoint = null;
            String indexedEndpoint = null;
            String firstEndpoint = null;

            for (ArtifactResolutionService ars : rd.getArtifactResolutionServices()) {
                if (firstEndpoint == null)
                    firstEndpoint = ars.getLocation();
                if (ars.isDefault())
                    defaultEndpoint = ars.getLocation();

                int i = 0;
                byte[] ba = b.getEndpointIndex();

                for (int ia = ba.length - 1; ia >= 0; ia--) {
                    i = i + (ba[ia] * Byte.SIZE);
                }

                if (ars.getIndex() == i) {
                    indexedEndpoint = ars.getLocation();
                }
            }

            //choose right endpoint:
            if (indexedEndpoint != null)
                endpoint = indexedEndpoint;
            else if (defaultEndpoint != null)
                endpoint = defaultEndpoint;
            else
                endpoint = firstEndpoint;
        }
    } catch (MetadataProviderException e1) {
        String msg = "Exception while fetching metadata for requestor while decoding artifact";
        _logger.debug(msg);
        throw new MessageDecodingException(msg, e1);
    }

    if (endpoint == null) {
        String msg = "Could not fetch endpoint for requestor while decoding artifact";
        _logger.debug(msg);
        throw new MessageDecodingException(msg);
    }

    BodyBuilder bodyBuilder = (BodyBuilder) _builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
    Body body = bodyBuilder.buildObject();
    body.getUnknownXMLObjects().add(artifactResolve);

    EnvelopeBuilder envelopeBuilder = (EnvelopeBuilder) _builderFactory
            .getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    Envelope env = envelopeBuilder.buildObject();
    env.setBody(body);

    BasicSOAPMessageContext soapContext = new BasicSOAPMessageContext();
    soapContext.setOutboundMessage(env);

    HttpClientBuilder clientBuilder = new HttpClientBuilder();
    clientBuilder.setConnectionTimeout(5000);

    HttpSOAPClient soapClient = new HttpSOAPClient(clientBuilder.buildClient(), super.getParserPool());

    if (_logger.isDebugEnabled())
        logXML(env);

    try {
        soapClient.send(endpoint, soapContext);
    } catch (Exception e) {
        String msg = "Could not resolve artifact";
        _logger.debug(msg, e);
        throw new MessageDecodingException(msg, e);
    }

    Envelope envelope = (Envelope) soapContext.getInboundMessage();

    if (_logger.isDebugEnabled())
        logXML(envelope);

    XMLObject samlResponseMessage = null;
    XMLObject responseMessage = soapContext.getInboundMessage();
    if (responseMessage != null && responseMessage instanceof Envelope) {
        Envelope responseEnvelope = (Envelope) responseMessage;
        Body responseBody = responseEnvelope.getBody();
        if (responseBody != null) {
            samlResponseMessage = responseBody.getUnknownXMLObjects().get(0);
        } else {
            _logger.debug("No body in response message");
        }
    } else {
        _logger.debug("No envelope in response message");
    }

    if (samlResponseMessage != null && samlResponseMessage instanceof ArtifactResponse) {
        ArtifactResponse artResp = (ArtifactResponse) samlResponseMessage;
        SAMLObject message = artResp.getMessage();
        if (message != null)
            samlMsgCtx.setInboundSAMLMessage(message);
        else
            _logger.debug("No message found in artifact: " + artResp);
    } else {
        _logger.debug("Response doesn't contain an ArtifactResponse object");
    }
}

From source file:org.lsc.utils.security.SymmetricEncryption.java

/**
 * Initialize encryption object from the configuration file.
 * @return boolean (always true if no exception)
 * @throws GeneralSecurityException //  www  . j a  v  a 2  s .co  m
 */
public boolean initialize() throws GeneralSecurityException {
    InputStream input = null;
    boolean fail = false;
    try {
        input = new FileInputStream(new File(this.keyPath));
        byte[] data = new byte[strength / Byte.SIZE];
        input.read(data);

        Key key = new SecretKeySpec(data, this.algorithm);
        this.cipherEncrypt = Cipher.getInstance(this.algorithm);
        this.cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);
        this.cipherDecrypt = Cipher.getInstance(this.algorithm);
        this.cipherDecrypt.init(Cipher.DECRYPT_MODE, key);

    } catch (IOException e) {
        fail = true;
    } finally {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException e) {
        }
    }

    if (fail) {
        LOGGER.error("Error reading the key for SymmetricEncryption! ({})", this.keyPath);
        return false;
    }

    return true;
}

From source file:org.skife.muckery.mappy.ByteUtils.java

public static long readVarNumber(DataInputStream input) throws IOException {
    int b = 0xFF & input.readByte();
    if ((b & MASK_10000000) == 0) {
        // one byte value, mask off the size bit and return
        return MASK_01111111 & b;
    } else if ((b & MASK_11000000) == MASK_10000000) {
        // two byte value, mask off first two bits
        long val = (b & MASK_00111111) << Byte.SIZE;
        val |= 0xFF & input.readByte();
        return val;
    } else if ((b & MASK_11100000) == MASK_11000000) {
        // four byte value, mask off three bits
        long val = (b & MASK_00011111);
        for (int i = 0; i < 3; i++) {
            val <<= Byte.SIZE;
            val |= 0xFF & input.readByte();
        }/*  w  ww  . j av  a2s .  c  o m*/
        return val;
    } else if ((b & MASK_11100000) == MASK_11100000) {
        // eight byte value, mask off three bits
        long val = (b & MASK_00011111);
        for (int i = 0; i < 7; i++) {
            val <<= Byte.SIZE;
            val |= 0xFF & input.readByte();
        }
        return val;
    } else {
        throw new IllegalArgumentException("Unknown prefix!");
    }
}

From source file:org.springframework.jdbc.repo.impl.jdbc.RawPropertiesRepoImplTest.java

@Test
public void testListMatchingIdentifiers() {
    final String COMMON_PART = "testListMatchingIdentifiers";
    // NOTE: we chose a separator that has SQL meaning on purpose
    final String COMMON_PREFIX = getClass().getSimpleName() + "#" + COMMON_PART + "%";
    Map<String, Serializable> props = createEntityProperties(COMMON_PART);
    List<String> expected = new ArrayList<String>();
    for (int index = 0; index < Byte.SIZE; index++) {
        String id = COMMON_PREFIX + index;
        repo.setProperties(id, props);// w w  w  .j a  v  a 2 s  . c om
        expected.add(id);
    }

    // create some extra values
    for (int index = 0; index < Byte.SIZE; index++) {
        repo.setProperties(String.valueOf(Math.random()), props);
    }

    List<String> actual = repo.listMatchingIdentifiers("*" + COMMON_PART + "*");
    if (!CollectionUtils.isEqualCollection(expected, actual)) {
        fail("Mismatched common part wildcard results: expected=" + expected + ", actual=" + actual);
    }

    actual = repo.listMatchingIdentifiers(COMMON_PREFIX + "*");
    if (!CollectionUtils.isEqualCollection(expected, actual)) {
        fail("Mismatched common prefix wildcard results: expected=" + expected + ", actual=" + actual);
    }

    for (String id : expected) {
        actual = repo.listMatchingIdentifiers(id);
        assertEquals(id + ": Mismatched results count", 1, ExtendedCollectionUtils.size(actual));
        assertEquals("Mismatched matched identifiers", id, actual.get(0));
    }
}

From source file:org.kiji.schema.FormattedEntityId.java

/**
 * Create an hbase row key, which is a byte array from the given formatted kijiRowKey.
 * This method requires that the kijiRowKey argument is the correct length for the specified
 * format.// ww w .j  a va  2 s . co m
 * The following encoding will be used to ensure correct ordering:
 * Strings are UTF-8 encoded and terminated by a null byte. Strings cannot contain "\u0000".
 * Integers are exactly 4 bytes long.
 * Longs are exactly 8 bytes long.
 * Both integers and longs have the sign bit flipped so that their values are wrapped around to
 * create the correct lexicographic ordering. (i.e. after converting to byte array,
 * MIN_INT < 0 < MAX_INT).
 * Hashed components are exactly hash_size bytes long and are the first component of
 * the hbase key.
 * Except for the first, all components of a kijiRowKey can be null. However, to maintain
 * ordering, all components to the right of a null component must also be null. Nullable index
 * in the row key format specifies which component (and hence following components) are nullable.
 * By default, the hash only uses the first component, but this can be changed using the Range
 * Scan index.
 *
 * @param format The formatted row key format for this table.
 * @param kijiRowKey An ordered list of Objects of the key components.
 * @return A byte array representing the encoded Hbase row key.
 */
private static byte[] makeHbaseRowKey(RowKeyFormat2 format, List<Object> kijiRowKey) {

    ArrayList<byte[]> hbaseKey = new ArrayList<byte[]>();
    final byte zeroDelim = 0;

    int pos;
    for (pos = 0; pos < kijiRowKey.size(); pos++) {
        // we have already done the validation check for null cascades.
        if (null == kijiRowKey.get(pos)) {
            continue;
        }
        byte[] tempBytes;
        switch (getType(kijiRowKey.get(pos))) {
        case STRING:
            if (((String) kijiRowKey.get(pos)).contains("\u0000")) {
                throw new EntityIdException("String component cannot contain \u0000");
            }
            try {
                hbaseKey.add(((String) kijiRowKey.get(pos)).getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LOG.error(e.toString());
                throw new EntityIdException(String.format("UnsupportedEncoding for component %d", pos));
            }
            break;
        case INTEGER:
            int temp = (Integer) kijiRowKey.get(pos);
            tempBytes = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(temp).array();
            tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE);
            hbaseKey.add(tempBytes);
            break;
        case LONG:
            long templong = (Long) kijiRowKey.get(pos);
            tempBytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(templong).array();
            tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE);
            hbaseKey.add(tempBytes);
            break;
        default:
            throw new RuntimeException("Invalid code path");
        }
    }

    // hash stuff
    int hashUpto = format.getRangeScanStartIndex() - 1;
    ByteArrayOutputStream tohash = new ByteArrayOutputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (pos = 0; pos <= hashUpto && pos < hbaseKey.size(); pos++) {
        tohash.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length);
    }
    byte[] hashed = Arrays.copyOfRange(Hasher.hash(tohash.toByteArray()), 0, format.getSalt().getHashSize());
    baos.write(hashed, 0, hashed.length);

    // to materialize or not to materialize that is the question
    if (format.getSalt().getSuppressKeyMaterialization()) {
        return baos.toByteArray();
    } else {
        for (pos = 0; pos < hbaseKey.size(); pos++) {
            baos.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length);
            if (format.getComponents().get(pos).getType() == ComponentType.STRING
                    || format.getComponents().get(pos) == null) {
                // empty strings will be encoded as null, hence we need to delimit them too
                baos.write(zeroDelim);
            }
        }
        return baos.toByteArray();
    }
}

From source file:com.moz.fiji.schema.FormattedEntityId.java

/**
 * Create an hbase row key, which is a byte array from the given formatted fijiRowKey.
 * This method requires that the fijiRowKey argument is the correct length for the specified
 * format.//from   w  ww  .j  a  v  a 2 s  . c o  m
 * The following encoding will be used to ensure correct ordering:
 * Strings are UTF-8 encoded and terminated by a null byte. Strings cannot contain "\u0000".
 * Integers are exactly 4 bytes long.
 * Longs are exactly 8 bytes long.
 * Both integers and longs have the sign bit flipped so that their values are wrapped around to
 * create the correct lexicographic ordering. (i.e. after converting to byte array,
 * MIN_INT < 0 < MAX_INT).
 * Hashed components are exactly hash_size bytes long and are the first component of
 * the hbase key.
 * Except for the first, all components of a fijiRowKey can be null. However, to maintain
 * ordering, all components to the right of a null component must also be null. Nullable index
 * in the row key format specifies which component (and hence following components) are nullable.
 * By default, the hash only uses the first component, but this can be changed using the Range
 * Scan index.
 *
 * @param format The formatted row key format for this table.
 * @param fijiRowKey An ordered list of Objects of the key components.
 * @return A byte array representing the encoded Hbase row key.
 */
private static byte[] makeHbaseRowKey(RowKeyFormat2 format, List<Object> fijiRowKey) {

    ArrayList<byte[]> hbaseKey = new ArrayList<byte[]>();
    final byte zeroDelim = 0;

    int pos;
    for (pos = 0; pos < fijiRowKey.size(); pos++) {
        // we have already done the validation check for null cascades.
        if (null == fijiRowKey.get(pos)) {
            continue;
        }
        byte[] tempBytes;
        switch (getType(fijiRowKey.get(pos))) {
        case STRING:
            if (((String) fijiRowKey.get(pos)).contains("\u0000")) {
                throw new EntityIdException("String component cannot contain \u0000");
            }
            try {
                hbaseKey.add(((String) fijiRowKey.get(pos)).getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LOG.error(e.toString());
                throw new EntityIdException(String.format("UnsupportedEncoding for component %d", pos));
            }
            break;
        case INTEGER:
            int temp = (Integer) fijiRowKey.get(pos);
            tempBytes = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(temp).array();
            tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE);
            hbaseKey.add(tempBytes);
            break;
        case LONG:
            long templong = (Long) fijiRowKey.get(pos);
            tempBytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(templong).array();
            tempBytes[0] = (byte) ((int) tempBytes[0] ^ (int) Byte.MIN_VALUE);
            hbaseKey.add(tempBytes);
            break;
        default:
            throw new RuntimeException("Invalid code path");
        }
    }

    // hash stuff
    int hashUpto = format.getRangeScanStartIndex() - 1;
    ByteArrayOutputStream tohash = new ByteArrayOutputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (pos = 0; pos <= hashUpto && pos < hbaseKey.size(); pos++) {
        tohash.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length);
    }
    byte[] hashed = Arrays.copyOfRange(Hasher.hash(tohash.toByteArray()), 0, format.getSalt().getHashSize());
    baos.write(hashed, 0, hashed.length);

    // to materialize or not to materialize that is the question
    if (format.getSalt().getSuppressKeyMaterialization()) {
        return baos.toByteArray();
    } else {
        for (pos = 0; pos < hbaseKey.size(); pos++) {
            baos.write(hbaseKey.get(pos), 0, hbaseKey.get(pos).length);
            if (format.getComponents().get(pos).getType() == ComponentType.STRING
                    || format.getComponents().get(pos) == null) {
                // empty strings will be encoded as null, hence we need to delimit them too
                baos.write(zeroDelim);
            }
        }
        return baos.toByteArray();
    }
}

From source file:org.skife.muckery.mappy.ByteUtils.java

/**
 * Get the nth byte from the right in the given number
 *
 * @param l The number from which to extract the byte
 * @param n The byte index/*from   w ww. j a va  2 s.com*/
 * @return The given byte
 */
public static byte readNthByte(long l, int n) {
    return (byte) (0xFF & (l >> (n * Byte.SIZE)));
}

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

private SecretKey scrypt(CharSequence password, byte[] salt, int costParam, int blockSize,
        int keyLengthInBits) {
    // use sb, as password.toString's implementation is unknown
    final StringBuilder sb = new StringBuilder(password);
    final byte[] pw = sb.toString().getBytes();
    try {/*from   ww w .  j av a2s  . c o m*/
        final byte[] key = SCrypt.generate(pw, salt, costParam, blockSize, 1, keyLengthInBits / Byte.SIZE);
        return new SecretKeySpec(key, AES_KEY_ALGORITHM);
    } finally {
        // destroy copied bytes of the plaintext password:
        Arrays.fill(pw, (byte) 0);
        for (int i = 0; i < password.length(); i++) {
            sb.setCharAt(i, (char) 0);
        }
    }
}