Example usage for java.math BigInteger ZERO

List of usage examples for java.math BigInteger ZERO

Introduction

In this page you can find the example usage for java.math BigInteger ZERO.

Prototype

BigInteger ZERO

To view the source code for java.math BigInteger ZERO.

Click Source Link

Document

The BigInteger constant zero.

Usage

From source file:org.opendaylight.netvirt.vpnmanager.ArpNotificationHandler.java

private void processArpLearning(String srcInterface, IpAddress srcIP, PhysAddress srcMac, BigInteger metadata,
        IpAddress dstIP) {//ww w  . ja  va 2 s  .  c o  m
    if (metadata != null && !Objects.equals(metadata, BigInteger.ZERO)) {
        long vpnId = MetaDataUtil.getVpnIdFromMetadata(metadata);
        // Process ARP only if vpnservice is configured on the interface
        InstanceIdentifier<VpnIds> vpnIdsInstanceIdentifier = VpnUtil.getVpnIdToVpnInstanceIdentifier(vpnId);
        Optional<VpnIds> vpnIdsOptional = VpnUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION,
                vpnIdsInstanceIdentifier);
        if (!vpnIdsOptional.isPresent()) {
            LOG.trace("ARP NO_RESOLVE: VPN {} not configured. Ignoring responding to ARP requests on this VPN",
                    vpnId);
            return;
        }
        VpnIds vpnIds = vpnIdsOptional.get();
        String vpnName = vpnIds.getVpnInstanceName();
        if (VpnUtil.isInterfaceAssociatedWithVpn(dataBroker, vpnName, srcInterface)) {
            LOG.debug("Received ARP for sender MAC {} and sender IP {} via interface {}", srcMac.getValue(),
                    srcIP.getIpv4Address().getValue(), srcInterface);
            String ipToQuery = srcIP.getIpv4Address().getValue();
            LOG.trace("ARP being processed for Source IP {}", ipToQuery);
            VpnPortipToPort vpnPortipToPort = VpnUtil.getNeutronPortFromVpnPortFixedIp(dataBroker, vpnName,
                    ipToQuery);
            if (vpnPortipToPort != null) {
                /* This is a well known neutron port and so should be ignored
                 * from being discovered
                 */
                return;
            }
            LearntVpnVipToPort learntVpnVipToPort = VpnUtil.getLearntVpnVipToPort(dataBroker, vpnName,
                    ipToQuery);
            if (learntVpnVipToPort != null) {
                String oldPortName = learntVpnVipToPort.getPortName();
                String oldMac = learntVpnVipToPort.getMacAddress();
                if (!oldMac.equalsIgnoreCase(srcMac.getValue())) {
                    //MAC has changed for requested IP
                    LOG.trace("ARP Source IP/MAC data modified for IP {} with MAC {} and Port {}", ipToQuery,
                            srcMac, srcInterface);
                    synchronized ((vpnName + ipToQuery).intern()) {
                        removeMipAdjacency(vpnName, oldPortName, srcIP);
                        VpnUtil.removeLearntVpnVipToPort(dataBroker, vpnName, ipToQuery);
                        putVpnIpToMigrateArpCache(vpnName, ipToQuery, srcMac);
                    }
                }
            } else if (!isIpInArpMigrateCache(vpnName, ipToQuery)) {
                learnMacFromArpPackets(vpnName, srcInterface, srcIP, srcMac, dstIP);
            }
        }
    }
}

From source file:com.docd.purefm.file.JavaFile.java

/**
 * {@inheritDoc}//from ww  w  . j a  v  a 2  s .  c  o  m
 */
@Override
public BigInteger lengthTotal() {
    if (mFile.exists()) {
        try {
            return FileUtils.sizeOfAsBigInteger(mFile);
        } catch (StackOverflowError e) {
            //if we have too much directories, we can get this
            return BigInteger.valueOf(-1);
        }
    }
    return BigInteger.ZERO;
}

From source file:test.be.fedict.eid.applet.RSATest.java

