Example usage for java.math BigInteger valueOf

List of usage examples for java.math BigInteger valueOf

Introduction

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

Prototype

private static BigInteger valueOf(int val[]) 

Source Link

Document

Returns a BigInteger with the given two's complement representation.

Usage

From source file:com.xerox.amazonws.sqs.MessageQueue.java

/**
 * Attempts to retrieve a number of messages from the queue. If less than that are availble,
 * the max returned is the number of messages in the queue, but not necessarily all messages
 * in the queue will be returned. The queue default visibility timeout is used.
 *
 * @param numMessages the maximum number of messages to return
 * @return an array of message objects/*w w w  . ja  va  2 s .co m*/
 */
public Message[] receiveMessages(int numMessages) throws SQSException {
    return receiveMessages(BigInteger.valueOf(numMessages), ((BigInteger) (null)));
}

From source file:gedi.util.math.stat.distributions.OccupancyNumberDistribution.java

private static final BigInteger factorial(int b, int k) {
    if (b == 0 || k == 0)
        return BigInteger.ONE;
    BigInteger re = BigInteger.valueOf(b);
    for (int i = b - 1; i > b - k; i--)
        re = re.multiply(BigInteger.valueOf(i));
    return re;/*from ww  w.  j  a  v a  2  s .c o m*/
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsReadersTest.java

/**
 * Test the reader for the table mantis_user_table.
 *
 * @throws Exception// w w  w .j a v a 2  s  .  c o  m
 *          Technical Exception
 */
@Test
public void testProjectUsersReader() throws Exception {
    final AccountData[] expected = new AccountData[] {
            new AccountData(BigInteger.ONE, "user_1", "user_real_1", "toto1@foo.fr"),
            new AccountData(BigInteger.valueOf(2), "user_2", "user_real_2", "toto2@foo.fr") };

    Mockito.when(clientStub.mc_project_get_users("toto", "passwd", BigInteger.ONE, BigInteger.TEN))
            .thenReturn(expected);

    projectUsersReader.setClientStub(clientStub);

    for (int i = 0; i <= expected.length; i++) {
        final AccountData item = projectUsersReader.read();
        if (i < expected.length) {
            assertNotNull(item);
            assertEquals(expected[i].getId(), item.getId());
            assertEquals(expected[i].getName(), item.getName());
            assertEquals(expected[i].getReal_name(), item.getReal_name());
            assertEquals(expected[i].getEmail(), item.getEmail());
        } else {
            assertNull(item);
        }
    }
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private BigInteger getNextSerialNumber() {
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    synchronized (serials) {
        while (serials.contains(serial))
            serial = serial.add(BigInteger.ONE);
        serials.add(serial);/* ww w  . jav  a2s.c  o m*/
        return serial;
    }
}

From source file:co.rsk.mine.BlockToMineBuilder.java

private BlockHeader createHeader(Block newBlockParent, List<BlockHeader> uncles, List<Transaction> txs,
        Coin minimumGasPrice) {/*from   ww  w. jav a2  s . c o  m*/
    final byte[] unclesListHash = HashUtil.keccak256(BlockHeader.getUnclesEncodedEx(uncles));

    final long timestampSeconds = clock.calculateTimestampForChild(newBlockParent);

    // Set gas limit before executing block
    BigInteger minGasLimit = BigInteger.valueOf(miningConfig.getGasLimit().getMininimum());
    BigInteger targetGasLimit = BigInteger.valueOf(miningConfig.getGasLimit().getTarget());
    BigInteger parentGasLimit = new BigInteger(1, newBlockParent.getGasLimit());
    BigInteger gasUsed = BigInteger.valueOf(newBlockParent.getGasUsed());
    boolean forceLimit = miningConfig.getGasLimit().isTargetForced();
    BigInteger gasLimit = gasLimitCalculator.calculateBlockGasLimit(parentGasLimit, gasUsed, minGasLimit,
            targetGasLimit, forceLimit);

    final BlockHeader newHeader = new BlockHeader(newBlockParent.getHash().getBytes(), unclesListHash,
            miningConfig.getCoinbaseAddress().getBytes(), new Bloom().getData(), new byte[] { 1 },
            newBlockParent.getNumber() + 1, gasLimit.toByteArray(), 0, timestampSeconds, new byte[] {},
            new byte[] {}, new byte[] {}, new byte[] {}, minimumGasPrice.getBytes(),
            CollectionUtils.size(uncles));
    newHeader.setDifficulty(difficultyCalculator.calcDifficulty(newHeader, newBlockParent.getHeader()));
    newHeader.setTransactionsRoot(Block.getTxTrie(txs).getHash().getBytes());
    return newHeader;
}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

private X509Certificate createAgentCertificate(PublicKey publicKey, PrivateKey intermediatePrivateKey,
        PublicKey intermediatePublicKey, String hostname, Date startDate) throws Exception {

    X500NameBuilder issuerBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    issuerBuilder.addRDN(BCStyle.OU, INTERMEDIATE_CERT_OU);
    issuerBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL);
    X500Name issuerDn = issuerBuilder.build();

    X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    subjectBuilder.addRDN(BCStyle.OU, AGENT_CERT_OU);
    subjectBuilder.addRDN(BCStyle.CN, hostname);
    subjectBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL);
    X500Name subjectDn = subjectBuilder.build();

    X509CertificateGenerator.V3X509CertificateGenerator v3CertGen = new V3X509CertificateGenerator(startDate,
            issuerDn, subjectDn, publicKey, BigInteger.valueOf(3));

    // add the extensions
    v3CertGen.addSubjectKeyIdExtension(publicKey);
    v3CertGen.addAuthorityKeyIdExtension(intermediatePublicKey);

    X509Certificate cert = v3CertGen.generate(intermediatePrivateKey);

    Date now = new Date();
    cert.checkValidity(now);/*from  w  w  w.ja  v a2 s . co m*/
    cert.verify(intermediatePublicKey);

    PKCS12BagAttributeSetter.usingBagAttributeCarrier(cert).setFriendlyName("cruise-agent")
            .setLocalKeyId(publicKey);

    return cert;
}

