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:info.savestate.saveybot.JSONFileManipulator.java

public String lowestSlot() {
    BigInteger lowest = BigInteger.ZERO;
    JSONArray json = getJSON();/*from ww w .j  a  v a 2s .co m*/
    boolean passed = false;
    while (!passed) {
        passed = true;
        for (int i = 0; i < json.length(); i++) {
            JSONObject o = json.getJSONObject(i);
            BigInteger current = o.getBigInteger("slot");
            if (current.compareTo(lowest) == 0) {
                lowest = lowest.add(BigInteger.ONE);
                passed = false;
                break;
            }
        }
    }
    return lowest.toString();
}

From source file:com.keylesspalace.tusky.fragment.NotificationsFragment.java

private void saveNewestNotificationId(List<Notification> notifications) {

    AccountEntity account = accountManager.getActiveAccount();
    BigInteger lastNoti = new BigInteger(account.getLastNotificationId());

    for (Notification noti : notifications) {
        BigInteger a = new BigInteger(noti.getId());
        if (isBiggerThan(a, lastNoti)) {
            lastNoti = a;/*from w ww.j a  v a 2s.  c  o  m*/
        }
    }

    Log.d(TAG, "saving newest noti id: " + lastNoti);

    account.setLastNotificationId(lastNoti.toString());
    accountManager.saveAccount(account);
}

From source file:org.activiti.content.storage.fs.FileSystemContentStorage.java

public ContentObject createContentObject(InputStream contentStream, Long lengthHint) {
    // Get hold of the next free ID to use
    BigInteger id = fetchNewId();
    File contentFile = new File(rootFolder, converter.getPathForId(id).getPath());
    long length = -1;
    try {/*from   ww  w . j a  v  a 2 s.co m*/
        length = IOUtils.copy(contentStream, new FileOutputStream(contentFile, false));
    } catch (FileNotFoundException e) {
        throw new ContentStorageException(
                "Content file was deleted or no longer accessible prior to writing: " + contentFile, e);
    } catch (IOException e) {
        throw new ContentStorageException("Error while writing content to file: " + contentFile, e);
    }

    if (length < 0) {
        // The file was larger than 2GB (max integer value), we need to get the length from the file instead
        length = contentFile.length();
    }

    return new FileSystemContentObject(contentFile, id.toString(), length);
}

From source file:jp.terasoluna.fw.web.struts.form.FieldChecksEx.java

/**
 * wtB?[h?l`FbN?B//from  ww  w.ja  v a 2 s.co m
 * 
 * ?Ap?A<code>BigDecimal</code> ^??
 * ??s\G?[pActionMessage???A<code>false</code> p?B
 * 
 * ???w???A?mF?s?B <code>validation.xml</code> 
 * <code>isAccordedInteger()</code>  <code>"true"</code> w??
 * ???`FbN?s?B `FbN???AG?[pActionMessage???Afalsep?B
 * 
 * ????w???A?mF?s?B
 * validation.xmlisAccordedScale"true"?? ???`FbN?s?B
 * 
 * <p>
 * G?[???AG?[????A wG?[?Xg?B G?[?bZ?[WtH?[}bg?A<code>validation-rules.xml</code>
 * L?q?B<br>
 * L?A??3?A??2?l??B
 * </p>
 * 
 * <h5>validation.xmlL?q</h5>
 * <code><pre>
 * &lt;form name=&quot;/sample&quot;&gt;
 *  ?E?E?E
 *  &lt;field property=&quot;escape&quot;
 *      depends=&quot;number&quot;&gt;
 *    &lt;arg0 key=&quot;sample.escape&quot;/&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;integerLength&lt;/var-name&gt;
 *      &lt;var-value&gt;3&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;scale&lt;/var-name&gt;
 *      &lt;var-value&gt;2&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedInteger&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *    &lt;var&gt;
 *      &lt;var-name&gt;isAccordedScale&lt;/var-name&gt;
 *      &lt;var-value&gt;true&lt;/var-value&gt;
 *    &lt;/var&gt;
 *  &lt;/field&gt;
 *  ?E?E?E
 * &lt;/form&gt;
 * </pre></code>
 * <h5>validation.xml?v&lt;var&gt;vf</h5>
 * <table border="1">
 * <tr>
 * <td><center><b><code>var-name</code></b></center></td>
 * <td><center><b><code>var-value</code></b></center></td>
 * <td><center><b>K?{?</b></center></td>
 * <td><center><b>Tv</b></center></td>
 * </tr>
 * <tr>
 * <td> <code>integerLength</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>?????A<code>isAccordedInteger</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>scale</code> </td>
 * <td> ??? </td>
 * <td> <code>false</code> </td>
 * <td>??l???A<code>isAccordedScale</code>w
 * ?Aw???s?B??A?l ??A??s?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedInteger</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * <tr>
 * <td> <code>isAccordedScale</code> </td>
 * <td> ???v`FbN </td>
 * <td> <code>false</code> </td>
 * <td> <code>true</code>w?A???v`FbN ?s?B??A<code>true</code>O?
 * ?`FbN?B</td>
 * </tr>
 * </table>
 * 
 * @param bean
 *            ??IuWFNg
 * @param va
 *            StrutspValidatorAction
 * @param field
 *            tB?[hIuWFNg
 * @param errors
 *            ActionMessages ANVG?[
 * @param validator
 *            ValidatorCX^X
 * @param request
 *            HTTPNGXg
 * @return l? <code>true</code>
 */