@Test
public void testManualEncryption() throws Exception {
    while (true) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA",
                BouncyCastleProvider.PROVIDER_NAME);
        SecureRandom random = new SecureRandom();
        int keySize = 128;
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
        LOG.debug("private key modulus: " + rsaPrivateKey.getModulus());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        LOG.debug("public key modulus: " + rsaPublicKey.getModulus());
        LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent());
        LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        int dataSize = keySize / 8 - 11;
        byte[] data1 = new byte[dataSize];
        for (int i = 0; i < data1.length; i++) {
            data1[i] = 0x00;/*from ww  w  . j  a  v a 2  s  . c  o m*/
        }
        byte[] data2 = new byte[dataSize];
        for (int i = 0; i < data2.length; i++) {
            data2[i] = 0x00;
        }
        data2[data2.length - 1] = 0x07;

        byte[] signatureValue1 = cipher.doFinal(data1);

        LOG.debug("signature size: " + signatureValue1.length);

        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] signatureValue2 = cipher.doFinal(data2);

        BigInteger sigBigInt1 = new BigInteger(signatureValue1);
        BigInteger sigBigInt2 = new BigInteger(signatureValue2);
        BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        LOG.debug("msg big int: " + msgBigInt1);
        byte[] msgBytes1 = msgBigInt1.toByteArray();
        LOG.debug("original message size: " + msgBytes1.length);
        LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1)));
        LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray())));

        LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100));
        LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100));

        // BigInteger.pow offers a very naive implementation
        LOG.debug("calculating s1^e...");
        BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s1^e: " + s1_e);
        LOG.debug("calculating s2^e...");
        BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s2^e: " + s2_e);

        LOG.debug("calculating GCD...");
        LOG.debug("msg1: " + msgBigInt1);
        LOG.debug("msg2: " + msgBigInt2);
        BigInteger a = s1_e.subtract(msgBigInt1);
        BigInteger b = s2_e.subtract(msgBigInt2);
        LOG.debug("a: " + a);
        LOG.debug("b: " + b);
        BigInteger candidateModulus = a.gcd(b);
        LOG.debug("candidate modulus: " + candidateModulus);
        LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length);
        BigInteger s_e = s1_e.multiply(s2_e);
        BigInteger m = msgBigInt1.multiply(msgBigInt2);
        while (false == rsaPublicKey.getModulus().equals(candidateModulus)) {
            LOG.error("incorrect candidate modulus");
            LOG.debug("modulus | candidate modulus: "
                    + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO));
            s_e = s_e.multiply(s1_e);
            m = m.multiply(msgBigInt1);
            BigInteger n1 = s_e.subtract(m).gcd(a);
            BigInteger n2 = s_e.subtract(m).gcd(b);
            candidateModulus = n1.gcd(n2);
            // try / 2
            LOG.debug("new modulus:       " + n1);
            LOG.debug("new modulus:       " + n2);
            LOG.debug("candidate modulus: " + candidateModulus);
            LOG.debug("actual mod:        " + rsaPublicKey.getModulus());
        }
    }
}

From source file:org.esupportail.portlet.filemanager.services.opencmis.CmisAccessImpl.java

/**
 * @param cmisObject//from   w w w  .  ja  v a2 s  . c  om
 * @param path
 * @param parentPath
 * @return a JsTreeFile where lid = /cmis_parent_parent_object_idJsTreeFile.ID_TITLE_SPLITcmis_parent_parent_object_name/cmis_parent_object_idJsTreeFile.ID_TITLE_SPLITcmis_parent_object_name/cmis_object_idJsTreeFile.ID_TITLE_SPLITcmis_object_name
 */
private JsTreeFile cmisObjectAsJsTreeFile(CmisObject cmisObject, String path, String parentPath,
        boolean folderDetails, boolean fileDetails) {
    // TODO: folderDetails
    // TODO: fileDetails
    String title = cmisObject.getName();
    String lid = cmisObject.getId().concat(JsTreeFile.ID_TITLE_SPLIT).concat(title);
    if (path != null) {
        lid = path;
    } else if (parentPath != null) {
        lid = parentPath.concat("/").concat(lid);
    }
    // remove / at the beginning if it exists
    if (lid.startsWith("/"))
        lid = lid.substring(1);

    String type = (BaseTypeId.CMIS_DOCUMENT.equals(cmisObject.getBaseTypeId())) ? "file" : "folder";

    // root case :
    if ("".equals(path)) {
        title = "";
        type = "drive";
    }

    JsTreeFile file = new JsTreeFile(title, lid, type);
    if (fileDetails) {

        if ("file".equals(type)) {
            String icon = resourceUtils.getIcon(title);
            file.setIcon(icon);

            Document document = (Document) cmisObject;
            BigInteger size = BigInteger.ZERO;
            List<Object> contentStreamLength = document.getProperty("cmis:contentStreamLength").getValues();
            if (!contentStreamLength.isEmpty())
                size = (BigInteger) contentStreamLength.get(0);
            file.setSize(size.longValue());
            file.setOverSizeLimit(file.getSize() > resourceUtils.getSizeLimit(title));
        }

        Date date = cmisObject.getLastModificationDate().getTime();
        file.setLastModifiedTime(new SimpleDateFormat(this.datePattern).format(date));

    }

    if (folderDetails && ("folder".equals(type) || "drive".equals(type))) {
        Folder folder = (Folder) cmisObject;
        ItemIterable<CmisObject> pl = folder.getChildren();
        long totalSize = 0;
        long fileCount = 0;
        long folderCount = 0;
        fileCount = pl.getTotalNumItems();

        for (CmisObject child : pl) {
            String childType = (BaseTypeId.CMIS_DOCUMENT.equals(child.getBaseTypeId())) ? "file" : "folder";
            if ("folder".equals(childType)) {
                ++folderCount;
            } else if ("file".equals(childType)) {
                ++fileCount;
                Document document = (Document) child;
                BigInteger size = BigInteger.ZERO;
                List<Object> contentStreamLength = document.getProperty("cmis:contentStreamLength").getValues();
                if (!contentStreamLength.isEmpty())
                    size = (BigInteger) contentStreamLength.get(0);
                totalSize += size.longValue();
            }
        }
        file.setTotalSize(totalSize);
        file.setFileCount(fileCount);
        file.setFolderCount(folderCount);
    }

    Set<Action> actions = cmisObject.getAllowableActions().getAllowableActions();
    // check if actions seem to be filled correctly
    if (actions.contains(Action.CAN_GET_PROPERTIES)) {
        // ok, set capability based on available actions
        file.setWriteable(actions.contains(Action.CAN_DELETE_OBJECT));
    }

    return file;
}