From source file:com.stratio.ingestion.sink.cassandra.EventParserTest.java

@Test
public void shouldParsePrimitiveTypes() throws Exception {
    Object integer = EventParser.parseValue("1", DataType.Name.INT);
    assertThat(integer).isInstanceOf(Integer.class).isEqualTo(1);
    integer = EventParser.parseValue(Integer.toString(Integer.MAX_VALUE), DataType.Name.INT);
    assertThat(integer).isInstanceOf(Integer.class).isEqualTo(Integer.MAX_VALUE);
    integer = EventParser.parseValue(Integer.toString(Integer.MIN_VALUE), DataType.Name.INT);
    assertThat(integer).isInstanceOf(Integer.class).isEqualTo(Integer.MIN_VALUE);
    integer = EventParser.parseValue(" 1 2 ", DataType.Name.INT);
    assertThat(integer).isInstanceOf(Integer.class).isEqualTo(12);

    Object counter = EventParser.parseValue("1", DataType.Name.COUNTER);
    assertThat(counter).isEqualTo(1L);//from  ww w  . ja  v a2s  .  c o m
    counter = EventParser.parseValue(Long.toString(Long.MAX_VALUE), DataType.Name.COUNTER);
    assertThat(counter).isEqualTo(Long.MAX_VALUE);
    counter = EventParser.parseValue(Long.toString(Long.MIN_VALUE), DataType.Name.COUNTER);
    assertThat(counter).isEqualTo(Long.MIN_VALUE);
    counter = EventParser.parseValue(" 1 2 ", DataType.Name.COUNTER);
    assertThat(counter).isEqualTo(12L);

    Object _float = EventParser.parseValue("1", DataType.Name.FLOAT);
    assertThat(_float).isInstanceOf(Float.class).isEqualTo(1f);
    _float = EventParser.parseValue("1.0", DataType.Name.FLOAT);
    assertThat(_float).isInstanceOf(Float.class).isEqualTo(1f);
    _float = EventParser.parseValue(Float.toString(Float.MAX_VALUE), DataType.Name.FLOAT);
    assertThat(_float).isInstanceOf(Float.class).isEqualTo(Float.MAX_VALUE);
    _float = EventParser.parseValue(Float.toString(Float.MIN_VALUE), DataType.Name.FLOAT);
    assertThat(_float).isInstanceOf(Float.class).isEqualTo(Float.MIN_VALUE);
    _float = EventParser.parseValue(" 1 . 0 ", DataType.Name.FLOAT);
    assertThat(_float).isInstanceOf(Float.class).isEqualTo(1f);

    Object _double = EventParser.parseValue("1", DataType.Name.DOUBLE);
    assertThat(_double).isInstanceOf(Double.class).isEqualTo(1.0);
    _double = EventParser.parseValue("0", DataType.Name.DOUBLE);
    assertThat(_double).isInstanceOf(Double.class).isEqualTo(0.0);
    _double = EventParser.parseValue(Double.toString(Double.MAX_VALUE), DataType.Name.DOUBLE);
    assertThat(_double).isInstanceOf(Double.class).isEqualTo(Double.MAX_VALUE);
    _double = EventParser.parseValue(Double.toString(Double.MIN_VALUE), DataType.Name.DOUBLE);
    assertThat(_double).isInstanceOf(Double.class).isEqualTo(Double.MIN_VALUE);
    _double = EventParser.parseValue(" 1 . 0 ", DataType.Name.DOUBLE);
    assertThat(_double).isInstanceOf(Double.class).isEqualTo(1.0);

    for (DataType.Name type : Arrays.asList(DataType.Name.BIGINT)) {
        Object bigInteger = EventParser.parseValue("1", type);
        assertThat(bigInteger).isInstanceOf(Long.class).isEqualTo(1L);
        bigInteger = EventParser.parseValue("0", type);
        assertThat(bigInteger).isInstanceOf(Long.class).isEqualTo(0L);
        bigInteger = EventParser.parseValue(Long.toString(Long.MAX_VALUE), type);
        assertThat(bigInteger).isInstanceOf(Long.class).isEqualTo(Long.MAX_VALUE);
        bigInteger = EventParser.parseValue(Long.toString(Long.MIN_VALUE), type);
        assertThat(bigInteger).isInstanceOf(Long.class).isEqualTo(Long.MIN_VALUE);
    }

    for (DataType.Name type : Arrays.asList(DataType.Name.VARINT)) {
        Object bigInteger = EventParser.parseValue("1", type);
        assertThat(bigInteger).isInstanceOf(BigInteger.class).isEqualTo(BigInteger.ONE);
        bigInteger = EventParser.parseValue("0", type);
        assertThat(bigInteger).isInstanceOf(BigInteger.class).isEqualTo(BigInteger.ZERO);
        bigInteger = EventParser.parseValue(
                BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2L)).toString(), type);
        assertThat(bigInteger).isInstanceOf(BigInteger.class)
                .isEqualTo(BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2L)));
        bigInteger = EventParser.parseValue(
                BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(2L)).toString(), type);
        assertThat(bigInteger).isInstanceOf(BigInteger.class)
                .isEqualTo(BigInteger.valueOf(Long.MIN_VALUE).multiply(BigInteger.valueOf(2L)));
    }

    Object bigDecimal = EventParser.parseValue("1", DataType.Name.DECIMAL);
    assertThat(bigDecimal).isInstanceOf(BigDecimal.class).isEqualTo(BigDecimal.valueOf(1));
    bigDecimal = EventParser.parseValue("0", DataType.Name.DECIMAL);
    assertThat(bigDecimal).isInstanceOf(BigDecimal.class).isEqualTo(BigDecimal.valueOf(0));
    bigDecimal = EventParser.parseValue(
            BigDecimal.valueOf(Double.MAX_VALUE).multiply(BigDecimal.valueOf(2)).toString(),
            DataType.Name.DECIMAL);
    assertThat(bigDecimal).isInstanceOf(BigDecimal.class)
            .isEqualTo(BigDecimal.valueOf(Double.MAX_VALUE).multiply(BigDecimal.valueOf(2)));
    bigDecimal = EventParser.parseValue(
            BigDecimal.valueOf(Double.MIN_VALUE).multiply(BigDecimal.valueOf(2)).toString(),
            DataType.Name.DECIMAL);
    assertThat(bigDecimal).isInstanceOf(BigDecimal.class)
            .isEqualTo(BigDecimal.valueOf(Double.MIN_VALUE).multiply(BigDecimal.valueOf(2)));
    bigDecimal = EventParser.parseValue(" 1 2 ", DataType.Name.DECIMAL);
    assertThat(bigDecimal).isInstanceOf(BigDecimal.class).isEqualTo(BigDecimal.valueOf(12));

    Object string = EventParser.parseValue("string", DataType.Name.TEXT);
    assertThat(string).isInstanceOf(String.class).isEqualTo("string");

    Object bool = EventParser.parseValue("true", DataType.Name.BOOLEAN);
    assertThat(bool).isInstanceOf(Boolean.class).isEqualTo(true);

    Object addr = EventParser.parseValue("192.168.1.1", DataType.Name.INET);
    assertThat(addr).isInstanceOf(InetAddress.class).isEqualTo(InetAddress.getByName("192.168.1.1"));

    UUID randomUUID = UUID.randomUUID();
    Object uuid = EventParser.parseValue(randomUUID.toString(), DataType.Name.UUID);
    assertThat(uuid).isInstanceOf(UUID.class).isEqualTo(randomUUID);
}

