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:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

/**
 * Generates a self signed x509 certificate identified by the given
 * <code>userName</code> and the given <code>keyPair</code>.
 *
 * @param userName common name of {@link X500Principal} ("CN={userName}") used as
 *                 subjectDN and issuerDN.
 * @param keyPair  used for the certificate public and private key
 * @return self signed X509 certificate/* w w w  .j a v a 2  s. c  o m*/
 */
@SuppressWarnings("deprecation")
@Nonnull
public X509Certificate generateSelfSignedX509Certificate(@Nonnull String userName,
        @Nonnull java.security.KeyPair keyPair) {
    try {
        DateTime startDate = new DateTime().minusDays(1);
        DateTime expiryDate = new DateTime().plusYears(2);

        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal dnName = new X500Principal("CN=" + userName);

        certGen.setSubjectDN(dnName);
        // same as subject : self signed certificate
        certGen.setIssuerDN(dnName);
        certGen.setNotBefore(startDate.toDate());
        certGen.setNotAfter(expiryDate.toDate());
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

        return certGen.generate(keyPair.getPrivate(), BOUNCY_CASTLE_PROVIDER_NAME);

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this * value)}.
 *
 * @param value the value to be multiplied by this {@link Rational}.
 * @return The multiplication result.//from w  w  w. ja v  a 2s .c o  m
 */