From source file:com.mothsoft.alexis.engine.numeric.TopicActivityDataSetImporter.java

private BigInteger importTopicDataForTopic(final Long topicId, final Date startDate, final Date endDate) {
    logger.debug(String.format("Importing topic activity for topic: %d between %s and %s", topicId,
            startDate.toString(), endDate.toString()));

    final String queryString = "SELECT DATE_FORMAT(td.creation_date, '%Y-%m-%d %H:00:00') as the_hour, "
            + " COUNT(td.id) from topic_document td INNER JOIN topic on topic.id = td.topic_id "
            + " WHERE td.creation_date >= ? AND td.creation_date <= ? AND td.topic_id = ? "
            + " GROUP BY the_hour ORDER BY td.creation_date";

    final BigInteger count = this.transactionTemplate.execute(new TransactionCallback<BigInteger>() {
        @Override/*from  w ww.  j a v  a2s.c o m*/
        public BigInteger doInTransaction(TransactionStatus txStatus) {
            final Query query = TopicActivityDataSetImporter.this.em.createNativeQuery(queryString);
            query.setParameter(1, startDate);
            query.setParameter(2, endDate);
            query.setParameter(3, topicId);

            final List<?> results = query.getResultList();

            if (results == null || results.isEmpty()) {
                return BigInteger.ZERO;
            } else {
                final Object[] array = (Object[]) results.get(0);
                return (BigInteger) array[1];
            }
        }
    });

    logger.debug("Data set point: (" + startDate + ", " + count + ")");

    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            TopicActivityDataSet dataSet = TopicActivityDataSetImporter.this.dataSetDao
                    .findTopicActivityDataSet(topicId);

            if (dataSet == null) {
                final DataSetType type = TopicActivityDataSetImporter.this.dataSetTypeDao
                        .findSystemDataSetType(DataSetType.TOPIC_ACTIVITY);
                final Topic topic = TopicActivityDataSetImporter.this.topicDao.get(topicId);
                dataSet = new TopicActivityDataSet(topic, type);
                TopicActivityDataSetImporter.this.em.persist(dataSet);
            }

            final DataSetPoint point = new DataSetPoint(dataSet, startDate, count.doubleValue());
            TopicActivityDataSetImporter.this.dataSetPointDao.add(point);
        }
    });

    return count;
}

From source file:org.openhim.mediator.denormalization.ATNAAuditingActor.java

protected String generateForRegistryQueryReceived(ATNAAudit audit) throws JAXBException {
    AuditMessage res = new AuditMessage();

    EventIdentificationType eid = new EventIdentificationType();
    eid.setEventID(ATNAUtil.buildCodedValueType("DCM", "110112", "Query"));
    eid.setEventActionCode("E");
    eid.setEventDateTime(ATNAUtil.newXMLGregorianCalendar());
    eid.getEventTypeCode()/*w  w  w .java  2s.  c o  m*/
            .add(ATNAUtil.buildCodedValueType("IHE Transactions", "ITI-18", "Registry Stored Query"));
    eid.setEventOutcomeIndicator(audit.getOutcome() ? BigInteger.ZERO : new BigInteger("4"));
    res.setEventIdentification(eid);

    res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(ATNAUtil.WSA_REPLYTO_ANON, "client", true,
            audit.getSourceIP(), (short) 2, "DCM", "110153", "Source"));
    res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(ATNAUtil.WSA_REPLYTO_ANON,
            ATNAUtil.getProcessID(), false, ATNAUtil.getHostIP(), (short) 2, "DCM", "110152", "Destination"));

    res.getAuditSourceIdentification().add(ATNAUtil.buildAuditSource("openhim"));

    // Max of 1 patient is allowed
    Identifier id = audit.getParticipantIdentifiers().get(0);
    if (id != null) {
        res.getParticipantObjectIdentification().add(ATNAUtil.buildParticipantObjectIdentificationType(
                id.toCX(), (short) 1, (short) 1, "RFC-3881", "2", "PatientNumber", null));
    }

    List<ATNAUtil.ParticipantObjectDetail> pod = new ArrayList<>();
    pod.add(new ATNAUtil.ParticipantObjectDetail("QueryEncoding", "UTF-8".getBytes()));
    if (audit.getHomeCommunityId() != null)
        pod.add(new ATNAUtil.ParticipantObjectDetail("urn:ihe:iti:xca:2010:homeCommunityId",
                audit.getHomeCommunityId().getBytes()));

    res.getParticipantObjectIdentification()
            .add(ATNAUtil.buildParticipantObjectIdentificationType(audit.getUniqueId(), (short) 2, (short) 24,
                    "IHE Transactions", "ITI-18", "Registry Stored Query", audit.getMessage(), pod));

    return ATNAUtil.marshallATNAObject(res);
}

