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:co.rsk.peg.BridgeSerializationUtilsTest.java

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

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

    StringBuilder sampleBuilder = new StringBuilder();
    sampleBuilder.append("03"); // Length of outer list
    sampleBuilder.append("02"); // Length of first element
    sampleBuilder.append("02"); // Length of second element
    sampleBuilder.append("cd"); // Length of third element
    sampleBuilder.append("1388"); // First element (creation date -> 5000 milliseconds from epoch)
    sampleBuilder.append("002a"); // Second element block number 42
    sampleBuilder.append("06212121212121"); // third element (inner list, public keys). 6 elements of 33 bytes (0x21 bytes) each.
    for (int i = 0; i < publicKeyBytes.length; i++) {
        sampleBuilder.append(Hex.toHexString(publicKeyBytes[i]));
    }//from   w w  w.j  av  a2s  .  co  m
    byte[] sample = Hex.decode(sampleBuilder.toString());

    Federation deserializedFederation = BridgeSerializationUtils.deserializeFederation(sample,
            NetworkParameters.fromID(NetworkParameters.ID_REGTEST));

    Assert.assertEquals(5000, deserializedFederation.getCreationTime().toEpochMilli());
    Assert.assertEquals(4, deserializedFederation.getNumberOfSignaturesRequired());
    Assert.assertEquals(6, deserializedFederation.getPublicKeys().size());
    Assert.assertThat(deserializedFederation.getCreationBlockNumber(), is(42L));
    for (int i = 0; i < 6; i++) {
        Assert.assertTrue(
                Arrays.equals(publicKeyBytes[i], deserializedFederation.getPublicKeys().get(i).getPubKey()));
    }
    Assert.assertEquals(NetworkParameters.fromID(NetworkParameters.ID_REGTEST),
            deserializedFederation.getBtcParams());
}

From source file:org.alfresco.mobile.android.api.services.impl.AbstractDocumentFolderServiceImpl.java

/** {@inheritDoc} */
public PagingResult<Node> getChildren(Folder parentFolder, ListingContext lcontext) {

    if (isObjectNull(parentFolder)) {
        throw new IllegalArgumentException(String
                .format(Messagesl18n.getString("ErrorCodeRegistry.GENERAL_INVALID_ARG_NULL"), "parentFolder"));
    }/*from   w ww  .  j a  v a2s. c  om*/

    try {
        NavigationService navigationService = cmisSession.getBinding().getNavigationService();
        OperationContext ctxt = new OperationContextImpl(cmisSession.getDefaultContext());
        ObjectFactory objectFactory = cmisSession.getObjectFactory();

        // By default Listing context has default value
        String orderBy = getSorting(SORT_PROPERTY_NAME, true);
        BigInteger maxItems = null;
        BigInteger skipCount = null;

        if (lcontext != null) {
            orderBy = getSorting(lcontext.getSortProperty(), lcontext.isSortAscending());
            maxItems = BigInteger.valueOf(lcontext.getMaxItems());
            skipCount = BigInteger.valueOf(lcontext.getSkipCount());
        }
        // get the children
        ObjectInFolderList children = navigationService.getChildren(session.getRepositoryInfo().getIdentifier(),
                parentFolder.getIdentifier(), ctxt.getFilterString(), orderBy, ctxt.isIncludeAllowableActions(),
                ctxt.getIncludeRelationships(), ctxt.getRenditionFilterString(), ctxt.isIncludePathSegments(),
                maxItems, skipCount, null);

        // convert objects
        List<Node> page = new ArrayList<Node>();
        List<ObjectInFolderData> childObjects = children.getObjects();

        if (childObjects != null) {
            // //Log.d(TAG, "childObjects : " + childObjects.size());
            for (ObjectInFolderData objectData : childObjects) {
                if (objectData.getObject() != null) {
                    Node n = convertNode(objectFactory.convertObject(objectData.getObject(), ctxt));
                    page.add(n);
                }
            }
        }

        Boolean hasMoreItem = false;
        if (maxItems != null) {
            hasMoreItem = children.hasMoreItems() && page.size() == maxItems.intValue();
        } else {
            hasMoreItem = children.hasMoreItems();
        }

        return new PagingResultImpl<Node>(page, hasMoreItem, children.getNumItems().intValue());
    } catch (Exception e) {
        convertException(e);
    }
    return null;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepOne() throws Exception {
    byte[] send;//from   w  w w .  jav a 2  s.  co m
    IHttpRequestResponse response;
    byte[] request;

    BigInteger ciphered = new BigInteger(1, this.encryptedKey);

    do {
        // Check if user has cancelled the worker
        if (isCancelled()) {
            loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user",
                    Logger.LogLevel.INFO);
            return;
        }

        this.si = this.si.add(BigInteger.ONE);
        send = prepareMsg(ciphered, this.si);

        request = this.requestResponse.getRequest();
        String[] components = Decoder.getComponents(this.parameter.getJoseValue());
        components[1] = Decoder.base64UrlEncode(send);

        String newComponentsConcatenated = Decoder.concatComponents(components);

        request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated);

        response = callbacks.makeHttpRequest(this.httpService, request);
        updateAmountRequest();

    } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID);

    this.c0 = new BigInteger(1, send);
    this.s0 = this.si;
    // mi = {[2B,3B-1]}
    this.m = new Interval[] { new Interval(BigInteger.valueOf(2).multiply(bigB),
            (BigInteger.valueOf(3).multiply(bigB)).subtract(BigInteger.ONE)) };

    loggerInstance.log(getClass(), "Found s0 : " + this.si, Logger.LogLevel.INFO);
}

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./*from  w w  w . ja v a2  s .com*/
 *
 * @param numMessages the maximum number of messages to return
 * @param visibilityTimeout the duration (in seconds) the retrieved message is hidden from
 *                          subsequent calls to retrieve.
 * @return an array of message objects
 */