@Nonnull
public Rational multiply(long value) {
    return multiply(BigInteger.valueOf(value));
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

protected long _reorganizeSpace(Connection con, SequencerEngine seq, FxTreeMode sourceMode, FxTreeMode destMode,
        long nodeId, boolean includeNodeId, BigInteger overrideSpacing, BigInteger overrideLeft,
        FxTreeNodeInfo insertParent, int insertPosition, BigInteger insertSpace, BigInteger insertBoundaries[],
        int depthDelta, Long destinationNode, boolean createMode, boolean createKeepIds,
        boolean disableSpaceOptimization) throws FxTreeException {
    long firstCreatedNodeId = -1;
    FxTreeNodeInfoSpreaded nodeInfo;/*from   ww w .  j  a v a2 s .  c o  m*/
    try {
        nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, sourceMode, nodeId);
    } catch (Exception e) {
        return -1;
    }

    if (!nodeInfo.isSpaceOptimizable() && !disableSpaceOptimization) {
        // The Root node and cant be optimize any more ... so all we can do is fail :-/
        // This should never really happen
        if (nodeId == ROOT_NODE) {
            return -1;
        }
        //System.out.println("### UP we go, depthDelta=" + depthDelta);
        return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                depthDelta, destinationNode, createMode, createKeepIds, false);
    }

    BigInteger spacing = nodeInfo.getDefaultSpacing();
    if (overrideSpacing != null && (overrideSpacing.compareTo(spacing) < 0 || overrideLeft != null)) {
        // override spacing unless it is greater OR overrideLeft is specified (in that case we
        // have to use the spacing for valid tree ranges)  
        spacing = overrideSpacing;
    } else {
        if (spacing.compareTo(GO_UP) < 0 && !createMode && !disableSpaceOptimization) {
            return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                    overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                    depthDelta, destinationNode, createMode, createKeepIds, false);
        }
    }

    if (insertBoundaries != null && insertPosition == -1) {
        insertPosition = 0; // insertPosition cannot be negative
    }

    Statement stmt = null;
    PreparedStatement ps = null;
    ResultSet rs;
    BigInteger left = overrideLeft == null ? nodeInfo.getLeft() : overrideLeft;
    BigInteger right = null;
    String includeNode = includeNodeId ? "=" : "";
    long counter = 0;
    long newId = -1;
    try {
        final long start = System.currentTimeMillis();
        String createProps = createMode ? ",PARENT,REF,NAME,TEMPLATE" : "";
        String sql = " SELECT ID," + StorageManager.getIfFunction( // compute total child count only when the node has children
                "CHILDCOUNT = 0", "0",
                "(SELECT COUNT(*) FROM " + getTable(sourceMode) + " WHERE LFT > NODE.LFT AND RGT < NODE.RGT)") +
        // 3           4             5   6
                ", CHILDCOUNT, LFT AS LFTORD,RGT,DEPTH" + createProps
                + " FROM (SELECT ID,CHILDCOUNT,LFT,RGT,DEPTH" + createProps + " FROM " + getTable(sourceMode)
                + " WHERE " + "LFT>" + includeNode + nodeInfo.getLeft() + " AND LFT<" + includeNode
                + nodeInfo.getRight() + ") NODE " + "ORDER BY LFTORD ASC";
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        if (createMode) {
            //                                                                 1  2      3     4     5   6        7   8
            ps = con.prepareStatement(
                    "INSERT INTO " + getTable(destMode) + " (ID,PARENT,DEPTH,DIRTY,REF,TEMPLATE,LFT,RGT," +
                    //9           10    11
                            "CHILDCOUNT,NAME,MODIFIED_AT) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?)");
        } else {
            ps = con.prepareStatement("UPDATE " + getTable(sourceMode) + " SET LFT=?,RGT=?,DEPTH=? WHERE ID=?");
        }
        long id;
        int total_childs;
        int direct_childs;
        BigInteger nextLeft;
        int lastDepth = nodeInfo.getDepth() + (includeNodeId ? 0 : 1);
        int depth;
        BigInteger _rgt;
        BigInteger _lft;
        Long ref = null;
        String data = null;
        String name = "";

        Stack<Long> currentParent = null;
        if (createMode) {
            currentParent = new Stack<Long>();
            currentParent.push(destinationNode);
        }

        //System.out.println("Spacing:"+SPACING);
        while (rs.next()) {
            //System.out.println("------------------");
            id = rs.getLong(1);
            total_childs = rs.getInt(2);
            direct_childs = rs.getInt(3);
            _lft = getNodeBounds(rs, 4);
            _rgt = getNodeBounds(rs, 5);
            depth = rs.getInt(6);
            if (createMode) {
                // Reading these properties is slow, only do it when needed
                ref = rs.getLong(8);
                if (rs.wasNull())
                    ref = null;
                name = rs.getString(9);
                data = rs.getString(10);
                if (rs.wasNull())
                    data = null;
            }
            left = left.add(spacing).add(BigInteger.ONE);

            // Handle depth differences
            if (lastDepth - depth > 0) {
                BigInteger depthDifference = spacing.add(BigInteger.ONE);
                left = left.add(depthDifference.multiply(BigInteger.valueOf(lastDepth - depth)));
            }
            if (createMode) {
                if (lastDepth < depth) {
                    currentParent.push(newId);
                } else if (lastDepth > depth) {
                    for (int p = 0; p < (lastDepth - depth); p++)
                        currentParent.pop();
                }
            }

            right = left.add(spacing).add(BigInteger.ONE);

            // add child space if needed
            if (total_childs > 0) {
                BigInteger childSpace = spacing.multiply(BigInteger.valueOf(total_childs * 2));
                childSpace = childSpace.add(BigInteger.valueOf((total_childs * 2) - 1));
                right = right.add(childSpace);
                nextLeft = left;
            } else {
                nextLeft = right;
            }

            if (insertBoundaries != null) {
                // insert gap at requested position
                // If we're past the gap, keep adding the insert space to left/right because the added
                // space is never "injected" into the loop, i.e. without adding it the left/right boundaries of
                // nodes after the gap would be too far to the left.
                if (_lft.compareTo(insertBoundaries[0]) > 0) {
                    left = left.add(insertSpace);
                }
                if (_rgt.compareTo(insertBoundaries[0]) > 0) {
                    right = right.add(insertSpace);
                }
            }

            // sanity checks
            if (left.compareTo(right) >= 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "left greater than right");
            }
            if (insertParent != null && right.compareTo((BigInteger) insertParent.getRight()) > 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "wrote past parent node bounds");
            }

            // Update the node
            if (createMode) {
                newId = createKeepIds ? id : seq.getId(destMode.getSequencer());
                if (firstCreatedNodeId == -1)
                    firstCreatedNodeId = newId;

                // Create the main entry
                ps.setLong(1, newId);
                ps.setLong(2, currentParent.peek());
                ps.setLong(3, depth + depthDelta);
                ps.setBoolean(4, destMode != FxTreeMode.Live); //only flag non-live tree's dirty
                if (ref == null) {
                    ps.setNull(5, java.sql.Types.NUMERIC);
                } else {
                    ps.setLong(5, ref);
                }
                if (data == null) {
                    ps.setNull(6, java.sql.Types.VARCHAR);
                } else {
                    ps.setString(6, data);
                }
                //                    System.out.println("=> id:"+newId+" left:"+left+" right:"+right);
                setNodeBounds(ps, 7, left);
                setNodeBounds(ps, 8, right);
                ps.setInt(9, direct_childs);
                ps.setString(10, name);
                ps.setLong(11, System.currentTimeMillis());
                ps.addBatch();
            } else {
                setNodeBounds(ps, 1, left);
                setNodeBounds(ps, 2, right);
                ps.setInt(3, depth + depthDelta);
                ps.setLong(4, id);
                ps.addBatch();
                //                    ps.executeBatch();
                //                    ps.clearBatch();
            }

            // Prepare variables for the next node
            left = nextLeft;
            lastDepth = depth;
            counter++;

            // Execute batch every 10000 items to avoid out of memory
            if (counter % 10000 == 0) {
                ps.executeBatch();
                ps.clearBatch();
            }
        }
        rs.close();
        stmt.close();
        stmt = null;
        ps.executeBatch();

        if (LOG.isDebugEnabled()) {
            final long time = System.currentTimeMillis() - start;

            LOG.debug("Tree reorganization of " + counter + " items completed in " + time + " ms (spaceLen="
                    + spacing + ")");
        }
        return firstCreatedNodeId;
    } catch (FxApplicationException e) {
        throw e instanceof FxTreeException ? (FxTreeException) e : new FxTreeException(e);
    } catch (SQLException e) {
        String next = "";
        if (e.getNextException() != null)
            next = " next:" + e.getNextException().getMessage();
        if (StorageManager.isDuplicateKeyViolation(e))
            throw new FxTreeException(LOG, e, "ex.tree.reorganize.duplicateKey");
        throw new FxTreeException(LOG, e, "ex.tree.reorganize.failed", counter, left, right,
                e.getMessage() + next);
    } catch (Exception e) {
        throw new FxTreeException(e);
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (Throwable t) {
            /*ignore*/}
        try {
            if (ps != null)
                ps.close();
        } catch (Throwable t) {
            /*ignore*/}
    }
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.EntityGraphJGraphT.java

