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:it.cnr.icar.eric.server.query.CompressContentQueryFilterPlugin.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected List executeQuery(ServerRequestContext context, String queryId, Map queryParams) throws Exception {
    List<?> res = null;//w w  w  . j  a v a 2 s .c  o  m
    AdhocQueryRequest req = BindingUtility.getInstance().createAdhocQueryRequest("SELECT * FROM DummyTable");
    int startIndex = 0;
    int maxResults = -1;
    req.setStartIndex(BigInteger.valueOf(startIndex));
    req.setMaxResults(BigInteger.valueOf(maxResults));

    HashMap<String, String> slotsMap = new HashMap<String, String>();
    slotsMap.put(BindingUtility.CANONICAL_SLOT_QUERY_ID, queryId);
    if ((queryParams != null) && (queryParams.size() > 0)) {
        slotsMap.putAll(queryParams);
    }
    BindingUtility.getInstance().addSlotsToRequest(req, slotsMap);

    //Now execute the query
    HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>();
    context.setRepositoryItemsMap(idToRepositoryItemMap);

    boolean requestOk = false;
    try {
        context.pushRegistryRequest(req);
        AdhocQueryResponse ebAdhocQueryResponse = QueryManagerFactory.getInstance().getQueryManager()
                .submitAdhocQuery(context);
        bu.checkRegistryResponse(ebAdhocQueryResponse);
        res = ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable();
        requestOk = true;
    } finally {
        context.popRegistryRequest();
        closeContext(context, requestOk);
    }
    return res;
}

From source file:dap4.dap4.Dap4Print.java

protected String valueString(Object value, DapType basetype) throws DataException {
    if (value == null)
        return "null";
    AtomicType atype = basetype.getAtomicType();
    boolean unsigned = atype.isUnsigned();
    switch (atype) {
    case Int8:/*from w ww .j  a v  a2 s  .com*/
    case UInt8:
        long lvalue = ((Byte) value).longValue();
        if (unsigned)
            lvalue &= 0xFFL;
        return String.format("%d", lvalue);
    case Int16:
    case UInt16:
        lvalue = ((Short) value).longValue();
        if (unsigned)
            lvalue &= 0xFFFFL;
        return String.format("%d", lvalue);
    case Int32:
    case UInt32:
        lvalue = ((Integer) value).longValue();
        if (unsigned)
            lvalue &= 0xFFFFFFFFL;
        return String.format("%d", lvalue);
    case Int64:
    case UInt64:
        lvalue = ((Long) value).longValue();
        if (unsigned) {
            BigInteger b = BigInteger.valueOf(lvalue);
            b = b.and(DapUtil.BIG_UMASK64);
            return b.toString();
        } else
            return String.format("%d", lvalue);
    case Float32:
        return String.format("%f", ((Float) value).floatValue());
    case Float64:
        return String.format("%f", ((Double) value).doubleValue());
    case Char:
        return "'" + ((Character) value).toString() + "'";
    case String:
    case URL:
        return "\"" + ((String) value) + "\"";
    case Opaque:
        ByteBuffer opaque = (ByteBuffer) value;
        String s = "0x";
        for (int i = 0; i < opaque.limit(); i++) {
            byte b = opaque.get(i);
            char c = hexchar((b >> 4) & 0xF);
            s += c;
            c = hexchar((b) & 0xF);
            s += c;
        }
        return s;
    case Enum:
        return valueString(value, ((DapEnum) basetype).getBaseType());
    default:
        break;
    }
    throw new DataException("Unknown type: " + basetype);
}

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