public Message[] receiveMessages(int numMessages, int visibilityTimeout) throws SQSException {
    return receiveMessages(BigInteger.valueOf(numMessages), BigInteger.valueOf(visibilityTimeout));
}

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

@Test
public void testDeployIssuerContract() throws Exception {
    testDeployLicenseManager();//from  w ww  .  java  2s  .  com

    File file = new File("ca.txt");
    String ca = IOUtils.toString(new FileInputStream(file), EthereumFacade.CHARSET);
    EthAddress address = EthAddress.of(ca);

    String itemName = "'The item name.'";
    String textHash = "TextHash";
    String url = "http://test.org";
    String[] args = new String[] { "-cic", address.withLeading0x(), itemName, textHash, url, "0", "200", "-wca",
            "ca.txt", "-de" };
    LicenseManagerDeployer.main(args);

    LicenseManager licenseManager = deployer.createLicenseManagerProxy(sender, address);
    assertEquals(1, licenseManager.contractCount().intValue());

    EthAddress lia = licenseManager.contracts(0);

    LicenseIssuer licenseIssuer = deployer.createLicenseIssuerProxy(sender, lia);

    assertEquals(itemName, licenseIssuer.licensedItemName());
    assertEquals(textHash, licenseIssuer.licenseTextHash());
    assertEquals(url, licenseIssuer.licenseUrl());
    assertEquals(true, licenseIssuer.issuable());
    assertEquals(0, licenseIssuer.licenseCount().intValue());

    assertEquals(0, licenseIssuer.licenseLifetime().intValue());
    assertEquals(BigInteger.valueOf(FINNEY_TO_WEI).multiply(BigInteger.valueOf(200)),
            licenseIssuer.licencePrice());

}

From source file:co.rsk.remasc.Remasc.java

/**
 * Pay the mainchain block miner, its siblings miners and the publisher miners
 *//*from   w ww.  j a  v a 2 s  .  c o m*/
private void payWithSiblings(BlockHeader processingBlockHeader, BigInteger fullBlockReward,
        List<Sibling> siblings, boolean previousBrokenSelectionRule) {
    SiblingPaymentCalculator paymentCalculator = new SiblingPaymentCalculator(fullBlockReward,
            previousBrokenSelectionRule, siblings.size(), this.remascConstants);

    this.payPublishersWhoIncludedSiblings(siblings, paymentCalculator.getIndividualPublisherReward());
    provider.addToBurnBalance(paymentCalculator.getPublishersSurplus());

    provider.addToBurnBalance(paymentCalculator.getMinersSurplus());

    this.payIncludedSiblings(siblings, paymentCalculator.getIndividualMinerReward());
    if (previousBrokenSelectionRule) {
        provider.addToBurnBalance(
                paymentCalculator.getPunishment().multiply(BigInteger.valueOf(siblings.size() + 1L)));
    }

    // Pay to main chain block miner
    transfer(processingBlockHeader.getCoinbase(), paymentCalculator.getIndividualMinerReward());
}

From source file:org.araneaframework.tests.FormConstraintTest.java

/**
 * Testing reading from request with a primitive constraint set.
 *//*w w  w.  j av a 2s.  c om*/