/**
 * Computes and sets the diameter, the average degree and the average shortest path length of
 * the graph. Do not call this in the constructor. May run a while. It is called in the getters,
 * if parameters are not yet initialized when retrieved.
 *///w w  w. j  a v a  2  s  .  co  m
private void setGraphParameters() {

    logger.info("Setting graph parameters.");
    // The directed graph is treated as an undirected graph to compute these parameters.
    // UndirectedGraph<String, DefaultEdge> undirectedGraph = new AsUndirectedGraph<String,
    // DefaultEdge>(directedGraph);
    logger.info("Treating the graph as undirected.");

    // Diameter is the maximum of all shortest path lengths
    // Average shortest path length is (as the name says) the average of the shortest path
    // length between all node pairs

    BigInteger bigMaxPathLength = BigInteger.valueOf(0);
    BigInteger bigShortestPathLengthSum = BigInteger.valueOf(0);
    double degreeSum = 0.0;
    double clusterCoefficientSum = 0.0;

    // iterate over all node pairs
    Set<Entity> nodes = undirectedGraph.vertexSet();

    // a hashset of the nodes which have been the start node of the computation process
    // for such nodes all path lengths have been already computed
    Set<Entity> wasSource = new HashSet<Entity>();

    int progress = 0;
    double percent = 0.0;
    for (Entity node : nodes) {

        progress++;
        percent = (double) progress / nodes.size() * 100;

        if (percent % 10 == 0) {
            logger.info("Progress: " + percent);
        }
        LoggingUtils.printProgressInfo(progress, nodes.size(), 100, LoggingUtils.ProgressInfoMode.TEXT,
                "Getting graph parameters");

        int nodeDegree = undirectedGraph.degreeOf(node);
        degreeSum += nodeDegree;

        // logger.info("Updating degree distribution.");
        updateDegreeDistribution(nodeDegree);

        // cluster coefficient C_v of a node v is the fraction of the connections that exist
        // between the
        // neighbor nodes (k_v) of this node and all allowable connections between the neighbors
        // (k_v(k_v -1)/2)
        // for degrees 0 or 1 there is no cluster coefficient, as there can be no connections
        // between neighbors
        if (nodeDegree > 1) {
            double numberOfNeighborConnections = getNumberOfNeighborConnections(node);
            clusterCoefficientSum += (numberOfNeighborConnections / (nodeDegree * (nodeDegree - 1)));
        }

        // Returns the new shortestPathLengthSum and the new maxPathLength.
        // They are returned as an double array for performance reasons.
        // I do not want to create an object, as this function is called *very* often
        // logger.info("Computing shortest path lengths.");
        BigInteger[] returnValues = computeShortestPathLengths(node, bigShortestPathLengthSum, bigMaxPathLength,
                wasSource);
        bigShortestPathLengthSum = returnValues[0];
        bigMaxPathLength = returnValues[1];

        // save the info that the node was already used as the source of path computation
        wasSource.add(node);
    }

    if (nodes.size() > 1) {
        long denominator = nodes.size() * (nodes.size() - 1) / 2;
        this.averageShortestPathLength = bigShortestPathLengthSum.divide(BigInteger.valueOf(denominator))
                .doubleValue();
        // sum of path lengths / (number of node pairs)
    } else {
        this.averageShortestPathLength = 0; // there is only one node
    }
    this.diameter = bigMaxPathLength.doubleValue();
    this.clusterCoefficient = clusterCoefficientSum / nodes.size();
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransactionTest.java

@Test
public void testTransactionWriteWriteConflicts() throws Exception {
    // This test creates various types of conflicting writes and makes sure that write-write
    // conflicts are thrown when necessary, and not thrown when there actually isn't a conflict.
    Cell row1Column1 = Cell.create("row1".getBytes(), "column1".getBytes());
    Cell row1Column2 = Cell.create("row1".getBytes(), "column2".getBytes());
    Cell row2Column1 = Cell.create("row2".getBytes(), "column1".getBytes());

    // First transaction commits first, second tries to commit same write
    Transaction t1 = txManager.createNewTransaction();
    Transaction t2 = txManager.createNewTransaction();
    t1.put(TABLE1, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t2.put(TABLE1, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t1.commit();//w w  w  .ja va 2  s . c o  m
    try {
        t2.commit();
        assertTrue(false);
    } catch (TransactionConflictException e) {
        // We expect to catch this exception
    }

    // Second transaction commits first, first tries to commit same write
    t1 = txManager.createNewTransaction();
    t2 = txManager.createNewTransaction();
    t1.put(TABLE1, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t2.put(TABLE1, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t2.commit();
    try {
        t1.commit();
        assertTrue(false);
    } catch (TransactionConflictException e) {
        // We expect to catch this exception
    }

    // Transactions committing to different rows
    t1 = txManager.createNewTransaction();
    t2 = txManager.createNewTransaction();
    t1.put(TABLE1, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t2.put(TABLE1, ImmutableMap.of(row2Column1, BigInteger.valueOf(1).toByteArray()));
    t1.commit();
    t2.commit();

    // Transactions committing to different tables
    t1 = txManager.createNewTransaction();
    t2 = txManager.createNewTransaction();
    t1.put(TABLE1, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t2.put(TABLE2, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t1.commit();
    t2.commit();

    // Transactions committing to different columns in the same row
    t1 = txManager.createNewTransaction();
    t2 = txManager.createNewTransaction();
    t1.put(TABLE1, ImmutableMap.of(row1Column1, BigInteger.valueOf(1).toByteArray()));
    t2.put(TABLE1, ImmutableMap.of(row1Column2, BigInteger.valueOf(1).toByteArray()));
    t1.commit();
    t2.commit();
}

From source file:jp.aegif.nemaki.cmis.aspect.impl.ExceptionServiceImpl.java

private void constraintIntegerPropertyValue(PropertyDefinition<?> definition, PropertyData<?> propertyData,
        String objectId) {//w w  w  . jav a2  s  .  c o  m
    final String msg = "AN INTEGER property violates the range constraints";
    BigInteger val = BigInteger.valueOf((Long) propertyData.getFirstValue());

    BigInteger min = ((PropertyIntegerDefinition) definition).getMinValue();
    if (min != null && min.compareTo(val) > 0) {
        constraint(objectId, msg);
    }

    BigInteger max = ((PropertyIntegerDefinition) definition).getMinValue();
    if (max != null && max.compareTo(val) < 0) {
        constraint(objectId, msg);
    }
}

From source file:com.google.bitcoin.core.Block.java

/**
 * Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the
 * target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception
 * is thrown./*from   ww w  .  j  a va 2s.co  m*/
 */
public BigInteger getDifficultyTargetAsInteger() throws VerificationException {
    maybeParseHeader();
    BigInteger target = Utils.decodeCompactBits(difficultyTarget);
    if (target.compareTo(BigInteger.valueOf(0)) <= 0 || target.compareTo(params.proofOfWorkLimit) > 0)
        throw new VerificationException("Difficulty target is bad: " + target.toString());
    return target;
}

From source file:piuk.MyRemoteWallet.java

public static List<MyTransactionOutPoint> getUnspentOutputPoints(String[] from, int min_confirmations,
        int limit) throws Exception {

    String rootURL = "unspent";

    StringBuffer params = new StringBuffer(
            "limit=" + limit + "&confirmations=" + min_confirmations + "&active=");

    int ii = 0;/*ww  w . ja va  2  s . c  o  m*/
    for (String address : from) {
        params.append(address);

        if (ii < from.length - 1)
            params.append("|");

        ++ii;
    }

    List<MyTransactionOutPoint> outputs = new ArrayList<>();

    String response = postAPI(rootURL, params.toString());

    Map<String, Object> root = (Map<String, Object>) JSONValue.parse(response);

    List<Map<String, Object>> outputsRoot = (List<Map<String, Object>>) root.get("unspent_outputs");

    for (Map<String, Object> outDict : outputsRoot) {

        byte[] hashBytes = Hex.decode((String) outDict.get("tx_hash"));

        ArrayUtils.reverse(hashBytes);

        Sha256Hash txHash = new Sha256Hash(hashBytes);

        int txOutputN = ((Number) outDict.get("tx_output_n")).intValue();
        BigInteger value = BigInteger.valueOf(((Number) outDict.get("value")).longValue());
        byte[] scriptBytes = Hex.decode((String) outDict.get("script"));
        int confirmations = ((Number) outDict.get("confirmations")).intValue();

        //Contrstuct the output
        MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes);

        outPoint.setConfirmations(confirmations);

        outputs.add(outPoint);
    }

    return outputs;
}

From source file:co.rsk.peg.BridgeSerializationUtilsTest.java

@Test
public void deserializeOneOffLockWhitelistAndDisableBlockHeight() throws Exception {
    PowerMockito.mockStatic(RLP.class);
    mock_RLP_decode2(InnerListMode.NONE);

    byte[][] addressesBytes = Arrays.asList(100, 200, 300, 400).stream()
            .map(k -> BtcECKey.fromPrivate(BigInteger.valueOf(k))).sorted(BtcECKey.PUBKEY_COMPARATOR)
            .map(k -> k.getPubKeyHash()).toArray(byte[][]::new);

    StringBuilder sampleBuilder = new StringBuilder();
    sampleBuilder.append("09140314031403140302"); // 9 elements: 8 of 20 bytes (0x14 bytes) and 3 bytes interleaved plus one more element of 2 bytes
    for (int i = 0; i < addressesBytes.length; i++) {
        sampleBuilder.append(Hex.toHexString(addressesBytes[i]));
        sampleBuilder.append("0186a0"); // Coin.MILLICOIN
    }/*from  w  w  w.  java  2  s .  c o  m*/
    sampleBuilder.append("002a");
    byte[] sample = Hex.decode(sampleBuilder.toString());

    Pair<HashMap<Address, OneOffWhiteListEntry>, Integer> deserializedLockWhitelist = BridgeSerializationUtils
            .deserializeOneOffLockWhitelistAndDisableBlockHeight(sample,
                    NetworkParameters.fromID(NetworkParameters.ID_REGTEST));

    Assert.assertThat(deserializedLockWhitelist.getLeft().size(), is(addressesBytes.length));
    Assert.assertThat(deserializedLockWhitelist.getLeft().keySet().stream().map(Address::getHash160)
            .collect(Collectors.toList()), containsInAnyOrder(addressesBytes));
    Set<Coin> deserializedCoins = deserializedLockWhitelist.getLeft().values().stream()
            .map(entry -> ((OneOffWhiteListEntry) entry).maxTransferValue()).collect(Collectors.toSet());
    Assert.assertThat(deserializedCoins, hasSize(1));
    Assert.assertThat(deserializedCoins, hasItem(Coin.MILLICOIN));
    Assert.assertThat(deserializedLockWhitelist.getRight(), is(42));
}

From source file:jp.aegif.nemaki.cmis.aspect.impl.ExceptionServiceImpl.java

private void constraintStringPropertyValue(PropertyDefinition<?> definition, PropertyData<?> propertyData,
        String objectId) {/*  www .  j a v  a 2s  .c  o m*/
    final String msg = "An STRING property violates the length constraints";
    if (!(propertyData instanceof PropertyString))
        return;
    String val = ((PropertyString) propertyData).getFirstValue();
    if (StringUtils.isEmpty(val))
        return;
    BigInteger length = BigInteger.valueOf(val.length());
    BigInteger max = ((PropertyStringDefinition) definition).getMaxLength();
    if (max != null && max.compareTo(length) < 0) {
        constraint(objectId, msg);
    }
}