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:Main.java

public static byte[] decodeBase58(String input) {
    if (input == null) {
        return null;
    }//from   w ww.  ja va2s  .co m
    input = input.trim();
    if (input.length() == 0) {
        return new byte[0];
    }
    BigInteger resultNum = BigInteger.ZERO;
    int nLeadingZeros = 0;
    while (nLeadingZeros < input.length() && input.charAt(nLeadingZeros) == BASE58[0]) {
        nLeadingZeros++;
    }
    long acc = 0;
    int nDigits = 0;
    int p = nLeadingZeros;
    while (p < input.length()) {
        int v = BASE58_VALUES[input.charAt(p) & 0xff];
        if (v >= 0) {
            acc *= 58;
            acc += v;
            nDigits++;
            if (nDigits == BASE58_CHUNK_DIGITS) {
                resultNum = resultNum.multiply(BASE58_CHUNK_MOD).add(BigInteger.valueOf(acc));
                acc = 0;
                nDigits = 0;
            }
            p++;
        } else {
            break;
        }
    }
    if (nDigits > 0) {
        long mul = 58;
        while (--nDigits > 0) {
            mul *= 58;
        }
        resultNum = resultNum.multiply(BigInteger.valueOf(mul)).add(BigInteger.valueOf(acc));
    }
    final int BASE58_SPACE = -2;
    while (p < input.length() && BASE58_VALUES[input.charAt(p) & 0xff] == BASE58_SPACE) {
        p++;
    }
    if (p < input.length()) {
        return null;
    }
    byte[] plainNumber = resultNum.toByteArray();
    int plainNumbersOffs = plainNumber[0] == 0 ? 1 : 0;
    byte[] result = new byte[nLeadingZeros + plainNumber.length - plainNumbersOffs];
    System.arraycopy(plainNumber, plainNumbersOffs, result, nLeadingZeros,
            plainNumber.length - plainNumbersOffs);
    return result;
}

From source file:com.spotify.cassandra.opstools.autobalance.Main.java

private void run(CommandLine cmd) throws IOException, InterruptedException {
    boolean dryrun = cmd.hasOption("d");
    boolean force = cmd.hasOption("f");
    boolean noresolve = cmd.hasOption("r");
    int port = cmd.hasOption("p") ? Integer.parseInt(cmd.getOptionValue("p")) : 7199;
    String nodehost = cmd.hasOption("h") ? cmd.getOptionValue("h") : "localhost";

    System.out.println("Collecting information about the cluster...");

    NodeProbe nodeProbe = new NodeProbe(nodehost, port);

    if (nodeProbe.getTokens().size() != 1) {
        System.err.println("Cluster is using vnodes and should already be automatically balanced!");
        System.exit(1);//  w  w  w  . ja va2  s.  com
    }

    boolean hasData = false;
    if (!dryrun) {
        Map<String, String> loadMap = nodeProbe.getLoadMap();
        for (String s : loadMap.values()) {
            if (s.contains("KB"))
                continue;
            if (s.contains("MB") || s.contains("GB") || s.contains("TB")) {
                hasData = true;
                continue;
            }
            throw new RuntimeException("Unknown suffix in load map; don't dare to continue");
        }
    }

    String partitioner = nodeProbe.getPartitioner();
    BigInteger minToken, maxToken;

    if (partitioner.equals(RandomPartitioner.class.getName())) {
        minToken = RandomPartitioner.ZERO;
        maxToken = RandomPartitioner.MAXIMUM;
    } else if (partitioner.equals(Murmur3Partitioner.class.getName())) {
        minToken = BigInteger.valueOf(Murmur3Partitioner.MINIMUM.token);
        maxToken = BigInteger.valueOf(Murmur3Partitioner.MAXIMUM);
    } else {
        throw new RuntimeException("Unsupported partitioner: " + partitioner);
    }

    // Get current mapping of all live nodes

    List<String> liveNodes = nodeProbe.getLiveNodes();

    Map<String, BigInteger> hostTokenMap = new HashMap<String, BigInteger>();
    Map<String, String> hostDcMap = new HashMap<String, String>();

    for (String host : liveNodes) {
        String dc = nodeProbe.getEndpointSnitchInfoProxy().getDatacenter(host);

        String decoratedHost = host;

        if (!noresolve) {
            // Prefix host with canonical host name.
            // This makes things prettier and also causes tokens to be assigned in logical order.
            decoratedHost = InetAddress.getByName(host).getCanonicalHostName() + "/" + host;
        } else {
            decoratedHost = "/" + host;
        }

        hostDcMap.put(decoratedHost, dc);

        List<String> tokens = nodeProbe.getTokens(host);

        if (tokens.size() > 1) {
            throw new RuntimeException("vnodes not supported");
        }
        if (tokens.size() == 0) {
            throw new RuntimeException("No token for " + host + "; aborting");
        }

        hostTokenMap.put(decoratedHost, new BigInteger(tokens.get(0)));
    }

    Balancer balancer = new Balancer(hostTokenMap, hostDcMap, minToken, maxToken);
    Map<String, BigInteger> newMap = balancer.balance();

    List<Operation> operations = new ArrayList<Operation>();

    boolean movesNeeded = false;
    for (Map.Entry<String, BigInteger> entry : hostTokenMap.entrySet()) {
        String host = entry.getKey();
        BigInteger oldToken = entry.getValue();
        BigInteger newToken = newMap.get(host);
        if (!oldToken.equals(newToken)) {
            movesNeeded = true;
        }
        operations.add(new Operation(host, hostDcMap.get(host), oldToken, newToken));
    }

    if (movesNeeded && hasData && !dryrun && !force) {
        dryrun = true;
        System.out.println(
                "The cluster is unbalanced but has data, so no operations will actually be carried out. Use --force if you want the cluster to balance anyway.");
    }

    Collections.sort(operations);

    boolean unbalanced = false, moved = false;
    for (Operation op : operations) {
        if (op.oldToken.equals(op.newToken)) {
            System.out.println(op.host + ": Stays on token " + op.oldToken);
        } else {
            System.out.println(op.host + ": Moving from token " + op.oldToken + " to token " + op.newToken);
            if (!dryrun) {
                String ip = op.host.substring(op.host.lastIndexOf("/") + 1);
                NodeProbe np = new NodeProbe(ip, 7199);
                np.move(op.newToken.toString());
                moved = true;
            } else {
                unbalanced = true;
            }
        }
    }

    if (!unbalanced && moved) {
        System.out.println("The cluster is now balanced!");
    }
}