@Test
public void testTransactionIsolation() throws Exception {
    // This test creates multiple partially-done transactions and ensures that even after writes
    // and commits, the value returned by get() is consistent with either the initial value or
    // the most recently written value within the transaction.
    int numColumns = 10;
    int numTransactions = 500;

    Transaction initTransaction = txManager.createNewTransaction();
    for (int i = 0; i < numColumns; i++) {
        Cell cell = Cell.create("row".getBytes(), ("column" + i).getBytes());
        BigInteger cellValue = BigInteger.valueOf(i);
        initTransaction.put(TABLE, ImmutableMap.of(cell, cellValue.toByteArray()));
    }//from   w  w w . j  a v  a2  s.c  o m
    initTransaction.commit();

    List<Transaction> allTransactions = Lists.newArrayList();
    List<List<BigInteger>> writtenValues = Lists.newArrayList();
    for (int i = 0; i < numTransactions; i++) {
        allTransactions.add(txManager.createNewTransaction());
        List<BigInteger> initialValues = Lists.newArrayList();
        for (int j = 0; j < numColumns; j++) {
            initialValues.add(BigInteger.valueOf(j));
        }
        writtenValues.add(initialValues);
    }

    Random random = new Random(1);
    for (int i = 0; i < 10000 && !allTransactions.isEmpty(); i++) {
        int transactionIndex = random.nextInt(allTransactions.size());
        Transaction t = allTransactions.get(transactionIndex);

        int actionCode = random.nextInt(30);

        if (actionCode == 0) {
            // Commit the transaction and remove it.
            try {
                t.commit();
            } catch (TransactionConflictException e) {
                // Ignore any conflicts; the transaction just fails
            }
            allTransactions.remove(transactionIndex);
            writtenValues.remove(transactionIndex);
        } else if (actionCode < 15) {
            // Write a new value to a random column
            int columnNumber = random.nextInt(numColumns);
            Cell cell = Cell.create("row".getBytes(), ("column" + columnNumber).getBytes());

            BigInteger newValue = BigInteger.valueOf(random.nextInt(100000));
            t.put(TABLE, ImmutableMap.of(cell, newValue.toByteArray()));
            writtenValues.get(transactionIndex).set(columnNumber, newValue);
        } else {
            // Read and verify the value of a random column
            int columnNumber = random.nextInt(numColumns);
            Cell cell = Cell.create("row".getBytes(), ("column" + columnNumber).getBytes());
            byte[] storedValue = t.get(TABLE, Collections.singleton(cell)).get(cell);
            BigInteger expectedValue = writtenValues.get(transactionIndex).get(columnNumber);
            assertEquals(expectedValue, new BigInteger(storedValue));
        }
    }
}

From source file:piuk.MyRemoteWallet.java

public Pair<Transaction, Long> makeTransaction(KeyBag keyWallet, List<MyTransactionOutPoint> unspent,
        String toAddress, String changeAddress, BigInteger amount, BigInteger baseFee,
        boolean consumeAllOutputs) throws Exception {

    long priority = 0;

    if (unspent == null || unspent.size() == 0)
        throw new InsufficientFundsException("No free outputs to spend.");

    if (amount == null || amount.compareTo(BigInteger.ZERO) <= 0)
        throw new Exception("You must provide an amount");

    //Construct a new transaction
    Transaction tx = new Transaction(params);

    final Script toOutputScript = ScriptBuilder.createOutputScript(new Address(MainNetParams.get(), toAddress));

    final TransactionOutput output = new TransactionOutput(params, null, Coin.valueOf(amount.longValue()),
            toOutputScript.getProgram());

    tx.addOutput(output);/*from   www  . j  a v a2 s . com*/

    //Now select the appropriate inputs
    BigInteger valueSelected = BigInteger.ZERO;
    BigInteger valueNeeded = amount.add(baseFee);
    BigInteger minFreeOutputSize = BigInteger.valueOf(1000000);

    for (MyTransactionOutPoint outPoint : unspent) {

        Script scriptPubKey = outPoint.getConnectedOutput().getScriptPubKey();

        if (scriptPubKey == null) {
            throw new Exception("scriptPubKey is null");
        }

        final ECKey key = keyWallet.findKeyFromPubHash(scriptPubKey.getPubKeyHash());

        if (key == null) {
            throw new Exception("Unable to find ECKey for scriptPubKey " + scriptPubKey);
        }

        MyTransactionInput input = new MyTransactionInput(params, null, new byte[0], outPoint);

        tx.addInput(input);

        input.setScriptSig(scriptPubKey.createEmptyInputScript(key, null));

        valueSelected = valueSelected.add(BigInteger.valueOf(outPoint.getValue().longValue()));

        priority += outPoint.getValue().longValue() * outPoint.confirmations;

        if (!consumeAllOutputs) {
            if (valueSelected.compareTo(valueNeeded) == 0
                    || valueSelected.compareTo(valueNeeded.add(minFreeOutputSize)) >= 0)
                break;
        }
    }

    //Check the amount we have selected is greater than the amount we need
    if (valueSelected.compareTo(valueNeeded) < 0) {
        throw new InsufficientFundsException("Insufficient Funds");
    }

    long estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    BigInteger fee = BigInteger.valueOf((int) Math.ceil(estimatedSize / 1000d)).multiply(baseFee);

    BigInteger change = valueSelected.subtract(amount).subtract(fee);

    if (change.compareTo(BigInteger.ZERO) < 0) {
        throw new Exception("Insufficient Value for Fee. Fix this lazy.");
    } else if (change.compareTo(BigInteger.ZERO) > 0) {
        //Now add the change if there is any
        final Script change_script = ScriptBuilder
                .createOutputScript(new Address(MainNetParams.get(), changeAddress));

        TransactionOutput change_output = new TransactionOutput(params, null, Coin.valueOf(change.longValue()),
                change_script.getProgram());

        tx.addOutput(change_output);
    }

    estimatedSize = tx.bitcoinSerialize().length + (138 * tx.getInputs().size());

    priority /= estimatedSize;

    return new Pair<Transaction, Long>(tx, priority);
}