From source file:Ternary.java

public BigInteger toBigInteger() {
    BigInteger toRet = BigInteger.ZERO;
    BigInteger curr;//w  w  w  .j  a v  a2s  .c o m
    for (int pos = 0; pos < trits.size(); pos++) {
        curr = (biThree.pow(pos)).multiply(BigInteger.valueOf(getTrit(pos).toInt()));
        toRet = toRet.add(curr);
    }

    return toRet;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {//w w  w . j av a 2  s  .com
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                connOut = conn.getOutputStream();
            }

            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields());
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.kinesis.datavis.utils.StreamUtils.java

/**
 * Split a shard by dividing the hash key space in half.
 *
 * @param streamName Name of the stream that contains the shard to split.
 * @param shardId The id of the shard to split.
 *
 * @throws IllegalArgumentException When either streamName or shardId are null or empty.
 * @throws LimitExceededException Shard limit for the account has been reached.
 * @throws ResourceNotFoundException The stream or shard cannot be found.
 * @throws InvalidArgumentException If the shard is closed and no eligible for splitting.
 * @throws AmazonClientException Error communicating with Amazon Kinesis.
 *
 *///from w  w w. j a  v a 2 s  .  c  om
public void splitShardEvenly(String streamName, String shardId) throws LimitExceededException,
        ResourceNotFoundException, AmazonClientException, InvalidArgumentException, IllegalArgumentException {
    if (streamName == null || streamName.isEmpty()) {
        throw new IllegalArgumentException("stream name is required");
    }
    if (shardId == null || shardId.isEmpty()) {
        throw new IllegalArgumentException("shard id is required");
    }

    DescribeStreamResult result = kinesis.describeStream(streamName);
    StreamDescription description = result.getStreamDescription();

    // Find the shard we want to split
    Shard shardToSplit = null;
    for (Shard shard : description.getShards()) {
        if (shardId.equals(shard.getShardId())) {
            shardToSplit = shard;
            break;
        }
    }

    if (shardToSplit == null) {
        throw new ResourceNotFoundException(
                "Could not find shard with id '" + shardId + "' in stream '" + streamName + "'");
    }

    // Check if the shard is still open. Open shards do not have an ending sequence number.
    if (shardToSplit.getSequenceNumberRange().getEndingSequenceNumber() != null) {
        throw new InvalidArgumentException("Shard is CLOSED and is not eligible for splitting");
    }

    // Calculate the median hash key to use as the new starting hash key for the shard.
    BigInteger startingHashKey = new BigInteger(shardToSplit.getHashKeyRange().getStartingHashKey());
    BigInteger endingHashKey = new BigInteger(shardToSplit.getHashKeyRange().getEndingHashKey());
    BigInteger[] medianHashKey = startingHashKey.add(endingHashKey).divideAndRemainder(new BigInteger("2"));
    BigInteger newStartingHashKey = medianHashKey[0];

    if (!BigInteger.ZERO.equals(medianHashKey[1])) {
        // In order to more evenly distributed the new hash key ranges across the new shards we will "round up" to
        // the next integer when our current hash key range is not evenly divisible by 2.
        newStartingHashKey = newStartingHashKey.add(BigInteger.ONE);
    }

    // Submit the split shard request
    kinesis.splitShard(streamName, shardId, newStartingHashKey.toString());
}

From source file:com.facebook.infrastructure.service.StorageService.java

public static BigInteger hash(String key) {
    BigInteger h = BigInteger.ZERO;
    char val[] = key.toCharArray();
    for (int i = 0; i < StorageService.maxKeyHashLength_; i++) {
        if (i < val.length)
            h = StorageService.prime_.multiply(h).add(BigInteger.valueOf(val[i]));
        else/*w w w.  java2  s  .co m*/
            h = StorageService.prime_.multiply(h).add(StorageService.prime_);
    }

    return h;
}