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:com.openteach.diamond.network.waverider.network.Packet.java

/**
 * ??/*from  ww w .j  a va 2s. c  o m*/
 * @return
 */
public static int getLengthPosition() {
    int size = 0;
    size += NetWorkConstants.WAVERIDER_MAGIC.getBytes().length;
    size += Long.SIZE / Byte.SIZE;
    size += Long.SIZE / Byte.SIZE;

    return size;
}

From source file:org.apache.sshd.server.PasswordAuthenticatorUtilsTest.java

@Test
public void testRejectAllPasswordAuthenticatorOnVariousValues() {
    Collection<String> values = Collections.unmodifiableList(
            Arrays.asList(getClass().getSimpleName(), "testRejectAllPasswordAuthenticatorOnVariousValues"));
    for (String username : values) {
        for (String password : values) {
            for (int index = 0; index < Byte.SIZE; index++) {
                String u = shuffleCase(username), p = shuffleCase(password);
                assertFalse("user=" + u + "/password=" + p,
                        PasswordAuthenticatorUtils.REJECT_ALL_AUTHENTICATOR.authenticate(u, p, MOCK_SESSION));
            }//from w  w  w.j a  va2 s.  c  om
        }
    }
}

From source file:com.moscona.dataSpace.Numeric.java

@Override
public long sizeInBytes() {
    if (value == null) {
        return 2L;
    }//w  w  w.j av a 2  s .c om
    if (value.getClass() == Double.class) {
        return 2L + Double.SIZE / 8;
    }
    if (value.getClass() == Float.class) {
        return 2L + Float.SIZE / 8;
    }
    if (value.getClass() == Long.class) {
        return 2L + Long.SIZE / 8;
    }
    if (value.getClass() == Integer.class) {
        return 2L + Integer.SIZE / 8;
    }
    if (value.getClass() == Short.class) {
        return 2L + Short.SIZE / 8;
    }
    if (value.getClass() == Byte.class) {
        return 2L + Byte.SIZE / 8;
    }
    return 2L;
}

From source file:org.apache.hadoop.hive.serde2.compression.SnappyCompDe.java

/**
 * Compress a set of columns.//from w w w. j  a v a  2  s .co  m
 *
 * The header contains a compressed array of data types.
 * The body contains compressed columns and their metadata.
 * The footer contains a compressed array of chunk sizes. The final four bytes of the footer encode the byte size of that compressed array.
 *
 * @param colSet
 *
 * @return ByteBuffer representing the compressed set.
 */
