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:org.pgptool.gui.encryption.implpgp.EncryptionServicePgpImpl.java

private static void updateProgress(Updater progress, long totalBytesRead)
        throws UserRequestedCancellationException {
    if (progress == null) {
        return;/*from w w w  .  j  a va  2 s. c om*/
    }
    progress.updateStepsTaken(BigInteger.valueOf(totalBytesRead));
    if (progress.isCancelationRequested()) {
        throw new UserRequestedCancellationException();
    }
}

From source file:com.ethercamp.harmony.service.WalletService.java

public WalletInfoDTO getWalletInfo() {
    BigInteger gasPrice = BigInteger.valueOf(ethereum.getGasPrice());
    BigInteger txFee = gasLimit.multiply(gasPrice);

    List<WalletAddressDTO> list = addresses.entrySet().stream().flatMap(e -> {
        final String hexAddress = e.getKey();
        try {//from ww  w . j a  v a2  s .co m
            final byte[] address = Hex.decode(hexAddress);
            final BigInteger balance = repository.getBalance(address);
            final BigInteger sendBalance = calculatePendingChange(pendingSendTransactions, hexAddress, txFee);
            final BigInteger receiveBalance = calculatePendingChange(pendingReceiveTransactions, hexAddress,
                    BigInteger.ZERO);

            return Stream.of(new WalletAddressDTO(e.getValue(), e.getKey(), balance,
                    receiveBalance.subtract(sendBalance), keystore.hasStoredKey(e.getKey())));
        } catch (Exception exception) {
            log.error("Error in making wallet address " + hexAddress, exception);
            return Stream.empty();
        }
    }).collect(Collectors.toList());

    BigInteger totalAmount = list.stream().map(t -> t.getAmount()).reduce(BigInteger.ZERO,
            (state, amount) -> state.add(amount));

    WalletInfoDTO result = new WalletInfoDTO(totalAmount);

    result.getAddresses().addAll(list);
    return result;
}

From source file:com.microsoft.azure.keyvault.cryptography.algorithms.AesCbcHmacSha2.java

static byte[] toBigEndian(long i) {

    byte[] shortRepresentation = BigInteger.valueOf(i).toByteArray();
    byte[] longRepresentation = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };

    System.arraycopy(shortRepresentation, 0, longRepresentation,
            longRepresentation.length - shortRepresentation.length, shortRepresentation.length);

    return longRepresentation;
}

From source file:Main.java

/**
 * Add two positive Duration objects./*  ww w  .  ja v a 2 s  .c  o  m*/
 * @param d1 The first Duration.
 * @param d2 The second Duration.
 * @return The sum of the two durations.
 */
private static Duration addPositiveDurations(Duration d1, Duration d2) {
    BigDecimal s1 = fractionalSeconds(d1);
    BigDecimal s2 = fractionalSeconds(d2);
    BigDecimal extraSeconds = s1.add(s2);

    Duration strip1 = stripFractionalSeconds(d1);
    Duration strip2 = stripFractionalSeconds(d2);

    Duration stripResult = strip1.add(strip2);

    if (extraSeconds.compareTo(BigDecimal.ONE) >= 0) {
        stripResult = stripResult.add(DURATION_1_SECOND);
        extraSeconds = extraSeconds.subtract(BigDecimal.ONE);
    }

    BigDecimal properSeconds = BigDecimal.valueOf(stripResult.getSeconds()).add(extraSeconds);

    return FACTORY.newDuration(true, BigInteger.valueOf(stripResult.getYears()),
            BigInteger.valueOf(stripResult.getMonths()), BigInteger.valueOf(stripResult.getDays()),
            BigInteger.valueOf(stripResult.getHours()), BigInteger.valueOf(stripResult.getMinutes()),
            properSeconds);
}

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

