Example usage for java.math BigInteger ONE

List of usage examples for java.math BigInteger ONE

Introduction

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

Prototype

BigInteger ONE

To view the source code for java.math BigInteger ONE.

Click Source Link

Document

The BigInteger constant one.

Usage

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsReadersTest.java

public JobExecution getJobExecution() {
    if (jobExecution == null) {
        final Map<String, JobParameter> map = new HashMap<String, JobParameter>();
        map.put("mantis.username", new JobParameter("toto"));
        map.put("mantis.password", new JobParameter("passwd"));

        final JobParameters jobParams = new JobParameters(map);
        jobExecution = MetaDataInstanceFactory.createJobExecution("testJob", 1L, 1L, jobParams);

        jobExecution.getExecutionContext().put("mantis.acess_level", BigInteger.TEN);
        jobExecution.getExecutionContext().put("mantis.loop.project_id", BigInteger.ONE);
    }/*from   ww  w.j a  va2s  .  c om*/

    return jobExecution;
}

From source file:com.offbynull.peernetic.common.identification.Id.java

/**
 * Subtracts two IDs. The limit of the IDs must match.
 * @param lhs left-hand side/*from w ww .  jav  a  2 s  .c  o m*/
 * @param rhs right-hand side
 * @return {@code lhs - rhs}, wrapped around limit if it goes below {@code 0}
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if the limit from {@code lhs} doesn't match the limit from {@code rhs}
 */
public static Id subtract(Id lhs, Id rhs) {
    Validate.notNull(lhs);
    Validate.notNull(rhs);
    Validate.isTrue(lhs.limit.equals(rhs.limit));

    BigInteger subtracted = lhs.data.subtract(rhs.data);
    if (subtracted.signum() == -1) {
        subtracted = subtracted.add(lhs.limit).add(BigInteger.ONE);
    }

    Id subtractedId = new Id(subtracted, lhs.limit);

    return subtractedId;
}

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

@Override
// Fire prepared request and return responses as IHttpRequestResponse
protected Integer doInBackground() throws Exception {
    int i = 0;//from  ww w  .j a v  a 2  s . c  om
    boolean solutionFound = false;

    this.c0 = BigInteger.ZERO;
    this.si = BigInteger.ZERO;
    this.m = null;
    this.blockSize = this.pubKey.getModulus().bitLength() / 8;

    this.httpService = this.requestResponse.getHttpService();

    // b computation
    int tmp = this.pubKey.getModulus().bitLength();
    while (tmp % 8 != 0) {
        tmp++;
    }
    tmp = ((tmp / 8) - 2) * 8;
    this.bigB = BigInteger.valueOf(2).pow(tmp);

    loggerInstance.log(getClass(), "B computed: " + this.bigB.toString(16), Logger.LogLevel.INFO);
    loggerInstance.log(getClass(), "Blocksize: " + blockSize + " bytes", Logger.LogLevel.INFO);

    String[] components = Decoder.getComponents(this.parameter.getJoseValue());

    encryptedKey = Base64.decodeBase64(components[1]);

    loggerInstance.log(getClass(), "Step 1: Blinding", Logger.LogLevel.INFO);

    if (this.msgIsPkcs) {
        loggerInstance.log(getClass(), "Step skipped --> " + "Message is considered as PKCS compliant.",
                Logger.LogLevel.INFO);
        this.s0 = BigInteger.ONE;
        this.c0 = new BigInteger(1, this.encryptedKey);
        this.m = new Interval[] { new Interval(BigInteger.valueOf(2).multiply(this.bigB),
                (BigInteger.valueOf(3).multiply(this.bigB)).subtract(BigInteger.ONE)) };
    } else {
        stepOne();
    }

    i++;

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

        loggerInstance.log(getClass(), "Step 2: Searching for PKCS conforming messages.", Logger.LogLevel.INFO);
        try {
            stepTwo(i);
        } catch (Exception e) {
            loggerInstance.log(getClass(), "Error in stepTwo: " + e.getMessage(), Logger.LogLevel.INFO);
        }

        loggerInstance.log(getClass(), "Step 3: Narrowing the set of soultions.", Logger.LogLevel.INFO);
        stepThree(i);

        loggerInstance.log(getClass(), "Step 4: Computing the solution.", Logger.LogLevel.INFO);
        solutionFound = stepFour();
        i++;
    }

    return 1;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Constructs a {@link FingerTable}. All fingers are initialized to
 * {@code base}.//  w w w  .  java 2s .  co  m
 *
 * @param basePtr base pointer
 * @throws NullPointerException if any arguments are {@code null}
 */