@Override
public ByteBuffer compress(ColumnBuffer[] colSet) {

    // Many compression libraries allow you to avoid allocation of intermediate arrays.
    // To use these API, we need to preallocate the output container.

    // Reserve space for the header.
    int[] dataType = new int[colSet.length];
    int maxCompressedSize = Snappy.maxCompressedLength(4 * dataType.length);

    // Reserve space for the compressed nulls BitSet for each column.
    maxCompressedSize += colSet.length * Snappy.maxCompressedLength((colSet.length / 8) + 1);

    // Track the length of `List<Integer> compressedSize` which will be declared later.
    int uncompressedFooterLength = 1 + 2 * colSet.length;

    for (int colNum = 0; colNum < colSet.length; ++colNum) {
        // Reserve space for the compressed columns.
        dataType[colNum] = colSet[colNum].getType().toTType().getValue();
        switch (TTypeId.findByValue(dataType[colNum])) {
        case BOOLEAN_TYPE:
            maxCompressedSize += Integer.SIZE / Byte.SIZE; // This is for the encoded length.
            maxCompressedSize += Snappy.maxCompressedLength((colSet.length / 8) + 1);
            break;
        case TINYINT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length);
            break;
        case SMALLINT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Short.SIZE / Byte.SIZE);
            break;
        case INT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Integer.SIZE / Byte.SIZE);
            break;
        case BIGINT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Long.SIZE / Byte.SIZE);
            break;
        case DOUBLE_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Double.SIZE / Byte.SIZE);
            break;
        case BINARY_TYPE:
            // Reserve space for the size of the compressed array of row sizes.
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Integer.SIZE / Byte.SIZE);

            // Reserve space for the size of the compressed flattened bytes.
            for (ByteBuffer nextBuffer : colSet[colNum].toTColumn().getBinaryVal().getValues()) {
                maxCompressedSize += Snappy.maxCompressedLength(nextBuffer.limit());
            }

            // Add an additional value to the list of compressed chunk sizes (length of `rowSize` array).
            uncompressedFooterLength++;

            break;
        case STRING_TYPE:
            // Reserve space for the size of the compressed array of row sizes.
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Integer.SIZE / Byte.SIZE);

            // Reserve space for the size of the compressed flattened bytes.
            for (String nextString : colSet[colNum].toTColumn().getStringVal().getValues()) {
                maxCompressedSize += Snappy
                        .maxCompressedLength(nextString.getBytes(StandardCharsets.UTF_8).length);
            }

            // Add an additional value to the list of compressed chunk sizes (length of `rowSize` array).
            uncompressedFooterLength++;

            break;
        default:
            throw new IllegalStateException("Unrecognized column type");
        }
    }
    // Reserve space for the footer.
    maxCompressedSize += Snappy.maxCompressedLength(uncompressedFooterLength * Integer.SIZE / Byte.SIZE);

    // Allocate the output container.
    ByteBuffer output = ByteBuffer.allocate(maxCompressedSize);

    // Allocate the footer. This goes in the footer because we don't know the chunk sizes until after
    // the columns have been compressed and written.
    ArrayList<Integer> compressedSize = new ArrayList<Integer>(uncompressedFooterLength);

    // Write to the output buffer.
    try {
        // Write the header.
        compressedSize.add(writePrimitives(dataType, output));

        // Write the compressed columns and metadata.
        for (int colNum = 0; colNum < colSet.length; colNum++) {
            switch (TTypeId.findByValue(dataType[colNum])) {
            case BOOLEAN_TYPE: {
                TBoolColumn column = colSet[colNum].toTColumn().getBoolVal();

                List<Boolean> bools = column.getValues();
                BitSet bsBools = new BitSet(bools.size());
                for (int rowNum = 0; rowNum < bools.size(); rowNum++) {
                    bsBools.set(rowNum, bools.get(rowNum));
                }

                compressedSize.add(writePrimitives(column.getNulls(), output));

                // BitSet won't write trailing zeroes so we encode the length
                output.putInt(column.getValuesSize());

                compressedSize.add(writePrimitives(bsBools.toByteArray(), output));

                break;
            }
            case TINYINT_TYPE: {
                TByteColumn column = colSet[colNum].toTColumn().getByteVal();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedBytes(column.getValues(), output));
                break;
            }
            case SMALLINT_TYPE: {
                TI16Column column = colSet[colNum].toTColumn().getI16Val();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedShorts(column.getValues(), output));
                break;
            }
            case INT_TYPE: {
                TI32Column column = colSet[colNum].toTColumn().getI32Val();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedIntegers(column.getValues(), output));
                break;
            }
            case BIGINT_TYPE: {
                TI64Column column = colSet[colNum].toTColumn().getI64Val();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedLongs(column.getValues(), output));
                break;
            }
            case DOUBLE_TYPE: {
                TDoubleColumn column = colSet[colNum].toTColumn().getDoubleVal();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedDoubles(column.getValues(), output));
                break;
            }
            case BINARY_TYPE: {
                TBinaryColumn column = colSet[colNum].toTColumn().getBinaryVal();

                // Initialize the array of row sizes.
                int[] rowSizes = new int[column.getValuesSize()];
                int totalSize = 0;
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    rowSizes[rowNum] = column.getValues().get(rowNum).limit();
                    totalSize += column.getValues().get(rowNum).limit();
                }

                // Flatten the data for Snappy for a better compression ratio.
                ByteBuffer flattenedData = ByteBuffer.allocate(totalSize);
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    flattenedData.put(column.getValues().get(rowNum));
                }

                // Write nulls bitmap.
                compressedSize.add(writePrimitives(column.getNulls(), output));

                // Write the list of row sizes.
                compressedSize.add(writePrimitives(rowSizes, output));

                // Write the compressed, flattened data.
                compressedSize.add(writePrimitives(flattenedData.array(), output));

                break;
            }
            case STRING_TYPE: {
                TStringColumn column = colSet[colNum].toTColumn().getStringVal();

                // Initialize the array of row sizes.
                int[] rowSizes = new int[column.getValuesSize()];
                int totalSize = 0;
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    rowSizes[rowNum] = column.getValues().get(rowNum).length();
                    totalSize += column.getValues().get(rowNum).length();
                }

                // Flatten the data for Snappy for a better compression ratio.
                StringBuilder flattenedData = new StringBuilder(totalSize);
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    flattenedData.append(column.getValues().get(rowNum));
                }

                // Write nulls bitmap.
                compressedSize.add(writePrimitives(column.getNulls(), output));

                // Write the list of row sizes.
                compressedSize.add(writePrimitives(rowSizes, output));

                // Write the flattened data.
                compressedSize.add(
                        writePrimitives(flattenedData.toString().getBytes(StandardCharsets.UTF_8), output));

                break;
            }
            default:
                throw new IllegalStateException("Unrecognized column type");
            }
        }

        // Write the footer.
        output.putInt(writeBoxedIntegers(compressedSize, output));

    } catch (IOException e) {
        e.printStackTrace();
    }
    output.flip();
    return output;
}