public void testReadCmap() throws IOException {

    Map m = reader("{\"~#cmap\": [{\"~#ratio\":[\"~n1\",\"~n2\"]},1,{\"~#list\":[1,2,3]},2]}").read();

    assertEquals(2, m.size());// w w  w .j  a  v a2 s .c  om

    Iterator<Map.Entry> i = m.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry e = i.next();
        if ((Long) e.getValue() == 1L) {
            Ratio r = (Ratio) e.getKey();
            assertEquals(BigInteger.valueOf(1), r.getNumerator());
            assertEquals(BigInteger.valueOf(2), r.getDenominator());
        } else if ((Long) e.getValue() == 2L) {
            List l = (List) e.getKey();
            assertEquals(1L, l.get(0));
            assertEquals(2L, l.get(1));
            assertEquals(3L, l.get(2));
        }
    }
}

From source file:org.gofleet.openLS.ddbb.dao.postgis.PostGisHBGeoCodingDAO.java

@Transactional(readOnly = true)
public List<AbstractResponseParametersType> geocoding(final GeocodeRequestType param) {
    HibernateCallback<List<AbstractResponseParametersType>> action = new HibernateCallback<List<AbstractResponseParametersType>>() {
        public List<AbstractResponseParametersType> doInHibernate(Session session)
                throws HibernateException, SQLException {

            List<AddressType> addressList = param.getAddress();
            List<AbstractResponseParametersType> res_ = new LinkedList<AbstractResponseParametersType>();

            for (AddressType addressType : addressList) {

                // TODO change deprecation?
                @SuppressWarnings("deprecation")
                CallableStatement consulta = session.connection()
                        .prepareCall("{call gls_geocoding(?, ?, ?, ?, ?)}");

                String street = GeoUtil.extractStreet(addressType);
                String munsub = GeoUtil.extractMunSub(addressType);
                String mun = GeoUtil.extractMun(addressType);
                String subcountry = GeoUtil.extractSubCountry(addressType);
                String country = GeoUtil.extractCountry(addressType);

                consulta.setString(1, street);
                consulta.setString(2, munsub);
                consulta.setString(3, mun);
                consulta.setString(4, subcountry);
                consulta.setString(5, country);

                LOG.debug(consulta);/*  w w  w  . j  a va  2 s . c  o  m*/

                ResultSet o = consulta.executeQuery();
                GeocodeResponseType grt = new GeocodeResponseType();
                while (o.next()) {
                    GeocodeResponseListType geocode = new GeocodeResponseListType();
                    try {
                        PGgeometry g = (PGgeometry) o.getObject("geometry");
                        Jdbc4Array address = (Jdbc4Array) o.getArray("address");

                        GeocodedAddressType addresstype = new GeocodedAddressType();
                        addresstype.setPoint(PostGisUtils.getReferencedPoint(g));
                        addresstype.setAddress(PostGisUtils.getAddress(address));

                        geocode.getGeocodedAddress().add(addresstype);

                        geocode.setNumberOfGeocodedAddresses(BigInteger.valueOf(1l));

                        grt.getGeocodeResponseList().add(geocode);
                    } catch (Throwable t) {
                        LOG.error("Error extracting data from database.", t);
                    }
                    res_.add(grt);
                }
            }
            return res_;
        }

    };

    return hibernateTemplate.executeWithNativeSession(action);
}

From source file:net.ripe.rpki.validator.commands.TopDownWalkerTest.java

public static ManifestCms getRootManifestCms() {
    ManifestCmsBuilder builder = new ManifestCmsBuilder();
    builder.withCertificate(createManifestEECertificate()).withManifestNumber(BigInteger.valueOf(68));
    builder.withThisUpdateTime(THIS_UPDATE_TIME).withNextUpdateTime(NEXT_UPDATE_TIME);
    builder.addFile("foo1", FOO_CONTENT);
    builder.addFile("BaR", BAR_CONTENT);
    builder.withSignatureProvider(DEFAULT_SIGNATURE_PROVIDER);
    return builder.build(ROOT_KEY_PAIR.getPrivate());
}

From source file:ch.admin.hermes.etl.load.cmis.AlfrescoCMISClient.java

/**
 * Schreibt eine lokale Datei in Alfresco hoch.
 * @param parentId Parent Id//from ww  w . ja va 2s  . c o m
 * @param name Name
 * @param properties Eigenschaften
 * @param localname Lokaler Name wenn Datei oder URL wenn von http://www.hermes.admin.ch
 * @return neu erstelles Dokument
 * @throws Exception Allgemeiner I/O Fehler
 */