From source file:com.cyphermessenger.utils.Utils.java

public static byte[] longToBytes(long a) {
    return BigInteger.valueOf(a).toByteArray();
}

From source file:org.springframework.data.rest.webmvc.PersistentEntityResourceAssemblerIntegrationTests.java

/**
 * @see DATAREST-609/*  www  .j  ava 2  s  .  c o  m*/
 */
@Test
public void addsSelfAndSingleResourceLinkToResourceByDefault() throws Exception {

    Projector projector = mock(Projector.class);

    when(projector.projectExcerpt(anyObject())).thenAnswer(new ReturnsArgumentAt(0));

    PersistentEntityResourceAssembler assembler = new PersistentEntityResourceAssembler(entities, projector,
            associations,
            new DefaultSelfLinkProvider(entities, entityLinks, Collections.<EntityLookup<?>>emptyList()));

    User user = new User();
    user.id = BigInteger.valueOf(4711);

    PersistentEntityResource resource = assembler.toResource(user);

    Links links = new Links(resource.getLinks());

    assertThat(links, is(Matchers.<Link>iterableWithSize(2)));
    assertThat(links.getLink("self").getVariables(), is(Matchers.empty()));
    assertThat(links.getLink("user").getVariableNames(), is(hasItem("projection")));
}

From source file:com.github.beat.signer.pdf_signer.TSAClient.java

/**
 *
 * @param messageImprint//ww  w  .  ja v  a  2 s .  c o  m
 *            imprint of message contents
 * @return the encoded time stamp token
 * @throws IOException
 *             if there was an error with the connection or data from the
 *             TSA server, or if the time stamp response could not be
 *             validated
 */
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
    digest.reset();
    byte[] hash = digest.digest(messageImprint);

    // 32-bit cryptographic nonce
    // FIXME sicher??
    SecureRandom random = new SecureRandom();
    int nonce = random.nextInt();

    // generate TSA request
    TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
    tsaGenerator.setCertReq(true);
    ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
    TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));

    // get TSA response
    byte[] tsaResponse = getTSAResponse(request.getEncoded());

    TimeStampResponse response;
    try {
        response = new TimeStampResponse(tsaResponse);
        response.validate(request);
    } catch (TSPException e) {
        throw new IOException(e);
    }

    TimeStampToken token = response.getTimeStampToken();
    if (token == null) {
        throw new IOException("Response does not have a time stamp token");
    }

    return token.getEncoded();
}