From source file:mamo.vanillaVotifier.VotifierServer.java

public synchronized void start() throws IOException {
    if (isRunning()) {
        throw new IllegalStateException("Server is already running!");
    }/* w w  w  .  jav a  2  s  .  c  o  m*/
    notifyListeners(new ServerStartingEvent());
    serverSocket = new ServerSocket();
    serverSocket.bind(votifier.getConfig().getInetSocketAddress());
    running = true;
    notifyListeners(new ServerStartedEvent());
    new Thread(new Runnable() {
        @Override
        public void run() {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            while (isRunning()) {
                try {
                    final Socket socket = serverSocket.accept();
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                notifyListeners(new ConnectionEstablishedEvent(socket));
                                socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch.
                                BufferedWriter writer = new BufferedWriter(
                                        new OutputStreamWriter(socket.getOutputStream()));
                                writer.write("VOTIFIER 2.9\n");
                                writer.flush();
                                BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch.
                                byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair()
                                        .getPublic()).getModulus().bitLength() / Byte.SIZE];
                                in.read(request); // IOException: handled by try/catch.
                                notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request)));
                                request = RsaUtils
                                        .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate())
                                        .doFinal(request); // IllegalBlockSizeException: can't happen.
                                String requestString = new String(request);
                                notifyListeners(new DecryptedInputReceivedEvent(socket, requestString));
                                String[] requestArray = requestString.split("\n");
                                if ((requestArray.length == 5 || requestArray.length == 6)
                                        && requestArray[0].equals("VOTE")) {
                                    notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1],
                                            requestArray[2], requestArray[3], requestArray[4])));
                                    for (VoteAction voteAction : votifier.getConfig().getVoteActions()) {
                                        String[] params = new String[4];
                                        try {
                                            for (int i = 0; i < params.length; i++) {
                                                params[i] = SubstitutionUtils.applyRegexReplacements(
                                                        requestArray[i + 1], voteAction.getRegexReplacements());
                                            }
                                        } catch (PatternSyntaxException e) {
                                            notifyListeners(new RegularExpressionPatternErrorException(e));
                                            params = new String[] { requestArray[1], requestArray[2],
                                                    requestArray[3], requestArray[4] };
                                        }
                                        if (voteAction.getCommandSender() instanceof RconCommandSender) {
                                            RconCommandSender commandSender = (RconCommandSender) voteAction
                                                    .getCommandSender();
                                            StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor(
                                                    new SimpleEntry<String, Object>("service-name", params[0]),
                                                    new SimpleEntry<String, Object>("user-name", params[1]),
                                                    new SimpleEntry<String, Object>("address", params[2]),
                                                    new SimpleEntry<String, Object>("timestamp", params[3]));
                                            for (String command : voteAction.getCommands()) {
                                                String theCommand = substitutor.replace(command);
                                                notifyListeners(new SendingRconCommandEvent(
                                                        commandSender.getRconConnection(), theCommand));
                                                try {
                                                    notifyListeners(new RconCommandResponseEvent(
                                                            commandSender.getRconConnection(), commandSender
                                                                    .sendCommand(theCommand).getPayload()));
                                                } catch (Exception e) {
                                                    notifyListeners(new RconExceptionEvent(
                                                            commandSender.getRconConnection(), e));
                                                }
                                            }
                                        }
                                        if (voteAction.getCommandSender() instanceof ShellCommandSender) {
                                            ShellCommandSender commandSender = (ShellCommandSender) voteAction
                                                    .getCommandSender();
                                            HashMap<String, String> environment = new HashMap<String, String>();
                                            environment.put("voteServiceName", params[0]);
                                            environment.put("voteUserName", params[1]);
                                            environment.put("voteAddress", params[2]);
                                            environment.put("voteTimestamp", params[3]);
                                            for (String command : voteAction.getCommands()) {
                                                notifyListeners(new SendingShellCommandEvent(command));
                                                try {
                                                    commandSender.sendCommand(command, environment);
                                                    notifyListeners(new ShellCommandSentEvent());
                                                } catch (Exception e) {
                                                    notifyListeners(new ShellCommandExceptionEvent(e));
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    notifyListeners(new InvalidRequestEvent(socket, requestString));
                                }
                            } catch (SocketTimeoutException e) {
                                notifyListeners(new ReadTimedOutExceptionEvent(socket, e));
                            } catch (BadPaddingException e) {
                                notifyListeners(new DecryptInputExceptionEvent(socket, e));
                            } catch (Exception e) {
                                notifyListeners(new CommunicationExceptionEvent(socket, e));
                            }
                            try {
                                socket.close();
                                notifyListeners(new ConnectionClosedEvent(socket));
                            } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close.
                                notifyListeners(new ConnectionCloseExceptionEvent(socket, e));
                            }
                        }
                    });
                } catch (Exception e) {
                    if (running) { // Show errors only while running, to hide error while stopping.
                        notifyListeners(new ConnectionEstablishExceptionEvent(e));
                    }
                }
            }
            executorService.shutdown();
            if (!executorService.isTerminated()) {
                notifyListeners(new ServerAwaitingTaskCompletionEvent());
                try {
                    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
                } catch (Exception e) {
                    // InterruptedException: can't happen.
                }
            }
            notifyListeners(new ServerStoppedEvent());
        }
    }).start();
}

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

