Example usage for java.math BigInteger toString

List of usage examples for java.math BigInteger toString

Introduction

In this page you can find the example usage for java.math BigInteger toString.

Prototype

public String toString() 

Source Link

Document

Returns the decimal String representation of this BigInteger.

Usage

From source file:org.multibit.utils.CSMiscUtils.java

public static BigDecimal getDisplayUnitsForRawUnits(CSAsset asset, BigInteger rawQuantity) {
    if (asset == null)
        return BigDecimal.ZERO;
    CoinSparkGenesis genesis = asset.getGenesis();
    if (genesis == null)
        return BigDecimal.ZERO; // This can happen with brand new Manually transferred asset which has not yet been validated.
    int chargeBasisPoints = genesis.getChargeBasisPoints();
    int chargeExponent = genesis.getChargeFlatExponent();
    int chargeMantissa = genesis.getChargeFlatMantissa();
    int qtyExponent = genesis.getQtyExponent();
    int qtyMantissa = genesis.getQtyMantissa();

    double interestRate = asset.getInterestRate();
    Date issueDate = asset.getIssueDate();

    BigDecimal result = new BigDecimal(rawQuantity.toString());

    //System.out.println("interest rate = " + interestRate);
    //System.out.println("issue date = " + issueDate);

    //System.out.println("raw units =" + result);

    // 1. Compute interest
    if (issueDate != null && interestRate != 0.0) {

        BigDecimal rate = new BigDecimal(String.valueOf(interestRate));
        rate = rate.divide(new BigDecimal(100));
        rate = rate.add(BigDecimal.ONE);
        //interestRate = interestRate / 100;

        //System.out.println("interest rate 1 + ir/100 = " + rate.toPlainString());

        // get years elapsed
        DateTime d1 = new DateTime(issueDate);
        DateTime d2 = new DateTime();

        //System.out.println("Issue: " + d1 + "   Now: " + d2);
        int seconds = Math.abs(Seconds.secondsBetween(d1, d2).getSeconds());

        //System.out.println("...Number of seconds difference: " + seconds);

        BigDecimal elapsedSeconds = new BigDecimal(seconds);

        //System.out.println("...Number of seconds difference: " + elapsedSeconds.toPlainString());

        // To avoid exception, we need to set a precision.
        // java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
        // http://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable
        BigDecimal elapsedYears = elapsedSeconds.divide(new BigDecimal(COINSPARK_SECONDS_IN_YEAR),
                MathContext.DECIMAL32);
        //System.out.println("...Number of years difference: " + elapsedYears.toPlainString());

        double base = elapsedSeconds.doubleValue();
        double exp = elapsedYears.doubleValue();
        //System.out.println("...base=" + base + "  exponent=" + exp);
        double interestMultipler = Math.pow(rate.doubleValue(), elapsedYears.doubleValue());

        //System.out.println("interest multipler =" + interestMultipler);

        result = result.multiply(new BigDecimal(interestMultipler));

        //System.out.println("raw units with interest multiplier =" + result);

        result = result.setScale(0, RoundingMode.DOWN);

        //System.out.println("raw units with interest multiplier, floored =" + result);

    }// w w w.j  av a  2s .  c o m

    // 2. Apply multiple
    int decimalPlaces = CSMiscUtils.getNumberOfDisplayDecimalPlaces(asset);
    BigDecimal display = result;
    if (decimalPlaces != 0) {
        //       System.out.println(">>>>> display = " + display.toPlainString());
        display = result.movePointLeft(decimalPlaces);
        //       System.out.println(">>>>> display = " + display.toPlainString());
    }

    //long qty = Utils.mantissaExponentToQty(qtyMantissa, qtyExponent);
    //   double multiple = asset.getMultiple();
    // let's just do it for now to make sure code is corret   
    //if (multiple != 1.0)
    //   BigDecimal m = new BigDecimal(String.valueOf(multiple));
    //   BigDecimal display = result.multiply(m);

    //System.out.println("multiplier=" + m + ", display=" + display);
    // Stripping zeros from internal zero with different scale does not work, so use 
    // JDK bug still seems to exist
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6480539
    // http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes
    int cmpZeroResult = display.compareTo(BigDecimal.ZERO);
    if (decimalPlaces == 0) {
        display = display.stripTrailingZeros();
    }

    // Stripping trailing zeros from internal zero with different scale does not work, so set to ZERO instead.
    if (0 == cmpZeroResult) {
        display = BigDecimal.ZERO;
    }
    return display;
}