From source file:org.springframework.cloud.consul.discovery.ConsulCatalogWatch.java

@Scheduled(fixedDelayString = "${spring.cloud.consul.discovery.catalogServicesWatchDelay:10}")
public void catalogServicesWatch() {
    long index = -1;
    if (catalogServicesIndex.get() != null) {
        index = catalogServicesIndex.get().longValue();
    }// w w  w .  ja  va 2  s .  c om

    Response<Map<String, List<String>>> response = consul
            .getCatalogServices(new QueryParams(properties.getCatalogServicesWatchTimeout(), index));
    Long consulIndex = response.getConsulIndex();
    if (consulIndex != null) {
        catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
    }

    log.trace("Received services update from consul: {}, index: {}", response.getValue(), consulIndex);
    publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
}

From source file:eu.europa.ec.markt.dss.validation.tsp.OnlineTSPSource.java

@Override
public TimeStampResponse getTimeStampResponse(DigestAlgorithm algorithm, byte[] digest) throws IOException {

    try {/*from   www. ja v  a2  s.c  o m*/
        byte[] respBytes = null;

        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (policyOid != null) {
            tsqGenerator.setReqPolicy(policyOid);
        }
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(algorithm.getOid(), digest, nonce);
        byte[] requestBytes = request.getEncoded();

        // Call the communications layer
        respBytes = getTSAResponse(requestBytes);

        // Handle the TSA response
        TimeStampResponse response = new TimeStampResponse(respBytes);
        return response;

    } catch (TSPException ex) {
        throw new IOException("Invalid TSP response");
    }

}

From source file:github.daneren2005.serverproxy.ServerProxy.java

public String getPublicAddress(String request) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();

    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
        ipAddress = Integer.reverseBytes(ipAddress);
    }//from  w w  w  .  j a  va2  s. co m

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();
    String ipAddressString = null;
    try {
        ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
        Log.e(TAG, "Unable to get host address.");
    }

    return getAddress(ipAddressString, request);
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.issues.readers.OpenIssuesReader.java

/**
 * {@inheritDoc}//from   www . j  av a 2 s .  c  o m
 * @see org.springframework.batch.item.ItemReader#read()
 */
@Override
public IssueData read()
        throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {

    Assert.notNull(getClientStub());

    // If auth manager is set, try to get the cookie
    if (getAuthManager() != null && getAuthManager().getAuthCookie() != null) {
        getClientStub()._setProperty(HTTPConstants.HEADER_COOKIE, getAuthManager().getAuthCookie());
    }

    if (i < 0 || i >= (items.length - 1)) {
        currentPage++;
        i = -1;
        items = getClientStub().mc_project_get_issues(getUserName(), getPassword(), getProjectId(),
                BigInteger.valueOf(currentPage), PAGE_SIZE);
    }

    i++;
    if (items != null && i < items.length) {
        final IssueData item = items[i];

        if (item != null && (lastJobRun == null || item.getLast_updated() == null
                || item.getLast_updated().after(lastJobRun))) {

            return item;

        } else {
            items = null;
            return null;
        }
    } else {
        items = null;
        return null;
    }
}

From source file:it.gualtierotesta.gdocx.GTbl.java

/**
 * Set the preferred width of the table//from  ww  w  .ja  v a2 s . c  om
 *
 * @param lWidth the value of the preferred width of the table. If omitted,
 * the value is assumed to be zero.
 * @param sType type (unit) of the value Possible values are: auto, dxa,
 * nil, pict
 * @return same GTbl instance
 */
@Nonnull
public GTbl width(final long lWidth, @Nonnull final String sType) {

    Validate.isTrue(0L <= lWidth, "Width value not valid");
    Validate.notEmpty(sType, "Type not valid");

    final TblWidth tblWidth = FACTORY.createTblWidth();
    tblWidth.setType(sType);
    tblWidth.setW(BigInteger.valueOf(lWidth));
    tblPr.setTblW(tblWidth);
    return this;
}