@Test
public void testListEntities() {
    Set<String> expected = new TreeSet<String>();
    for (int index = 0; index < Byte.SIZE; index++) {
        TestEntry e = new TestEntry();
        repo.setProperties(e, new Transformer<TestEntry, Map<String, ?>>() {
            @Override//  w ww  . j a  v  a 2 s. co m
            public Map<String, ?> transform(TestEntry input) {
                return Collections.<String, Serializable>singletonMap(PROP_NAME, Double.valueOf(Math.random()));
            }
        });
        expected.add(e.getId());
    }

    List<String> idsList = repo.listEntities();
    assertEquals("Mismatched entities list count", expected.size(), ExtendedCollectionUtils.size(idsList));

    Set<String> actual = new TreeSet<>(idsList);
    assertEquals("Mismatched unique entities count", idsList.size(), actual.size());

    if (!CollectionUtils.isEqualCollection(expected, actual)) {
        fail("Mismatched ID set: expected=" + expected + ", actual=" + actual);
    }
}

From source file:com.xsdn.main.util.EtherAddress.java

/**
 * Convert a long number which represents an ethernet address into a byte
 * array./*from w  ww.  jav  a  2  s.c  om*/
 *
 * @param addr  A long integer which represents an byte array.
 * @return  A byte array that contains 6 octets.
 */