From source file:info.estebanluengo.alfrescoAPI.AlfrescoAPI.java

/**
 * Updates the document that exits in the server and creates a new version. The method allows to update the content of the document, 
 * the mimetype and the properties.<br>
 * In some circunstances a CmisStorageException could be thrown with the message "Expected x bytes but retrieved 0 bytes!". I Think
 * this is an issue in Alfresco Server and it can be resolved catching the exception and calling this method another time.<br> 
 * <a href="https://issues.alfresco.com/jira/browse/ACE-2821">Link to the issue</a>
 * //  w  ww . j a  va  2  s. co m
 * @param session a Session object that is connected with the server
 * @param doc a Document object to be updated.
 * @param newContent a byte[] with the content of the document. It can not be null.
 * @param mimeType a String that represent the mime type of the document
 * @param docProps a Map object with the properties of the document. It can be null
 * @param majorVersion a boolean. true indicates that we want a major version and false a minor version.
 * @param checkinComment a String with the comments that are associated to the new version
 * 
 * @return a Document that contains the new version created or null if it was not possible to make a new version.
 * Remember that every version of the document may has its own ID depending of the server. Alfresco uses alfhanumeric plus ;version
 */
public static Document updateDocument(Session session, Document doc, byte[] newContent, String mimeType,
        Map<String, Object> docProps, boolean majorVersion, String checkinComment) {
    logger.debug("updateDocument called for docId:" + doc.getId() + " length:" + newContent.length);
    Document updatedDocument = null;
    if (doc.getAllowableActions().getAllowableActions()
            .contains(org.apache.chemistry.opencmis.commons.enums.Action.CAN_CHECK_OUT)) {
        doc.refresh();
        //make a checkout is mandatory for some repositories. 
        ObjectId checkedOutDocument = doc.checkOut();
        Document pwc = (Document) session.getObject(checkedOutDocument);
        ByteArrayInputStream in = new ByteArrayInputStream(newContent);
        ObjectId objectId;
        try {
            ContentStream contentStream = new ContentStreamImpl(doc.getName(),
                    BigInteger.valueOf(newContent.length), mimeType, in);
            objectId = pwc.checkIn(majorVersion, docProps, contentStream, checkinComment);
        } catch (CmisStorageException e) {
            logger.error("Error trying to make a checkIn", e);
            pwc.delete();
            return null;
        }
        updatedDocument = (Document) session.getObject(objectId);
    }
    return updatedDocument;
}

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