public FingerTable(InternalPointer basePtr) {
    Validate.notNull(basePtr);
    Id baseId = basePtr.getId();
    Validate.isTrue(IdUtils.isUseableId(baseId)); // make sure satisfies 2^n-1

    this.basePtr = basePtr;

    this.bitCount = IdUtils.getBitLength(baseId);
    byte[] limit = baseId.getLimitAsByteArray();

    table = new ArrayList<>(bitCount);
    for (int i = 0; i < bitCount; i++) {
        BigInteger data = BigInteger.ONE.shiftLeft(i);
        byte[] offsetIdRaw = data.toByteArray();
        Id offsetId = new Id(offsetIdRaw, limit);
        Id expectedId = Id.add(baseId, offsetId);

        InternalEntry te = new InternalEntry();
        te.expectedId = expectedId;
        te.pointer = basePtr;

        table.add(te);
    }
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsReadersTest.java

/**
 * Test the reader for the table mantis_category_table.
 *
 * @throws Exception/* w  w w  .j  a  v a 2  s .  c o m*/
 *          Technical Exception
 */
@Test
public void testProjectCategoriesReader() throws Exception {
    final String[] expected = new String[] { "categorie_1", "categorie_2" };

    Mockito.when(clientStub.mc_project_get_categories("toto", "passwd", BigInteger.ONE)).thenReturn(expected);

    projectCategoriesReader.setClientStub(clientStub);

    for (int i = 0; i <= expected.length; i++) {
        final String item = projectCategoriesReader.read();
        if (i < expected.length) {
            assertNotNull(item);
            assertEquals(expected[i], item);
        } else {
            assertNull(item);
        }
    }
}

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

/**
 * Creates a temp file (in default temp file location) with fake Kinesis data records.
 * Records will be put in all shards./*from   w w  w. j av  a  2  s.co  m*/
 * @param fileNamePrefix Prefix for the name of the temp file
 * @param shardList List of shards (we use the shardId and sequenceNumberRange fields)
 * @param numRecordsPerShard Num records per shard (the shard sequenceNumberRange should be large enough
 *     for us to allow these many records with some "holes")
 * @return File with stream data filled in
 * @throws IOException Thrown if there are issues creating/updating the file
 */
public static File generateTempDataFile(List<Shard> shardList, int numRecordsPerShard, String fileNamePrefix)
        throws IOException {
    File file = File.createTempFile(fileNamePrefix, FILE_NAME_SUFFIX);
    try (BufferedWriter fileWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
        ObjectMapper objectMapper = new ObjectMapper();
        String serializedShardList = objectMapper
                .writeValueAsString(new KinesisLocalFileProxy.SerializedShardList(shardList));
        fileWriter.write(serializedShardList);
        fileWriter.newLine();
        BigInteger sequenceNumberIncrement = new BigInteger("0");
        long timestamp = STARTING_TIMESTAMP;
        for (int i = 0; i < numRecordsPerShard; i++) {
            for (Shard shard : shardList) {
                BigInteger sequenceNumber = new BigInteger(
                        shard.getSequenceNumberRange().getStartingSequenceNumber())
                                .add(sequenceNumberIncrement);
                String endingSequenceNumber = shard.getSequenceNumberRange().getEndingSequenceNumber();
                BigInteger maxSequenceNumber = KinesisLocalFileProxy.MAX_SEQUENCE_NUMBER;
                if (endingSequenceNumber != null) {
                    maxSequenceNumber = new BigInteger(endingSequenceNumber);
                }
                if (maxSequenceNumber.compareTo(sequenceNumber) != 1) {
                    throw new IllegalArgumentException("Not enough space in shard");
                }
                String partitionKey = PARTITION_KEY_PREFIX + shard.getShardId()
                        + generateRandomString(PARTITION_KEY_LENGTH);
                String data = generateRandomString(DATA_LENGTH);

                // Allow few records to have the same timestamps (to mimic real life scenarios).
                timestamp = (i % DIVISOR == 0) ? timestamp : timestamp + 1;
                String line = shard.getShardId() + "," + sequenceNumber + "," + partitionKey + "," + data + ","
                        + timestamp;

                fileWriter.write(line);
                fileWriter.newLine();
                sequenceNumberIncrement = sequenceNumberIncrement.add(BigInteger.ONE);
                sequenceNumberIncrement = sequenceNumberIncrement
                        .add(new BigInteger(NUM_BITS, randomGenerator));
            }
        }
    }
    return file;
}

From source file:net.ripe.rpki.commons.crypto.util.Asn1Util.java

/**
 * IPAddress ::= BIT STRING//from www. jav  a 2s . c  om
 */
public static IpAddress parseIpAddress(IpResourceType type, ASN1Encodable der, boolean padWithOnes) {
    expect(der, DERBitString.class);
    DERBitString derBitString = (DERBitString) der;

    byte[] bytes = derBitString.getBytes();
    BigInteger value = new BigInteger(1, bytes);
    int usedBits = bytes.length * Byte.SIZE;
    int neededBits = type.getBitSize();
    int padBits = derBitString.getPadBits();

    if (padBits > 0) {
        byte lastByte = bytes[bytes.length - 1];
        byte mask = (byte) ((1 << padBits) - 1);
        Validate.isTrue((lastByte & mask) == 0, "pad bits not zero");
    }

    BigInteger upperBits = value.shiftLeft(neededBits - usedBits);
    BigInteger lowerBits = BigInteger.ZERO;
    if (padWithOnes) {
        lowerBits = BigInteger.ONE.shiftLeft(neededBits - usedBits + padBits).subtract(BigInteger.ONE);
    }

    return (IpAddress) type.fromBigInteger(upperBits.or(lowerBits));
}

From source file:com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesServiceTest.java

/**
 * Test method for {@link com.github.jrrdev.mantisbtsync.core.services.JdbcIssuesService#insertUserIfNotExists(biz.futureware.mantis.rpc.soap.client.AccountData, java.math.BigInteger)}.
 *///  www . java 2  s.c  om
@Test
public void testInsertUserIfNotExists() {
    final Operation op = insertInto("mantis_project_table").columns("id", "name").values(1, "project_1")
            .build();

    lauchOperation(op);

    final AccountData item = new AccountData();
    item.setId(BigInteger.valueOf(1));
    item.setName("new_user_1");

    dao.insertUserIfNotExists(item, BigInteger.ONE);

    final List<AccountData> list = getJdbcTemplate()
            .query("SELECT usr.id, usr.name" + " FROM mantis_user_table usr"
                    + " INNER JOIN mantis_project_user_list_table pul ON pul.user_id = usr.id"
                    + " WHERE pul.project_id = 1", new BeanPropertyRowMapper<AccountData>(AccountData.class));

    assertEquals(1, list.size());
    assertEquals(item, list.get(0));

    dao.insertUserIfNotExists(item, BigInteger.ONE);
}

From source file:strat.mining.stratum.proxy.worker.GetworkJobTemplate.java

public GetworkJobTemplate(String jobId, String version, String hashPrevBlock, String time, String bits,
        List<String> merkleBranches, String coinbase1, String coinbase2, String extranonce1,
        boolean noMidState) {
    this.jobId = jobId;
    this.noMidState = noMidState;
    this.merkleBranches = merkleBranches;
    this.coinbase1 = coinbase1;
    this.coinbase2 = coinbase2;
    this.extranonce1 = extranonce1;

    this.hashPrevBlock = BaseEncoding.base16().decode(hashPrevBlock);
    this.version = BaseEncoding.base16().decode(version);
    // Create the time BigInteger from the LittleEndian hex data.
    this.time = new AtomicBigInteger(BaseEncoding.base16().decode(time));
    this.bits = BaseEncoding.base16().decode(bits);
    this.nonce = DEFAULT_NONCE;

    this.lastDataTemplateUpdateTime = System.currentTimeMillis() / 1000;

    this.target = DEFAULT_TARGET;
    this.targetInteger = BigInteger.ONE;

    computeTemplateData();/*from   ww  w .jav a  2s  .c  om*/
}

From source file:org.limewire.mojito.util.DHTSizeEstimator.java

/**
 * Computes and returns the approximate DHT size based 
 * on the given List of Contacts./*from  w w w .j a  v a 2s .c  om*/
 */
public synchronized BigInteger computeSize(Collection<? extends Contact> nodes) {

    // Works only with more than two Nodes
    if (nodes.size() < MIN_NODE_COUNT) {
        // There's always us!
        return BigInteger.ONE.max(BigInteger.valueOf(nodes.size()));
    }

    // Get the Iterator. We assume the Contacts are sorted by
    // their xor distance!
    Iterator<? extends Contact> contacts = nodes.iterator();

    // See Azureus DHTControlImpl.estimateDHTSize()
    // Di = nearestId xor NodeIDi
    // Dc = sum(i * Di) / sum(i * i)
    // Size = 2**160 / Dc

    BigInteger sum1 = BigInteger.ZERO;
    BigInteger sum2 = BigInteger.ZERO;

    // The algorithm works relative to the ID space.
    KUID nearestId = contacts.next().getNodeID();

    // We start 1 because the nearest Node is the 0th item!
    for (int i = 1; contacts.hasNext(); i++) {
        Contact node = contacts.next();

        BigInteger distance = nearestId.xor(node.getNodeID()).toBigInteger();
        BigInteger j = BigInteger.valueOf(i);

        sum1 = sum1.add(j.multiply(distance));
        sum2 = sum2.add(j.pow(2));
    }

    BigInteger estimatedSize = BigInteger.ZERO;
    if (!sum1.equals(BigInteger.ZERO)) {
        estimatedSize = KUID.MAXIMUM.toBigInteger().multiply(sum2).divide(sum1);
    }

    // And there is always us!
    estimatedSize = BigInteger.ONE.max(estimatedSize);

    // Get the average of the local estimations
    BigInteger localSize = BigInteger.ZERO;
    localSizeHistory.add(estimatedSize);

    // Adjust the size of the List. The Setting is SIMPP-able
    // and may change!
    int maxLocalHistorySize = ContextSettings.MAX_LOCAL_HISTORY_SIZE.getValue();
    while (localSizeHistory.size() > maxLocalHistorySize && !localSizeHistory.isEmpty()) {
        localSizeHistory.remove(0);
    }

    if (!localSizeHistory.isEmpty()) {
        BigInteger localSizeSum = BigInteger.ZERO;
        for (BigInteger size : localSizeHistory) {
            localSizeSum = localSizeSum.add(size);
        }

        localSize = localSizeSum.divide(BigInteger.valueOf(localSizeHistory.size()));
    }

    // Get the combined average
    // S = (localEstimation + sum(remoteEstimation[i]))/count
    BigInteger combinedSize = localSize;
    if (ContextSettings.COUNT_REMOTE_SIZE.getValue()) {
        // Prune all duplicates and sort the values
        Set<BigInteger> remoteSizeSet = new TreeSet<BigInteger>(remoteSizeHistory);

        if (remoteSizeSet.size() >= 3) {
            BigInteger[] remote = remoteSizeSet.toArray(new BigInteger[0]);

            // Skip the smallest and largest values
            int count = 1;
            int skip = ContextSettings.SKIP_REMOTE_ESTIMATES.getValue();
            for (int i = skip; (skip >= 0) && (i < (remote.length - skip)); i++) {
                combinedSize = combinedSize.add(remote[i]);
                count++;
            }
            combinedSize = combinedSize.divide(BigInteger.valueOf(count));

            // Make sure we didn't exceed the MAXIMUM number as
            // we made an addition with the local estimation which
            // might be already 2**160 bit!
            combinedSize = combinedSize.min(MAXIMUM);
        }
    }

    // There is always us!
    return BigInteger.ONE.max(combinedSize);
}