public static byte[] toBytes(long addr) {
    long value = addr;
    byte[] mac = new byte[SIZE];
    int i = SIZE - 1;
    do {
        mac[i] = (byte) value;
        value >>>= Byte.SIZE;
        i--;
    } while (i >= 0);

    return mac;
}

From source file:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java

@Test
public void testDeepDownRepositoryResolution() throws Exception {
    final String REPO_NAME = "testDeepDownRepositoryResolution", GIT_NAME = REPO_NAME + Constants.DOT_GIT_EXT;
    final int MAX_DEPTH = Byte.SIZE;
    StringBuilder sb = new StringBuilder(MAX_DEPTH + Long.SIZE);
    File parentDir = reposDir;//  www .  jav  a 2  s.com
    for (int depth = 0; depth < MAX_DEPTH; depth++) {
        String subName = String.valueOf(depth);
        parentDir = new File(parentDir, subName);
        sb.append(subName).append('/');

        File gitDir = new File(parentDir, GIT_NAME);
        if (!gitDir.exists()) {
            Repository repo = new FileRepository(gitDir);
            try {
                repo.create(true);
            } finally {
                repo.close();
            }
        } else {
            assertTrue("Child repo not a folder: " + gitDir, gitDir.isDirectory());
        }

        int curLen = sb.length();
        try {
            sb.append(REPO_NAME);

            int baseLen = sb.length();
            for (String ext : TEST_EXTS) {
                try {
                    Repository repo = resolver.open(null, sb.append(ext).toString());
                    assertNotNull("No resolution result for ext=" + ext, repo);

                    try {
                        File actual = repo.getDirectory();
                        assertEquals("Mismatched resolved location for ext=" + ext, gitDir, actual);
                    } finally {
                        repo.close();
                    }
                } finally {
                    sb.setLength(baseLen);
                }
            }
        } finally {
            sb.setLength(curLen);
        }
    }
}

From source file:net.ripe.rpki.commons.crypto.util.Asn1Util.java

/**
 * {@link IpAddress} used as a prefix.//from w w  w .  j a  v  a 2  s  . c  o  m
 */
public static IpRange parseIpAddressAsPrefix(IpResourceType type, ASN1Encodable der) {
    expect(der, DERBitString.class);
    DERBitString derBitString = (DERBitString) der;

    IpAddress ipAddress = parseIpAddress(type, derBitString, false);

    int padBits = derBitString.getPadBits();
    return IpRange.prefix(ipAddress, derBitString.getBytes().length * Byte.SIZE - padBits);
}

From source file:org.apache.spark.network.crypto.AuthEngine.java

/**
 * Validates the client challenge, and create the encryption backend for the channel from the
 * parameters sent by the client.//w  w w. j a  v a2  s  .  c o  m
 *
 * @param clientChallenge The challenge from the client.
 * @return A response to be sent to the client.
 */
ServerResponse respond(ClientChallenge clientChallenge) throws GeneralSecurityException, IOException {

    SecretKeySpec authKey = generateKey(clientChallenge.kdf, clientChallenge.iterations, clientChallenge.nonce,
            clientChallenge.keyLength);
    initializeForAuth(clientChallenge.cipher, clientChallenge.nonce, authKey);

    byte[] challenge = validateChallenge(clientChallenge.nonce, clientChallenge.challenge);
    byte[] response = challenge(appId, clientChallenge.nonce, rawResponse(challenge));
    byte[] sessionNonce = randomBytes(conf.encryptionKeyLength() / Byte.SIZE);
    byte[] inputIv = randomBytes(conf.ivLength());
    byte[] outputIv = randomBytes(conf.ivLength());

    SecretKeySpec sessionKey = generateKey(clientChallenge.kdf, clientChallenge.iterations, sessionNonce,
            clientChallenge.keyLength);
    this.sessionCipher = new TransportCipher(cryptoConf, clientChallenge.cipher, sessionKey, inputIv, outputIv);

    // Note the IVs are swapped in the response.
    return new ServerResponse(response, encrypt(sessionNonce), encrypt(outputIv), encrypt(inputIv));
}