From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java

public X509Certificate createClass1CaCert(KeyPair keyPair, PrivateKey ppk, X509Certificate caCert)
        throws Exception {

    X500Name idn = CertificateUtil.getSubject(caCert);
    BigInteger sno = BigInteger.valueOf(3);
    Date nb = new Date(System.currentTimeMillis() - HALF_DAY);
    Date na = new Date(nb.getTime() + TWENTY_YEAR);
    X500Name sdn = X500NameUtil.createClass1RootPrincipal();
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, sno, nb, na, sdn, pubKey);

    addSubjectKID(certBuilder, pubKey);/*from  www  .  ja va2  s  .com*/
    addAuthorityKID(certBuilder, caCert.getPublicKey());
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3));
    certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(BASE_EKU));

    X509Certificate certificate = signCert(certBuilder, ppk);
    certificate.checkValidity(new Date());
    certificate.verify(caCert.getPublicKey());

    setPKCS9Info(certificate);

    return certificate;
}

From source file:Peer.java

@Override
public String lookup(String word, Level logLevel) throws Exception {
    lg.log(Level.FINEST, "lookup Entry");

    // Get the hash for this word
    Key key = hasher.getHash(word);
    lg.log(Level.FINER, " Hashed word " + word + " has key " + key);

    // Get the max key value
    Key max = new Key(BigInteger.valueOf((int) Math.pow(2, hasher.getBitSize()))).pred();

    // If this peer knows the which peer that key belongs to ...
    if (/*from w  w w .ja  va  2 s .c o m*/
    // Normal ascending range
    pred == null || (key.compare(pred) > 0 && key.compare(nodeid) <= 0)
    // Modulor case
            || (pred.compare(nodeid) > 0 && (key.compare(pred) > 0 && key.compare(max) <= 0)
                    || (key.compare(nodeid) <= 0))) {
        lg.log(logLevel, "(lookup)Peer " + nodeid + " should have word " + word + " with key " + key);

        // Lookup keey 
        if (dict.get(word) != null) {
            lg.log(Level.FINEST, "lookup Exit");
            return dict.get(word);
        } else {
            lg.log(Level.FINEST, "lookup Exit");
            return "Meaning is not found";
        }
    }
    // ... else find next success through finger key.
    else {
        Key closestNode = ft.getClosestSuccessor(key);

        lg.log(logLevel, "(lookup)Peer " + nodeid + " should NOT have word " + word + " with key " + key
                + " ... calling insert on the best finger table match " + closestNode);
        PeerInterface peer = getPeer(closestNode);
        lg.log(Level.FINEST, "lookup Exit");
        return peer.lookup(word, logLevel);
    }
}