public static boolean validateNumber(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        Validator validator, HttpServletRequest request) {

    // beannull?AG?[?O?o?Atruep?B
    if (bean == null) {
        log.error("bean is null.");
        return true;
    }
    // ???
    String integerLength = field.getVarValue("integerLength");
    // ???
    String scaleStr = field.getVarValue("scale");
    // ???v`FbN
    String isAccordedInteger = field.getVarValue("isAccordedInteger");
    // ???v`FbN
    String isAccordedScale = field.getVarValue("isAccordedScale");

    String value = null;
    if (isString(bean)) {
        value = (String) bean;
    } else {
        value = ValidatorUtils.getValueAsString(bean, field.getProperty());
    }
    // ?lnull?Atruep
    if (GenericValidator.isBlankOrNull(value)) {
        return true;
    }
    char[] chars = value.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (!isHankaku(chars[i])) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }
    // ???w???A??`FbN?s
    if (GenericValidator.isInt(integerLength)) {
        try {
            BigDecimal bd = new BigDecimal(value);
            // ???l?o
            BigInteger bi = bd.toBigInteger().abs();
            // ???
            int length = bi.toString().length();
            // validation.xmlw?
            int checkLength = Integer.valueOf(integerLength).intValue();
            // ?I?[o?Afalsep
            if (length > checkLength) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
            // vw
            if (isAccordedInteger != null && "true".equals(isAccordedInteger)) {
                // ?sv?Afalsep
                if (length != checkLength) {
                    errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                    return false;
                }
            }
        } catch (NumberFormatException nfe) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
    }

    // ???w???A??`FbN?s
    if (GenericValidator.isInt(scaleStr)) {
        int scale = 0;
        int checkScale = 0;
        try {
            BigDecimal bd = new BigDecimal(value);
            scale = bd.scale();
            // validation.xmlw?
            checkScale = Integer.valueOf(scaleStr).intValue();
        } catch (NumberFormatException e) {
            // ?l^?Afalsep
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // ?I?[o?Afalsep
        if (scale > checkScale) {
            errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
            return false;
        }
        // vw
        if (isAccordedScale != null && "true".equals(isAccordedScale)) {
            // ?sv?Afalsep
            if (scale != checkScale) {
                errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
                return false;
            }
        }
    }
    return true;
}

From source file:com.google.bitcoin.core.Block.java

/**
 * Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the
 * target is represented using a compact form. If this form decodes to a value that is out of bounds, an exception
 * is thrown.//from w  w  w  . j a va 2 s  .  com
 */