From source file:io.hops.hopsworks.common.dao.tensorflow.config.TensorBoardProcessMgr.java

/**
 * Kill the TensorBoard process//from w w  w .j  a v a2  s  .c  om
 * @param pid
 * @return
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public int killTensorBoard(BigInteger pid) {

    String prog = settings.getHopsworksDomainDir() + "/bin/tensorboard.sh";
    int exitValue;

    String[] command = { "/usr/bin/sudo", prog, "kill", pid.toString() };
    LOGGER.log(Level.INFO, Arrays.toString(command));
    ProcessBuilder pb = new ProcessBuilder(command);
    try {
        Process process = pb.start();
        process.waitFor(20l, TimeUnit.SECONDS);
        exitValue = process.exitValue();
    } catch (IOException | InterruptedException ex) {
        exitValue = 2;
        LOGGER.log(Level.SEVERE, "Failed to kill TensorBoard", ex);
    }
    return exitValue;
}

From source file:io.hops.hopsworks.common.dao.tensorflow.config.TensorBoardProcessMgr.java

/**
 * Check to see if the process is running and is a TensorBoard started by tensorboard.sh
 * @param pid/*from  w  w w . j  a  va 2  s .co  m*/
 * @return
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public int ping(BigInteger pid) {

    String prog = settings.getHopsworksDomainDir() + "/bin/tensorboard.sh";
    int exitValue = 1;

    String[] command = { "/usr/bin/sudo", prog, "ping", pid.toString() };
    LOGGER.log(Level.INFO, Arrays.toString(command));
    ProcessBuilder pb = new ProcessBuilder(command);
    try {
        Process process = pb.start();
        process.waitFor(20l, TimeUnit.SECONDS);
        exitValue = process.exitValue();
    } catch (IOException | InterruptedException ex) {
        LOGGER.log(Level.SEVERE, "Problem pinging: {0}", ex.toString());
    }
    return exitValue;
}

From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8Schema.java

public static String getUInt64String(BigInteger val) {
    if (val == null) {
        return ("null");
    } else {/*from  w w  w.j  av  a  2 s.  c  om*/
        return (val.toString());
    }
}