/**
 * Computes the shortest path from node to all other nodes. Paths to nodes that have already
 * been the source of the shortest path computation are omitted (the path was already added to
 * the path sum). Updates the sum of shortest path lengths and the diameter of the graph. As the
 * JGraphT BreadthFirstIterator does not provide information about the distance to the start
 * node in each step, we will use our own BFS implementation.
 *
 * @param pStartNode//from  www .  jav a 2 s.c o  m
 *            The start node of the search.
 * @param pShortestPathLengthSum
 *            The sum of the shortest path lengths.
 * @param pMaxPathLength
 *            The maximum path length found so far.
 * @param pWasSource
 *            A set of nodes which have been the start node of the computation process. For such
 *            nodes all path lengths have been already computed.
 * @return An array of double values. The first value is the shortestPathLengthSum The second
 *         value is the maxPathLength They are returned as an array for performance reasons. I
 *         do not want to create an object, as this function is called *very* often.
 */
private BigInteger[] computeShortestPathLengths(Entity pStartNode, BigInteger pBigShortestPathLengthSum,
        BigInteger pBigMaxPathLength, Set<Entity> pWasSource) {

    int pStartNodeMaxPathLength = 0;

    // a set of nodes that have already been expanded -> algorithm should expand nodes
    // monotonically and not go back
    Set<Entity> alreadyExpanded = new HashSet<Entity>();

    // a queue holding the newly discovered nodes and their distance to the start node
    List<Entity[]> queue = new ArrayList<Entity[]>();

    // initialize queue with start node
    Entity[] innerList = new Entity[2];
    innerList[0] = pStartNode; // the node
    innerList[1] = new Entity("0"); // the distance to the start node
    queue.add(innerList);

    // while the queue is not empty
    while (!queue.isEmpty()) {
        // remove first element from queue
        Entity[] queueElement = queue.get(0);
        Entity currentNode = queueElement[0];
        Entity distance = queueElement[1];
        queue.remove(0);

        // if the node was not already expanded
        if (!alreadyExpanded.contains(currentNode)) {

            // the node gets expanded now
            alreadyExpanded.add(currentNode);

            // if the node was a source node in a previous run, we already have added this path
            if (!pWasSource.contains(currentNode)) {
                // add the distance of this node to shortestPathLengthSum
                // check if maxPathLength must be updated
                int tmpDistance = new Integer(distance.getFirstLexeme());
                pBigShortestPathLengthSum = pBigShortestPathLengthSum.add(BigInteger.valueOf(tmpDistance));

                if (pBigMaxPathLength.compareTo(BigInteger.valueOf(tmpDistance)) == -1) {
                    pBigMaxPathLength = BigInteger.valueOf(tmpDistance);

                    // logger.info("*TEST TRUE:* pBigShortestPathLengthSum = " +
                    // pBigShortestPathLengthSum);
                }
                //
            }
            // even if the node was a source node in a previous run there can be a path to other
            // nodes over this node, so go on

            // get the neighbors of the queue element
            Set<Entity> neighbors = getNeighbors(currentNode);

            // iterate over all neighbors
            for (Entity neighbor : neighbors) {
                // if the node was not already expanded
                if (!alreadyExpanded.contains(neighbor)) {
                    // add the node to the queue, increase node distance by one
                    Entity[] tmpList = new Entity[2];
                    tmpList[0] = neighbor;
                    Integer tmpDistance = new Integer(distance.getFirstLexeme()) + 1;
                    tmpList[1] = new Entity(tmpDistance.toString());
                    queue.add(tmpList);
                }
            }
        }
        pStartNodeMaxPathLength = new Integer(distance.getFirstLexeme());
    }
    eccentricityMap.put(pStartNode, pStartNodeMaxPathLength);

    BigInteger returnArray[] = { pBigShortestPathLengthSum, pBigMaxPathLength };
    return returnArray;
}

From source file:alter.vitro.vgw.service.VitroGatewayService.java