public BigInteger getDifficultyTargetAsInteger() throws VerificationException {
    maybeParseHeader();
    BigInteger target = Utils.decodeCompactBits(difficultyTarget);
    if (target.compareTo(BigInteger.valueOf(0)) <= 0 || target.compareTo(params.proofOfWorkLimit) > 0)
        throw new VerificationException("Difficulty target is bad: " + target.toString());
    return target;
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShardConsumerTest.java

/**
 * Test method for {@link ShardConsumer#consumeShard()} that starts from initial position of type AT_TIMESTAMP.
 *//* w  w w  .  j  a  v  a2  s  .  com*/
@Test
public final void testConsumeShardWithInitialPositionAtTimestamp() throws Exception {
    int numRecs = 7;
    BigInteger startSeqNum = BigInteger.ONE;
    Date timestamp = new Date(KinesisLocalFileDataCreator.STARTING_TIMESTAMP + 3);
    InitialPositionInStreamExtended atTimestamp = InitialPositionInStreamExtended
            .newInitialPositionAtTimestamp(timestamp);
    String streamShardId = "kinesis-0-0";
    String testConcurrencyToken = "testToken";
    File file = KinesisLocalFileDataCreator.generateTempDataFile(1, "kinesis-0-", numRecs, startSeqNum,
            "unitTestSCT002");

    IKinesisProxy fileBasedProxy = new KinesisLocalFileProxy(file.getAbsolutePath());

    final int maxRecords = 2;
    final int idleTimeMS = 0; // keep unit tests fast
    ICheckpoint checkpoint = new InMemoryCheckpointImpl(startSeqNum.toString());
    checkpoint.setCheckpoint(streamShardId, ExtendedSequenceNumber.AT_TIMESTAMP, testConcurrencyToken);
    when(leaseManager.getLease(anyString())).thenReturn(null);

    TestStreamlet processor = new TestStreamlet();

    StreamConfig streamConfig = new StreamConfig(fileBasedProxy, maxRecords, idleTimeMS,
            callProcessRecordsForEmptyRecordList, skipCheckpointValidationValue, atTimestamp);

    ShardInfo shardInfo = new ShardInfo(streamShardId, testConcurrencyToken, null,
            ExtendedSequenceNumber.TRIM_HORIZON);
    ShardConsumer consumer = new ShardConsumer(shardInfo, streamConfig, checkpoint, processor, leaseManager,
            parentShardPollIntervalMillis, cleanupLeasesOfCompletedShards, executorService, metricsFactory,
            taskBackoffTimeMillis,
            KinesisClientLibConfiguration.DEFAULT_SKIP_SHARD_SYNC_AT_STARTUP_IF_LEASES_EXIST);

    assertThat(consumer.getCurrentState(),
            is(equalTo(ConsumerStates.ShardConsumerState.WAITING_ON_PARENT_SHARDS)));
    consumer.consumeShard(); // check on parent shards
    Thread.sleep(50L);
    consumer.consumeShard(); // start initialization
    assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.INITIALIZING)));
    consumer.consumeShard(); // initialize
    Thread.sleep(50L);

    // We expect to process all records in numRecs calls
    for (int i = 0; i < numRecs;) {
        boolean newTaskSubmitted = consumer.consumeShard();
        if (newTaskSubmitted) {
            LOG.debug("New processing task was submitted, call # " + i);
            assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.PROCESSING)));
            // CHECKSTYLE:IGNORE ModifiedControlVariable FOR NEXT 1 LINES
            i += maxRecords;
        }
        Thread.sleep(50L);
    }

    assertThat(processor.getShutdownReason(), nullValue());
    consumer.beginShutdown();
    Thread.sleep(50L);
    assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.SHUTTING_DOWN)));
    consumer.beginShutdown();
    assertThat(consumer.getCurrentState(), is(equalTo(ConsumerStates.ShardConsumerState.SHUTDOWN_COMPLETE)));
    assertThat(processor.getShutdownReason(), is(equalTo(ShutdownReason.ZOMBIE)));

    executorService.shutdown();
    executorService.awaitTermination(60, TimeUnit.SECONDS);

    String iterator = fileBasedProxy.getIterator(streamShardId, timestamp);
    List<Record> expectedRecords = toUserRecords(fileBasedProxy.get(iterator, numRecs).getRecords());
    verifyConsumedRecords(expectedRecords, processor.getProcessedRecords());
    assertEquals(4, processor.getProcessedRecords().size());
    file.delete();
}

From source file:de.undercouch.bson4jackson.BsonGeneratorTest.java

@Test
public void generatePrimitives() throws Exception {
    Map<String, Object> data = new LinkedHashMap<String, Object>();
    data.put("Int32", 5);
    data.put("Boolean1", true);
    data.put("Boolean2", false);
    data.put("String", "Hello");
    data.put("Long", 1234L);
    data.put("Null", null);
    data.put("Float", 1234.1234f);
    data.put("Double", 5678.5678);

    //BigInteger that can be serialized as an Integer
    data.put("BigInt1", BigInteger.valueOf(Integer.MAX_VALUE));

    //BigInteger that can be serialized as a Long
    BigInteger bi2 = BigInteger.valueOf(Integer.MAX_VALUE).multiply(BigInteger.valueOf(2));
    data.put("BigInt2", bi2);

    //BigInteger that will be serialized as a String
    BigInteger bi3 = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(Long.MAX_VALUE));
    data.put("BigInt3", bi3);

    BSONObject obj = generateAndParse(data);

    assertEquals(5, obj.get("Int32"));
    assertEquals(true, obj.get("Boolean1"));
    assertEquals(false, obj.get("Boolean2"));
    assertEquals("Hello", obj.get("String"));
    assertEquals(1234L, obj.get("Long"));
    assertEquals(null, obj.get("Null"));
    assertEquals(1234.1234f, (Double) obj.get("Float"), 0.00001);
    assertEquals(5678.5678, (Double) obj.get("Double"), 0.00001);
    assertEquals(Integer.MAX_VALUE, obj.get("BigInt1"));
    assertEquals(Long.valueOf(Integer.MAX_VALUE) * 2L, obj.get("BigInt2"));
    assertEquals(bi3.toString(), obj.get("BigInt3"));
}