From source file:jp.aegif.nemaki.cmis.aspect.query.solr.SolrQueryProcessor.java

@Override
public ObjectList query(CallContext callContext, String repositoryId, String statement,
        Boolean searchAllVersions, Boolean includeAllowableActions, IncludeRelationships includeRelationships,
        String renditionFilter, BigInteger maxItems, BigInteger skipCount) {

    SolrServer solrServer = solrUtil.getSolrServer();

    // TODO walker is required?
    QueryUtilStrict util = new QueryUtilStrict(statement, new CmisTypeManager(repositoryId, typeManager), null);
    QueryObject queryObject = util.getQueryObject();

    // Get where caluse as Tree
    Tree whereTree = null;//from www. j ava2  s  .  c  o m
    try {
        util.processStatement();
        Tree tree = util.parseStatement();
        whereTree = extractWhereTree(tree);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Build solr statement of WHERE
    String whereQueryString = "";
    if (whereTree == null || whereTree.isNil()) {
        whereQueryString = "*:*";
    } else {
        try {
            SolrPredicateWalker solrPredicateWalker = new SolrPredicateWalker(repositoryId, queryObject,
                    solrUtil, contentService);
            Query whereQuery = solrPredicateWalker.walkPredicate(whereTree);
            whereQueryString = whereQuery.toString();
        } catch (Exception e) {
            e.printStackTrace();
            // TODO Output more detailed exception
            exceptionService.invalidArgument("Invalid CMIS SQL statement!");
        }
    }

    // Build solr query of FROM
    String fromQueryString = "";

    String repositoryQuery = "repository_id:" + repositoryId;

    fromQueryString += repositoryQuery + " AND ";

    TypeDefinition td = queryObject.getMainFromName();
    // includedInSupertypeQuery
    List<TypeDefinitionContainer> typeDescendants = typeManager.getTypesDescendants(repositoryId, td.getId(),
            BigInteger.valueOf(-1), false);
    Iterator<TypeDefinitionContainer> iterator = typeDescendants.iterator();
    List<String> tables = new ArrayList<String>();
    while (iterator.hasNext()) {
        TypeDefinition descendant = iterator.next().getTypeDefinition();
        if (td.getId() != descendant.getId()) {
            boolean isq = (descendant.isIncludedInSupertypeQuery() == null) ? false
                    : descendant.isIncludedInSupertypeQuery();
            if (!isq)
                continue;
        }
        String table = descendant.getQueryName();
        tables.add(table.replaceAll(":", "\\\\:"));
    }

    Term t = new Term(solrUtil.getPropertyNameInSolr(PropertyIds.OBJECT_TYPE_ID),
            StringUtils.join(tables, " "));
    fromQueryString += new TermQuery(t).toString();

    // Execute query
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery(whereQueryString);
    solrQuery.setFilterQueries(fromQueryString);

    //TEST
    solrQuery.set(CommonParams.START, 0);
    solrQuery.set(CommonParams.ROWS, maxItems.intValue());

    QueryResponse resp = null;
    try {
        resp = solrServer.query(solrQuery);
    } catch (SolrServerException e) {
        e.printStackTrace();
    }

    // Output search results to ObjectList
    if (resp != null && resp.getResults() != null && resp.getResults().getNumFound() != 0) {
        SolrDocumentList docs = resp.getResults();

        List<Content> contents = new ArrayList<Content>();
        for (SolrDocument doc : docs) {
            String docId = (String) doc.getFieldValue("object_id");
            Content c = contentService.getContent(repositoryId, docId);

            // When for some reason the content is missed, pass through
            if (c == null) {
                logger.warn("[objectId=" + docId + "]It is missed in DB but still rests in Solr.");
            } else {
                contents.add(c);
            }

        }

        List<Lock> locks = threadLockService.readLocks(repositoryId, contents);
        try {
            threadLockService.bulkLock(locks);

            // Filter out by permissions
            List<Content> permitted = permissionService.getFiltered(callContext, repositoryId, contents);

            // Filter return value with SELECT clause
            Map<String, String> requestedWithAliasKey = queryObject.getRequestedPropertiesByAlias();
            String filter = null;
            if (!requestedWithAliasKey.keySet().contains("*")) {
                // Create filter(queryNames) from query aliases
                filter = StringUtils.join(requestedWithAliasKey.values(), ",");
            }

            // Build ObjectList
            String orderBy = orderBy(queryObject);
            ObjectList result = compileService.compileObjectDataList(callContext, repositoryId, permitted,
                    filter, includeAllowableActions, includeRelationships, renditionFilter, false, maxItems,
                    skipCount, false, orderBy);

            return result;

        } finally {
            threadLockService.bulkUnlock(locks);
        }
    } else {
        ObjectListImpl nullList = new ObjectListImpl();
        nullList.setHasMoreItems(false);
        nullList.setNumItems(BigInteger.ZERO);
        return nullList;
    }
}