public void testFormOptionalConstraint() throws Exception {

    FormWidget testForm = makeUsualForm();

    MockHttpServletRequest request = new MockHttpServletRequest();

    //invalid

    request.addParameter("testForm.__present", "true");
    request.addParameter("testForm.myCheckBox", "true");
    request.addParameter("testForm.myLongText", "12345");
    request.addParameter("testForm.myDateTime", (String) null);

    //Testing primitive constraint
    testForm.getElement("myLongText").setConstraint(
            new OptionalConstraint(new NumberInRangeConstraint(BigInteger.valueOf(20000), null)));

    StandardServletInputData input = new StandardServletInputData(request);
    input.pushScope("testForm");
    testForm._getWidget().update(input);
    input.popScope();

    assertTrue("Test form must not be valid after reading from request", !testForm.convertAndValidate());

    //valid

    request = new MockHttpServletRequest();

    request.addParameter("testForm.__present", "true");
    request.addParameter("testForm.myCheckBox", "true");
    request.addParameter("testForm.myLongText", "40000");
    request.addParameter("testForm.myDateTime", (String) null);

    input = new StandardServletInputData(request);
    input.pushScope("testForm");
    testForm._getWidget().update(input);
    input.popScope();

    assertTrue("Test form must be valid after reading from request", testForm.convertAndValidate());

    //off

    request = new MockHttpServletRequest();

    request.addParameter("testForm.__present", "true");
    request.addParameter("testForm.myCheckBox", "true");
    request.addParameter("testForm.myLongText", (String) null);
    request.addParameter("testForm.myDateTime", (String) null);

    input = new StandardServletInputData(request);
    input.pushScope("testForm");
    testForm._getWidget().update(input);
    input.popScope();

    assertTrue("Test form must be valid after reading from request", testForm.convertAndValidate());

}

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

@Override
public void invalidArgumentDepth(BigInteger depth) {
    if (depth == BigInteger.ZERO) {
        invalidArgument("Depth must not be zero");
    } else if (depth == BigInteger.valueOf(-1)) {
        invalidArgument("Depth must not be less than -1");
    }//from  w  w  w  .ja  va2  s  .c om
}

From source file:javadz.beanutils.locale.converters.BigIntegerLocaleConverter.java

/**
 * Convert the specified locale-sensitive input object into an output object of
 * BigInteger type./*from w w w. j  a va 2  s  .c  o  m*/
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 * @return The converted value
 *
 * @exception ConversionException if conversion cannot be performed
 *  successfully
 * @throws ParseException if an error occurs parsing a String to a Number
 * @since 1.8.0
 */
protected Object parse(Object value, String pattern) throws ParseException {

    Object result = super.parse(value, pattern);

    if (result == null || result instanceof BigInteger) {
        return result;
    }

    if (result instanceof Number) {
        return BigInteger.valueOf(((Number) result).longValue());
    }

    try {
        return new BigInteger(result.toString());
    } catch (NumberFormatException ex) {
        throw new ConversionException("Suplied number is not of type BigInteger: " + result);
    }

}

From source file:org.ktunaxa.referral.server.service.CmisServiceImpl.java

protected Document create(String documentName, String mimeType, InputStream in, long contentLength,
        boolean canUpdate, String... folderNames) throws IOException {
    Folder folder = getWorkingFolder();//w  w w . j a v  a2  s  . c o  m

    for (String folderName : folderNames) {
        folder = getOrCreateSubFolder(folder, folderName);
    }

    // Go over all children and see if the document already exists:
    for (CmisObject object : folder.getChildren()) {
        if (documentName.equals(object.getName())) {
            // update if allowed
            if (canUpdate) {
                Document document = (Document) object;
                document.deleteAllVersions();
            } else {
                throw new IOException("Document '" + documentName + "' already exists.");
            }
        }
    }

    // New create the actual document:
    log.debug("Creating document " + documentName);
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
    properties.put(PropertyIds.NAME, documentName);
    properties.put(PropertyIds.CREATED_BY, config.getUserName());
    properties.put(PropertyIds.CHECKIN_COMMENT, "Create new document.");
    log.debug("Updating document " + documentName);
    log.debug(PropertyIds.OBJECT_TYPE_ID + "=cmis:document");
    log.debug(PropertyIds.NAME + "=" + documentName);
    log.debug(PropertyIds.CREATED_BY + "=" + config.getUserName());
    log.debug(PropertyIds.CHECKIN_COMMENT + "=Create new document.");
    log.debug("stream = " + in);

    ContentStreamImpl contentStream = new ContentStreamImpl();
    contentStream.setFileName(documentName);
    contentStream.setMimeType(mimeType);
    contentStream.setStream(in);
    if (contentLength >= 0) {
        log.debug("length=" + BigInteger.valueOf(contentLength));
        contentStream.setLength(BigInteger.valueOf(contentLength));
    }

    return folder.createDocument(properties, contentStream, VersioningState.NONE);
}