From source file:org.activiti.content.engine.impl.fs.FileSystemContentStorage.java

@Override
public ContentObject createContentObject(InputStream contentStream, Map<String, Object> metaData) {
    // Get hold of the next free ID to use
    BigInteger id = fetchNewId();
    File contentFile = new File(rootFolder, converter.getPathForId(id).getPath());
    long length = -1;
    try {//  www .  ja v a  2 s.  c  om
        length = IOUtils.copy(contentStream, new FileOutputStream(contentFile, false));
    } catch (FileNotFoundException e) {
        throw new ContentStorageException(
                "Content file was deleted or no longer accessible prior to writing: " + contentFile, e);
    } catch (IOException e) {
        throw new ContentStorageException("Error while writing content to file: " + contentFile, e);
    }

    if (length < 0) {
        // The file was larger than 2GB (max integer value), we need to get the
        // length from the file instead
        length = contentFile.length();
    }

    return new FileSystemContentObject(contentFile, id.toString(), length);
}

From source file:org.cesecore.certificates.certificate.CertificateCreateSessionBean.java

/** When no unique index is present in the database, we still try to enforce X.509 serial number per CA uniqueness. 
 * @throws CertificateCreateException if serial number already exists in database
 *//*from w ww  . ja  va2  s .  co m*/
private void assertSerialNumberForIssuerOk(final CA ca, final String issuerDN, final BigInteger serialNumber)
        throws CertificateSerialNumberException {
    if (ca.getCAType() == CAInfo.CATYPE_X509 && !isUniqueCertificateSerialNumberIndex()) {
        if (certificateStoreSession.findCertificateByIssuerAndSerno(issuerDN, serialNumber) != null) {
            final String msg = intres.getLocalizedMessage("createcert.cert_serial_number_already_in_database",
                    serialNumber.toString());
            log.info(msg);
            throw new CertificateSerialNumberException(msg);
        }
    }
}

From source file:org.codehaus.mojo.cassandra.AbstractCassandraMojo.java

/**
 * Generates the {@code cassandra.yaml} file.
 *
 * @param cassandraYaml the {@code cassandra.yaml} file.
 * @param data          The data directory.
 * @param commitlog     The commitlog directory.
 * @param savedCaches   The saved caches directory.
 * @param listenAddress The address to listen on for storage and other cassandra servers.
 * @param rpcAddress    The address to listen on for clients.
 * @param seeds         The seeds.//w  w w .j  a v  a2  s.c  o m
 * @throws IOException If something went wrong.
 */
private void createCassandraYaml(File cassandraYaml, File data, File commitlog, File savedCaches,
        String listenAddress, String rpcAddress, BigInteger initialToken, String[] seeds) throws IOException {
    String defaults = IOUtil.toString(getClass().getResourceAsStream("/cassandra.yaml"));
    StringBuilder config = new StringBuilder();
    config.append("data_file_directories:\n").append("    - ").append(data.getAbsolutePath()).append("\n");
    config.append("commitlog_directory: ").append(commitlog).append("\n");
    config.append("saved_caches_directory: ").append(savedCaches).append("\n");
    config.append("initial_token: ")
            .append(initialToken == null || "null".equals(initialToken) ? "" : initialToken.toString())
            .append("\n");
    config.append("listen_address: ").append(listenAddress).append("\n");
    config.append("storage_port: ").append(storagePort).append("\n");
    config.append("rpc_address: ").append(rpcAddress).append("\n");
    config.append("rpc_port: ").append(rpcPort).append("\n");
    config.append("native_transport_port: ").append(nativeTransportPort).append("\n");
    config.append("start_native_transport: ").append(startNativeTransport).append("\n");
    if (seeds != null) {
        config.append("seed_provider: ").append("\n");
        config.append("    - class_name: org.apache.cassandra.locator.SimpleSeedProvider").append("\n");
        config.append("      parameters:").append("\n");
        String sep = "          - seeds: \"";
        for (int i = 0; i < seeds.length; i++) {
            config.append(sep).append(seeds[i]);
            sep = ", ";
        }
        if (sep.length() == 2) {
            config.append("\"").append("\n");
        }
    }
    FileUtils.fileWrite(cassandraYaml.getAbsolutePath(),
            Utils.merge(Utils.merge(defaults, yaml), config.toString()));
}