private Document postFile(String parentId, String name, HashMap<String, Object> properties, File content)
        throws IOException {
    String mimeType = mimeTypesMap.getContentType(content);
    Folder parent = (Folder) session.getObject(parentId, session.getDefaultContext());

    if (properties == null)
        properties = new HashMap<String, Object>();

    properties.put("cmis:name", name);
    // This works because we are using the OpenCMIS extension for Alfresco
    properties.put("cmis:objectTypeId", "cmis:document,P:cm:titled");

    FileInputStream in = new FileInputStream(content);
    ContentStream contentStream = new ContentStreamImpl(name, BigInteger.valueOf(content.length()), mimeType,
            in);
    properties.put(PropertyIds.CONTENT_STREAM_FILE_NAME, name);
    properties.put(PropertyIds.CONTENT_STREAM_LENGTH, content.length());
    properties.put(PropertyIds.CONTENT_STREAM_MIME_TYPE, mimeType);

    Document doc = parent.createDocument(properties, contentStream, VersioningState.MAJOR);
    in.close();
    return (doc);
}

From source file:co.rsk.blockchain.utils.BlockGenerator.java

public static Block getNewGenesisBlock(long initialGasLimit, Map<byte[], BigInteger> preMineMap,
        byte difficultyByte) {

    byte[] nonce = new byte[] { 0 };
    byte[] difficulty = new byte[] { difficultyByte };
    byte[] mixHash = new byte[] { 0 };

    /* Unimportant address. Because there is no subsidy
    ECKey ecKey;/*from   w ww  .j  a  v a  2s .  c  om*/
    byte[] address;
    SecureRandom rand =new InsecureRandom(0);
    ecKey = new ECKey(rand);
    address = ecKey.getAddress();
    */
    byte[] coinbase = Hex.decode("e94aef644e428941ee0a3741f28d80255fddba7f");

    long timestamp = 0; // predictable timeStamp

    byte[] parentHash = EMPTY_BYTE_ARRAY;
    byte[] extraData = EMPTY_BYTE_ARRAY;

    long gasLimit = initialGasLimit;

    byte[] bitcoinMergedMiningHeader = null;
    byte[] bitcoinMergedMiningMerkleProof = null;
    byte[] bitcoinMergedMiningCoinbaseTransaction = null;

    Genesis genesis = new Genesis(parentHash, EMPTY_LIST_HASH, coinbase, getZeroHash(), difficulty, 0, gasLimit,
            0, timestamp, extraData, mixHash, nonce, bitcoinMergedMiningHeader, bitcoinMergedMiningMerkleProof,
            bitcoinMergedMiningCoinbaseTransaction, BigInteger.valueOf(100L).toByteArray());
    if (preMineMap != null) {
        Map<ByteArrayWrapper, InitialAddressState> preMineMap2 = generatePreMine(preMineMap);
        genesis.setPremine(preMineMap2);

        byte[] rootHash = generateRootHash(preMineMap2);
        genesis.setStateRoot(rootHash);

    }
    return genesis;
}

From source file:com.niroshpg.android.gmail.CronHandlerServlet.java

public BigInteger getHistoryIdXX(Gmail service, String userId, Credential credential) throws IOException {
    BigInteger historyId = null;/*from  w w w  .j a va  2 s.  c  om*/

    try {
        URL url = new URL("https://www.googleapis.com/gmail/v1/users/" + userId + "/profile");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //credential.refreshToken();
        connection.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
        connection.setRequestProperty("Content-Type", "application/json");

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // OK
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
                logger.warning(line);

            }
            reader.close();

            JSONObject jsonObj = new JSONObject(res);
            historyId = BigInteger.valueOf(jsonObj.getLong("historyId"));

        } else {
            // Server returned HTTP error code.
            logger.warning("failed : " + connection.getResponseCode());

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));

            String error = "";
            String text;
            while ((text = br.readLine()) != null) {
                error += text;
            }

            logger.warning("error : " + error);
        }

    } catch (Exception e) {
        logger.warning("exception : " + e.getMessage() + " , " + e.getStackTrace().toString());
    }
    return historyId;

}