From source file:be.fedict.trust.service.dao.bean.CertificateAuthorityDAOBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateRevokedCertificates(Set<X509CRLEntry> revokedCertificates, BigInteger crlNumber,
        X500Principal crlIssuer) {
    LOG.debug("Update " + revokedCertificates.size() + " revoked certificates (crlNumber=" + crlNumber + ")");
    for (X509CRLEntry revokedCertificate : revokedCertificates) {
        X500Principal certificateIssuer = revokedCertificate.getCertificateIssuer();
        String issuerName;/*  ww w.j a  v  a 2s .co m*/
        if (null == certificateIssuer) {
            issuerName = crlIssuer.toString();
        } else {
            issuerName = certificateIssuer.toString();
        }
        BigInteger serialNumber = revokedCertificate.getSerialNumber();
        Date revocationDate = revokedCertificate.getRevocationDate();

        // lookup
        RevokedCertificateEntity revokedCertificateEntity = this.entityManager.find(
                RevokedCertificateEntity.class, new RevokedCertificatePK(issuerName, serialNumber.toString()));

        if (null != revokedCertificateEntity) {
            // already exists, update revocationDate and crl number
            revokedCertificateEntity.setRevocationDate(revocationDate);
            revokedCertificateEntity.setCrlNumber(crlNumber);
        } else {
            // don't exist yet, add
            this.entityManager
                    .persist(new RevokedCertificateEntity(issuerName, serialNumber, revocationDate, crlNumber));
        }
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.KinesisLocalFileProxy.java

/**
 * {@inheritDoc}/*from w w w . j av a 2  s .c om*/
 */
@Override
public String getIterator(String shardId, String iteratorEnum, String sequenceNumber)
        throws ResourceNotFoundException, InvalidArgumentException {
    /*
     * If we don't have records in this shard, any iterator will return the empty list. Using a
     * sequence number of 1 on an empty shard will give this behavior.
     */
    List<Record> shardRecords = shardedDataRecords.get(shardId);
    if (shardRecords == null) {
        throw new ResourceNotFoundException(shardId + " does not exist");
    }
    if (shardRecords.isEmpty()) {
        return serializeIterator(shardId, "1");
    }

    if (ShardIteratorType.LATEST.toString().equals(iteratorEnum)) {
        /*
         * If we do have records, LATEST should return an iterator that can be used to read the
         * last record. Our iterators are inclusive for convenience.
         */
        Record last = shardRecords.get(shardRecords.size() - 1);
        return serializeIterator(shardId, last.getSequenceNumber());
    } else if (ShardIteratorType.TRIM_HORIZON.toString().equals(iteratorEnum)) {
        return serializeIterator(shardId, shardRecords.get(0).getSequenceNumber());
    } else if (ShardIteratorType.AT_SEQUENCE_NUMBER.toString().equals(iteratorEnum)) {
        return serializeIterator(shardId, sequenceNumber);
    } else if (ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString().equals(iteratorEnum)) {
        BigInteger num = new BigInteger(sequenceNumber);
        num = num.add(BigInteger.ONE);
        return serializeIterator(shardId, num.toString());
    } else {
        throw new IllegalArgumentException("IteratorEnum value was invalid: " + iteratorEnum);
    }
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

private void printSerialNumber(PrintStream outStream) {
    BigInteger serialNumber = cert.getSerialNumber();

    outStream.format("Serial Number: %s (0x%x)\n", serialNumber.toString(), serialNumber);
}

From source file:com.xerox.amazonws.sqs2.MessageQueue.java

/**
 * Internal implementation of receiveMessages.
 *
 * @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/*  w  w w  .ja v a  2  s.  c  o  m*/
 */
protected Message[] receiveMessages(BigInteger numMessages, BigInteger visibilityTimeout) throws SQSException {
    Map<String, String> params = new HashMap<String, String>();
    if (numMessages != null) {
        params.put("MaxNumberOfMessages", numMessages.toString());
    }
    if (visibilityTimeout != null) {
        params.put("VisibilityTimeout", visibilityTimeout.toString());
    }
    GetMethod method = new GetMethod();
    try {
        ReceiveMessageResponse response = makeRequest(method, "ReceiveMessage", params,
                ReceiveMessageResponse.class);
        if (response.getReceiveMessageResult().getMessages() == null) {
            return new Message[0];
        } else {
            ArrayList<Message> msgs = new ArrayList();
            for (com.xerox.amazonws.typica.sqs2.jaxb.Message msg : response.getReceiveMessageResult()
                    .getMessages()) {
                String decodedMsg = enableEncoding ? new String(Base64.decodeBase64(msg.getBody().getBytes()))
                        : msg.getBody();
                msgs.add(new Message(msg.getMessageId(), msg.getReceiptHandle(), decodedMsg,
                        msg.getMD5OfBody()));
            }
            return msgs.toArray(new Message[msgs.size()]);
        }
    } catch (JAXBException ex) {
        throw new SQSException("Problem parsing returned message.", ex);
    } catch (HttpException ex) {
        throw new SQSException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new SQSException(ex.getMessage(), ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.netscape.cmstools.CMCResponse.java

public void printContent(boolean printCerts) {
    try {/* w  ww.  j av a 2 s . co m*/
        SignedData cmcFullResp = (SignedData) contentInfo.getInterpretedContent();

        StringBuffer content = new StringBuffer();

        if (cmcFullResp.hasCertificates()) {
            SET certs = cmcFullResp.getCertificates();
            int numCerts = certs.size();

            for (int i = 0; i < numCerts; i++) {
                Certificate cert = (Certificate) certs.elementAt(i);
                X509CertImpl certImpl = new X509CertImpl(ASN1Util.encode(cert));

                if (printCerts) {
                    System.out.println("Cert:" + i);
                    ByteArrayOutputStream fos = new ByteArrayOutputStream();
                    certImpl.encode(fos);
                    fos.close();
                    byte[] certBytes = fos.toByteArray();
                    String certB64 = Utils.base64encode(certBytes, true);
                    System.out.println(certB64);
                    System.out.println("===");
                }

                CertPrettyPrint print = new CertPrettyPrint(certImpl);
                content.append(print.toString(Locale.getDefault()));
            }
        }

        System.out.println("Certificates: ");
        System.out.println(content.toString());
        System.out.println("");
        EncapsulatedContentInfo ci = cmcFullResp.getContentInfo();
        OBJECT_IDENTIFIER id = ci.getContentType();
        OBJECT_IDENTIFIER dataid = new OBJECT_IDENTIFIER("1.2.840.113549.1.7.1");
        if (!id.equals(OBJECT_IDENTIFIER.id_cct_PKIResponse) && !id.equals(dataid)) {
            System.out.println("Invalid CMC Response Format");
        }

        if (!ci.hasContent()) {
            // No EncapsulatedContentInfo content; Assume simple response
            return;
        }

        OCTET_STRING content1 = ci.getContent();
        ByteArrayInputStream bbis = new ByteArrayInputStream(content1.toByteArray());
        ResponseBody responseBody = (ResponseBody) (new ResponseBody.Template()).decode(bbis);
        SEQUENCE controlSequence = responseBody.getControlSequence();

        int numControls = controlSequence.size();
        System.out.println("Number of controls is " + numControls);

        for (int i = 0; i < numControls; i++) {
            TaggedAttribute taggedAttr = (TaggedAttribute) controlSequence.elementAt(i);
            OBJECT_IDENTIFIER type = taggedAttr.getType();

            if (type.equals(OBJECT_IDENTIFIER.id_cmc_statusInfoV2)) {
                System.out.println("Control #" + i + ": CMCStatusInfoV2");
                System.out.println("   OID: " + type.toString());
                SET sts = taggedAttr.getValues();
                int numSts = sts.size();
                for (int j = 0; j < numSts; j++) {
                    CMCStatusInfoV2 cst = (CMCStatusInfoV2) ASN1Util.decode(CMCStatusInfoV2.getTemplate(),
                            ASN1Util.encode(sts.elementAt(j)));
                    SEQUENCE seq = cst.getBodyList();

                    StringBuilder s = new StringBuilder("   BodyList: ");
                    for (int k = 0; k < seq.size(); k++) {
                        INTEGER n = (INTEGER) seq.elementAt(k);
                        s.append(n.toString() + " ");
                    }
                    System.out.println(s);
                    int st = cst.getStatus();
                    if (st != CMCStatusInfoV2.SUCCESS && st != CMCStatusInfoV2.CONFIRM_REQUIRED) {
                        String stString = cst.getStatusString();
                        if (stString != null)
                            System.out.println("   Status String: " + stString);
                        OtherInfo oi = cst.getOtherInfo();
                        OtherInfo.Type t = oi.getType();
                        if (t == OtherInfo.FAIL) {
                            System.out.println("   OtherInfo type: FAIL");
                            INTEGER failInfo = oi.getFailInfo();
                            if (failInfo == null) {
                                System.out.println("failInfo null...skipping");
                                continue;
                            }

                            System.out.println("     failInfo=" + OtherInfo.FAIL_INFO[failInfo.intValue()]);
                        } else if (t == OtherInfo.PEND) {
                            System.out.println("   OtherInfo type: PEND");
                            PendInfo pi = oi.getPendInfo();
                            if (pi == null) {
                                System.out.println("PendInfo null...skipping");
                                continue;
                            } else
                                System.out.println("PendInfo present...processing...");
                            if (pi.getPendTime() != null) {
                                String datePattern = "dd/MMM/yyyy:HH:mm:ss z";
                                SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
                                Date d = pi.getPendTime().toDate();
                                System.out.println("   Date: " + dateFormat.format(d));
                            }
                            OCTET_STRING pendToken = pi.getPendToken();
                            if (pendToken != null) {
                                byte reqId[] = pendToken.toByteArray();
                                String reqIdString = new String(reqId);
                                System.out.println("   Pending request id: " + reqIdString);
                            } else {
                                System.out.println("pendToken not in response");
                                System.exit(1);
                            }

                        }
                    } else if (st == CMCStatusInfoV2.SUCCESS) {
                        System.out.println("   Status: SUCCESS");
                    }
                }
            } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_transactionId)) {
                System.out.println("Control #" + i + ": CMC Transaction Id");
                System.out.println("   OID: " + type.toString());
                SET transIds = taggedAttr.getValues();
                INTEGER num = (INTEGER) (ASN1Util.decode(INTEGER.getTemplate(),
                        ASN1Util.encode(transIds.elementAt(0))));
                System.out.println("   INTEGER: " + num);
            } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_recipientNonce)) {
                System.out.println("Control #" + i + ": CMC Recipient Nonce");
                System.out.println("   OID: " + type.toString());
                SET recipientN = taggedAttr.getValues();
                OCTET_STRING str = (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                        ASN1Util.encode(recipientN.elementAt(0))));
                byte b[] = str.toByteArray();
                StringBuilder s = new StringBuilder("   Value: ");
                for (int m = 0; m < b.length; m++) {
                    s.append(b[m]);
                    s.append(" ");
                }
                System.out.println(s);
            } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_senderNonce)) {
                System.out.println("Control #" + i + ": CMC Sender Nonce");
                System.out.println("   OID: " + type.toString());
                SET senderN = taggedAttr.getValues();
                OCTET_STRING str = (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                        ASN1Util.encode(senderN.elementAt(0))));
                byte b[] = str.toByteArray();
                StringBuilder s = new StringBuilder("   Value: ");
                for (int m = 0; m < b.length; m++) {
                    s.append(b[m]);
                    s.append(" ");
                }
                System.out.println(s);
            } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_dataReturn)) {
                System.out.println("Control #" + i + ": CMC Data Return");
                System.out.println("   OID: " + type.toString());
                SET dataReturn = taggedAttr.getValues();
                OCTET_STRING str = (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                        ASN1Util.encode(dataReturn.elementAt(0))));
                byte b[] = str.toByteArray();
                StringBuilder s = new StringBuilder("   Value: ");
                for (int m = 0; m < b.length; m++) {
                    s.append(b[m]);
                    s.append(" ");
                }
                System.out.println(s);
            } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_encryptedPOP)) {
                System.out.println("Control #" + i + ": CMC encrypted POP");
                System.out.println("   OID: " + type.toString());
                SET encryptedPOPvals = taggedAttr.getValues();

                EncryptedPOP encryptedPOP = (EncryptedPOP) (ASN1Util.decode(EncryptedPOP.getTemplate(),
                        ASN1Util.encode(encryptedPOPvals.elementAt(0))));
                System.out.println("     encryptedPOP decoded");

            } else if (type.equals(OBJECT_IDENTIFIER.id_cmc_responseInfo)) {
                System.out.println("Control #" + i + ": CMC ResponseInfo");
                SET riVals = taggedAttr.getValues();
                OCTET_STRING reqIdOS = (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                        ASN1Util.encode(riVals.elementAt(0))));
                byte[] reqIdBA = reqIdOS.toByteArray();
                BigInteger reqIdBI = new BigInteger(reqIdBA);

                System.out.println("   requestID: " + reqIdBI.toString());
            }
        }
    } catch (Exception e) {
        System.out.println("Error found in the response. Exception: " + e.toString());
        System.exit(1);

    }
}

From source file:spade.reporter.audit.artifact.ArtifactManager.java

private Map<String, String> getStateAnnotations(ArtifactIdentifier identifier, BigInteger epoch,
        BigInteger version, String permissions) {
    ArtifactConfig config = artifactConfigs.get(identifier.getClass());
    Map<String, String> annotations = new HashMap<String, String>();
    if (epoch != null && config.hasEpoch) {
        annotations.put(OPMConstants.ARTIFACT_EPOCH, epoch.toString());
    }/*from   w  w w  . jav a  2 s.  c om*/
    if (version != null && config.hasVersion) {
        annotations.put(OPMConstants.ARTIFACT_VERSION, version.toString());
    }
    if (permissions != null && config.hasPermissions) {
        annotations.put(OPMConstants.ARTIFACT_PERMISSIONS, permissions);
    }
    return annotations;
}