public VgwResponse invokeWSIService(VgwRequestObservation request) throws VitroGatewayException {
    if (!getUseIdas()) {
        VgwResponse vgwResponse = new VgwResponse();
        vgwResponse.setSuccess(false);/*w  ww  .  j  a  v  a2s  .  com*/
        return vgwResponse;
    }

    // REDUNDANT CODE FOR DEBUGGING PURPOSES (SKIPPING THE REGISTRATION). TODO: remove later (perhaps make  gwWithNodeDescriptorList a private var, although will that create any race conditions for it?)
    CGateway myGateway = new CGateway();
    myGateway.setId(getAssignedGatewayUniqueIdFromReg());
    myGateway.setName("");
    myGateway.setDescription("");

    // TODO: transfer the code for acquiring GW description, in the createWSIDescr() method
    CGatewayWithSmartDevices gwWithNodeDescriptorList = myDCon.createWSIDescr(myGateway);
    logger.debug("nodeDescriptorList = {}", gwWithNodeDescriptorList.getSmartDevVec());
    List<CSmartDevice> alterNodeDescriptorsList = gwWithNodeDescriptorList.getSmartDevVec();
    ResourceAvailabilityService.getInstance().updateCachedNodeList(alterNodeDescriptorsList,
            ResourceAvailabilityService.INIT_DISCOVERY);
    // END OF REDUNDANT CODE

    logger.debug("request = {}", request);

    //Get requested resource
    String resourceName = request.getObsType().value();
    Resource requestedResource = Resource.getResource(resourceName);
    if (requestedResource == null) {
        throw new VitroGatewayException(resourceName + " not managed by VITRO gateway");
    }

    //List<Observation> observationList = rsController.getWSIData(requestedResource);
    Vector<QueriedMoteAndSensors> motesAndTheirSensorAndFunctsVec = new Vector<QueriedMoteAndSensors>();
    Vector<ReqFunctionOverData> reqFunctionVec = new Vector<ReqFunctionOverData>();
    ReqFunctionType rftObject = new ReqFunctionType();
    rftObject.setId(BigInteger.valueOf(1));
    rftObject.setDescription(ReqFunctionOverData.lastValFunc);
    reqFunctionVec.add(new ReqFunctionOverData(rftObject));

    //List<CSmartDevice> alterNodeDescriptorsList = gwWithNodeDescriptorList.getSmartDevVec();
    for (CSmartDevice alterNodeDescriptor : alterNodeDescriptorsList) {
        QueriedMoteAndSensors tmpQueriedMoteAndSensors = new QueriedMoteAndSensors();
        tmpQueriedMoteAndSensors.setMoteid(alterNodeDescriptor.getId());

        Vector<ReqSensorAndFunctions> QueriedSensorIdsAndFuncVec = new Vector<ReqSensorAndFunctions>();
        ReqSensorAndFunctions tmpReqSensingAndFunct = new ReqSensorAndFunctions();

        Integer thedigestInt = request.getObsType().value().hashCode();
        if (thedigestInt < 0)
            thedigestInt = thedigestInt * (-1);

        tmpReqSensingAndFunct.setSensorModelid(Integer.toString(thedigestInt));
        tmpReqSensingAndFunct.getFid().add(BigInteger.valueOf(1));
        QueriedSensorIdsAndFuncVec.add(tmpReqSensingAndFunct);

        tmpQueriedMoteAndSensors.setQueriedSensorIdsAndFuncVec(QueriedSensorIdsAndFuncVec);

        motesAndTheirSensorAndFunctsVec.addElement(tmpQueriedMoteAndSensors);
    }

    Vector<ReqResultOverData> observationsList = myDCon.translateAggrQuery(motesAndTheirSensorAndFunctsVec,
            reqFunctionVec);

    if (observationsList != null && !observationsList.isEmpty()) {
        //            // we only have one function, so only one element in the observarionList
        //            ReqResultOverData observations = observationsList.elementAt(0);
        //            Vector<ResultAggrStruct> tmpResultsStructVec = observations.getAllResultsforFunct();

        for (ReqResultOverData observations : observationsList) {
            Vector<ResultAggrStruct> tmpResultsStructVec = observations.getAllResultsforFunct();
            if (tmpResultsStructVec != null && !tmpResultsStructVec.isEmpty()) {
                for (ResultAggrStruct resultStruct : tmpResultsStructVec) {
                    if (resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValueNoReading)
                            || resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValuePending)
                            || resultStruct.getVal()
                                    .equalsIgnoreCase(ReqResultOverData.specialValueNotSupported)
                            || resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValueBinary)
                            || resultStruct.getVal().equalsIgnoreCase(ReqResultOverData.specialValueTimedOut)) {
                        System.out.println("Special values should not be sent!!");
                        continue;
                    }
                    Observation vgwObservation = new Observation();
                    Node theNode = new Node();
                    theNode.setId(resultStruct.getMid());

                    vgwObservation.setNode(theNode);
                    vgwObservation.setResource(requestedResource);
                    // TODO PRODUCES ERROR!!!
                    //System.out.println("Error prone!!");
                    Timestamp tmpTs = resultStruct.getTis().getFromTimestamp();
                    if (tmpTs == null) {
                        java.util.Date today = new java.util.Date();
                        tmpTs = new java.sql.Timestamp(today.getTime());
                    }
                    //System.out.println("Error prone!!");

                    vgwObservation.setTimestamp(tmpTs.getTime());//????
                    vgwObservation.setValue(resultStruct.getVal());
                    //Node node = observation.getNode();
                    String assignedSensorId = idasNodeMapping.get(resultStruct.getMid());
                    logger.debug("Node {} -> assignedSensotId {}", resultStruct.getMid(), assignedSensorId);
                    InsertObservation insertObservation = sensorMLMessageAdapter.getInsertObservationMessage(
                            assignedGatewayUniqueIdFromReg, assignedSensorId, vgwObservation);
                    InsertObservationResponse insertObservationResponse = idas
                            .insertObservation(insertObservation);
                    logger.debug("insertObservationResponse = {}", insertObservationResponse);
                }
            }
        }
    }
    VgwResponse vgwResponse = new VgwResponse();
    vgwResponse.setSuccess(true);
    return vgwResponse;
}

From source file:de.urszeidler.ethereum.licencemanager1.deployer.LicenseManagerDeployer.java

private void init(String senderKey, String senderPass) throws Exception {
    ethereum = EthereumInstance.getInstance().getEthereum();
    String property = System.getProperty("EthereumFacadeProvider");
    // testnetProvider
    if (property != null && (property.equalsIgnoreCase("rpc") || property.equalsIgnoreCase("ropsten")
            || property.equalsIgnoreCase("InfuraRopsten"))) {

        millis = 2000L;//  w  w w . j av  a2 s  .co  m
    } else if (property != null && property.equalsIgnoreCase("private")) {
        sender = AccountProvider.fromPrivateKey(BigInteger.valueOf(100000L));
        millis = 100L;
    } else {
        sender = AccountProvider.fromPrivateKey(
                (Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c")));
        millis = 10L;
    }

    if (senderKey != null && !senderKey.isEmpty() && sender == null) {
        sender = unlockAccount(senderKey, senderPass);
    }
    deployer = new ContractsDeployer(ethereum, "/contracts/combined.json", true);
}

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

private BlockHeader createHeader(Block newBlockParent, List<BlockHeader> uncles, List<Transaction> txs,
        BigInteger minimumGasPrice) {
    final byte[] unclesListHash = HashUtil.sha3(BlockHeader.getUnclesEncodedEx(uncles));

    final long timestampSeconds = this.getCurrentTimeInSeconds();

    // Set gas limit before executing block
    BigInteger minGasLimit = BigInteger
            .valueOf(properties.getBlockchainConfig().getCommonConstants().getMIN_GAS_LIMIT());
    BigInteger targetGasLimit = BigInteger
            .valueOf(properties.getBlockchainConfig().getCommonConstants().getTARGET_GAS_LIMIT());
    BigInteger parentGasLimit = new BigInteger(1, newBlockParent.getGasLimit());
    BigInteger gasLimit = new GasLimitCalculator().calculateBlockGasLimit(parentGasLimit,
            BigInteger.valueOf(newBlockParent.getGasUsed()), minGasLimit, targetGasLimit);

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

From source file:com.cognitect.transit.TransitTest.java

public void testWriteRatio() throws Exception {

    Ratio r = new RatioImpl(BigInteger.valueOf(1), BigInteger.valueOf(2));

    assertEquals("{\"~#ratio\":[\"~n1\",\"~n2\"]}", writeJsonVerbose(r));
    assertEquals("[\"~#ratio\",[\"~n1\",\"~n2\"]]", writeJson(r));
}