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.alertlogic.aws.analytics.poc.StreamUtils.java

/**
 * Split a shard by dividing the hash key space in half.
 *
 * @param streamName Name of the stream that contains the shard to split.
 * @param shardId The id of the shard to split.
 *
 * @throws IllegalArgumentException When either streamName or shardId are null or empty.
 * @throws LimitExceededException Shard limit for the account has been reached.
 * @throws ResourceNotFoundException The stream or shard cannot be found.
 * @throws InvalidArgumentException If the shard is closed and no eligible for splitting.
 * @throws AmazonClientException Error communicating with Amazon Kinesis.
 *
 *//*from   w  w w .  j  a  v a2  s  .  co  m*/
public void splitShardEvenly(String streamName, String shardId) throws LimitExceededException,
        ResourceNotFoundException, AmazonClientException, InvalidArgumentException, IllegalArgumentException {
    if (streamName == null || streamName.isEmpty()) {
        throw new IllegalArgumentException("stream name is required");
    }
    if (shardId == null || shardId.isEmpty()) {
        throw new IllegalArgumentException("shard id is required");
    }

    DescribeStreamResult result = kinesis.describeStream(streamName);
    StreamDescription description = result.getStreamDescription();

    // Find the shard we want to split
    Shard shardToSplit = null;
    for (Shard shard : description.getShards()) {
        if (shardId.equals(shard.getShardId())) {
            shardToSplit = shard;
            break;
        }
    }

    if (shardToSplit == null) {
        throw new ResourceNotFoundException(
                "Could not find shard with id '" + shardId + "' in stream '" + streamName + "'");
    }

    // Check if the shard is still open. Open shards do not have an ending sequence number.
    if (shardToSplit.getSequenceNumberRange().getEndingSequenceNumber() != null) {
        throw new InvalidArgumentException("Shard is CLOSED and is not eligible for splitting");
    }

    // Calculate the median hash key to use as the new starting hash key for the shard.
    BigInteger startingHashKey = new BigInteger(shardToSplit.getHashKeyRange().getStartingHashKey());
    BigInteger endingHashKey = new BigInteger(shardToSplit.getHashKeyRange().getEndingHashKey());
    BigInteger[] medianHashKey = startingHashKey.add(endingHashKey).divideAndRemainder(new BigInteger("2"));
    BigInteger newStartingHashKey = medianHashKey[0];
    if (!BigInteger.ZERO.equals(medianHashKey[1])) {
        // In order to more evenly distributed the new hash key ranges across the new shards we will "round up" to
        // the next integer when our current hash key range is not evenly divisible by 2.
        newStartingHashKey = newStartingHashKey.add(BigInteger.ONE);
    }

    // Submit the split shard request
    kinesis.splitShard(streamName, shardId, newStartingHashKey.toString());
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getEqualAreaPartitions() {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize);
    BigDecimal bdkmerend = new BigDecimal(kmerend);
    // moves between x (0~1) y (0~1)
    // sum of area (0.5)
    double kmerArea = 0.5;
    double sliceArea = kmerArea / this.numPartitions;

    // we think triangle is horizontally flipped so calc get easier.
    double x1 = 0;

    List<BigInteger> widths = new ArrayList<BigInteger>();
    BigInteger widthSum = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        // x2*x2 = 2*sliceArea + x1*x1
        double temp = (2 * sliceArea) + (x1 * x1);
        double x2 = Math.sqrt(temp);

        BigDecimal bdx1 = BigDecimal.valueOf(x1);
        BigDecimal bdx2 = BigDecimal.valueOf(x2);

        // if i increases, bdw will be decreased
        BigDecimal bdw = bdx2.subtract(bdx1);

        BigInteger bw = bdw.multiply(bdkmerend).toBigInteger();
        if (bw.compareTo(BigInteger.ZERO) <= 0) {
            bw = BigInteger.ONE;
        }//from www  . ja  v  a 2 s. c om

        if (widthSum.add(bw).compareTo(kmerend) > 0) {
            bw = kmerend.subtract(widthSum);
        }

        if (i == this.numPartitions - 1) {
            // last case
            if (widthSum.add(bw).compareTo(kmerend) < 0) {
                bw = kmerend.subtract(widthSum);
            }
        }

        // save it
        widths.add(bw);
        widthSum = widthSum.add(bw);

        x1 = x2;
    }

    BigInteger cur_begin = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        BigInteger slice_width = widths.get(this.numPartitions - 1 - i);

        BigInteger slice_begin = cur_begin;

        if (slice_begin.add(slice_width).compareTo(kmerend) > 0) {
            slice_width = kmerend.subtract(slice_begin);
        }

        BigInteger slice_end = cur_begin.add(slice_width).subtract(BigInteger.ONE);

        KmerRangePartition slice = new KmerRangePartition(this.kmerSize, this.numPartitions, i, slice_width,
                slice_begin, slice_end);
        partitions[i] = slice;

        cur_begin = cur_begin.add(slice_width);
    }

    return partitions;
}

From source file:org.tdmx.lib.zone.service.ChannelAuthorizationServiceRepositoryUnitTest.java

@Test
public void testModify() throws Exception {
    ChannelAuthorization ca = data.getDomains().get(0).getAuths().get(0);
    ChannelAuthorization storedCA = channelAuthorizationService.findByChannel(zone,
            ca.getDomain().getDomainName(), ca.getOrigin(), ca.getDestination());
    assertNotNull(storedCA);/*  w  w w .j  a  v  a  2  s  .  c o m*/
    storedCA.getUndeliveredBuffer().setHighMarkBytes(BigInteger.TEN);
    storedCA.getUndeliveredBuffer().setLowMarkBytes(BigInteger.ONE);
    storedCA.getUnsentBuffer().setHighMarkBytes(BigInteger.TEN);
    storedCA.getUnsentBuffer().setLowMarkBytes(BigInteger.ONE);
    channelAuthorizationService.createOrUpdate(storedCA);

    ChannelAuthorization modifiedCA = channelAuthorizationService.findByChannel(zone,
            ca.getDomain().getDomainName(), ca.getOrigin(), ca.getDestination());
    assertNotNull(modifiedCA);
    assertEquals(storedCA.getUndeliveredBuffer().getHighMarkBytes(),
            modifiedCA.getUndeliveredBuffer().getHighMarkBytes());
    assertEquals(storedCA.getUndeliveredBuffer().getLowMarkBytes(),
            modifiedCA.getUndeliveredBuffer().getLowMarkBytes());
    assertEquals(storedCA.getUnsentBuffer().getHighMarkBytes(),
            modifiedCA.getUnsentBuffer().getHighMarkBytes());
    assertEquals(storedCA.getUnsentBuffer().getLowMarkBytes(), modifiedCA.getUnsentBuffer().getLowMarkBytes());

}

From source file:org.owasp.jbrofuzz.core.FuzzerBigInteger.java

/**
 * <p>This method should not be trusted or used in the conventional
 * way that an iterator requires remove to be implemented.</p>
 * /*from w ww  . j a va  2s .  c  o  m*/
 * <p>Instead, during fuzzing, remove() can be called to
 * step back to the previous element.</p>
 * 
 * <p>This need is typical, in replay scenarios where something
 * worth investigating has been discovered and a quick, step
 * back step forward is executed.</p>
 * 
 * @author subere@uncon.org
 * @version 2.4
 * @since 2.4
 */
public void remove() {

    cValue = cValue.subtract(BigInteger.ONE);

}

From source file:com.google.uzaygezen.core.hbase.HBaseQueryTest.java

public Map<Pow2LengthBitSetRange, NodeValue<BigIntegerContent>> createRolledupCache(MockHTable table,
        MultiDimensionalSpec spec, SpaceFillingCurve sfc, int cacheSize) throws IOException {
    int[] elementLengths = Ints.toArray(new HilbertIndexMasks(sfc.getSpec()).cardinalities());
    BitVector[] path = new BitVector[elementLengths.length];
    for (int i = 0; i < path.length; ++i) {
        path[i] = BitVectorFactories.OPTIMAL.apply(elementLengths[path.length - i - 1]);
    }/*  ww  w  . j ava2  s.c  o  m*/
    StreamingRollup<BitVector, BigIntegerContent> rollup = BoundedRollup
            .create(new BigIntegerContent(BigInteger.ZERO), cacheSize);
    Scan fullScan = new Scan();
    ResultScanner scanner = table.getScanner(fullScan);
    BitVector hilbertIndex = BitVectorFactories.OPTIMAL.apply(spec.sumBitsPerDimension());
    for (Result row : scanner) {
        hilbertIndex.copyFromBigEndian(row.getRow());
        for (int i = 0; i < path.length; ++i) {
            path[i] = path[i].clone();
        }
        BitVectorMath.split(hilbertIndex, path);
        // We should say the exact number of times. Saying one is correct, but
        // suboptimal.
        BigIntegerContent v = new BigIntegerContent(BigInteger.ONE);
        rollup.feedRow(Iterators.<BitVector>forArray(path), v);
    }
    MapNode<BitVector, BigIntegerContent> rolledupTree = rollup.finish();
    Pow2LengthBitSetRangeFactory<BigIntegerContent> factory = Pow2LengthBitSetRangeFactory
            .create(Ints.asList(elementLengths));
    Map<Pow2LengthBitSetRange, NodeValue<BigIntegerContent>> rolledupMap = factory.apply(rolledupTree);
    return rolledupMap;
}

From source file:password.pwm.config.stored.ConfigurationReader.java

public void saveConfiguration(final StoredConfigurationImpl storedConfiguration,
        final PwmApplication pwmApplication, final SessionLabel sessionLabel)
        throws IOException, PwmUnrecoverableException, PwmOperationalException {
    File backupDirectory = null;//from ww w .j a v a  2  s  . c  o m
    int backupRotations = 0;
    if (pwmApplication != null) {
        final Configuration configuration = new Configuration(storedConfiguration);
        final String backupDirSetting = configuration.readAppProperty(AppProperty.BACKUP_LOCATION);
        if (backupDirSetting != null && backupDirSetting.length() > 0) {
            final File pwmPath = pwmApplication.getPwmEnvironment().getApplicationPath();
            backupDirectory = FileSystemUtility.figureFilepath(backupDirSetting, pwmPath);
        }
        backupRotations = Integer.parseInt(configuration.readAppProperty(AppProperty.BACKUP_CONFIG_COUNT));
    }

    { // increment the config epoch
        String epochStrValue = storedConfiguration.readConfigProperty(ConfigurationProperty.CONFIG_EPOCH);
        try {
            final BigInteger epochValue = epochStrValue == null || epochStrValue.length() < 0 ? BigInteger.ZERO
                    : new BigInteger(epochStrValue);
            epochStrValue = epochValue.add(BigInteger.ONE).toString();
        } catch (Exception e) {
            LOGGER.error(sessionLabel,
                    "error trying to parse previous config epoch property: " + e.getMessage());
            epochStrValue = "0";
        }
        storedConfiguration.writeConfigProperty(ConfigurationProperty.CONFIG_EPOCH, epochStrValue);
    }

    if (backupDirectory != null && !backupDirectory.exists()) {
        if (!backupDirectory.mkdirs()) {
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN,
                    "unable to create backup directory structure '" + backupDirectory.toString() + "'"));
        }
    }

    try {
        final File tempWriteFile = new File(configFile.getAbsoluteFile() + ".new");
        LOGGER.info(sessionLabel, "beginning write to configuration file " + tempWriteFile);
        saveInProgress = true;

        storedConfiguration.toXml(new FileOutputStream(tempWriteFile, false));
        LOGGER.info("saved configuration " + JsonUtil.serialize(storedConfiguration.toJsonDebugObject()));
        if (pwmApplication != null) {
            final String actualChecksum = storedConfiguration.settingChecksum();
            pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.CONFIG_HASH, actualChecksum);
        }

        LOGGER.trace(
                "renaming file " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath());
        try {
            Files.move(tempWriteFile.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.ATOMIC_MOVE);
        } catch (Exception e) {
            final String errorMsg = "unable to rename temporary save file from "
                    + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath() + "; error: "
                    + e.getMessage();
            throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
        }

        if (backupDirectory != null) {
            final String configFileName = configFile.getName();
            final String backupFilePath = backupDirectory.getAbsolutePath() + File.separatorChar
                    + configFileName + "-backup";
            final File backupFile = new File(backupFilePath);
            FileSystemUtility.rotateBackups(backupFile, backupRotations);
            storedConfiguration.toXml(new FileOutputStream(backupFile, false));
        }
    } finally {
        saveInProgress = false;
    }
}

From source file:spade.filter.DropRepeatEdges.java

@Override
public void putEdge(AbstractEdge incomingEdge) {
    /*/*  w  w w  . j  a  v  a2s  .  c  om*/
     * Checks if the edge is the same as the last one (between these two vertices) based 
     * on the aggregated value.
     */
    if (incomingEdge != null) {
        AbstractVertex parentVertex = incomingEdge.getParentVertex();
        AbstractVertex childVertex = incomingEdge.getChildVertex();
        if (parentVertex != null && childVertex != null) {
            String newDropValue = getDropByValue(incomingEdge, dropBy);
            boolean put = false;
            String parentHash = parentVertex.bigHashCode();
            String childHash = childVertex.bigHashCode();
            HashMap<String, String> vertex2LastDropValueMap = vertex2VertexAndLastDropByValue.get(parentHash);
            if (vertex2LastDropValueMap == null) {
                vertex2LastDropValueMap = new HashMap<String, String>();
                vertex2VertexAndLastDropByValue.put(parentHash, vertex2LastDropValueMap);
                vertex2LastDropValueMap.put(childHash, newDropValue);
                put = true;
            } else {
                String existingDropValue = vertex2LastDropValueMap.get(childHash);
                if (!StringUtils.equals(existingDropValue, newDropValue)) {
                    vertex2LastDropValueMap.put(childHash, newDropValue);
                    put = true;
                }
            }

            if (put) {
                super.putInNextFilter(incomingEdge);
            } else {
                totalDropped = totalDropped.add(BigInteger.ONE);
            }
        }
    }
}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        final Output writer, final BindingSession session, BigInteger offset, BigInteger length) {
    int respCode = -1;

    try {/*from   w  w  w .  ja  va  2  s.  co  m*/
        // log before connect
        if (LOG.isDebugEnabled()) {
            LOG.debug("Session {}: {} {}", session.getSessionId(), method, url);
        }

        // get HTTP client object from session
        DefaultHttpClient httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT);
        if (httpclient == null) {
            session.writeLock();
            try {
                httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT);
                if (httpclient == null) {
                    httpclient = createHttpClient(url, session);
                    session.put(HTTP_CLIENT, httpclient, true);
                }
            } finally {
                session.writeUnlock();
            }
        }

        HttpRequestBase request = null;

        if ("GET".equals(method)) {
            request = new HttpGet(url.toString());
        } else if ("POST".equals(method)) {
            request = new HttpPost(url.toString());
        } else if ("PUT".equals(method)) {
            request = new HttpPut(url.toString());
        } else if ("DELETE".equals(method)) {
            request = new HttpDelete(url.toString());
        } else {
            throw new CmisRuntimeException("Invalid HTTP method!");
        }

        // set content type
        if (contentType != null) {
            request.setHeader("Content-Type", contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }

        // authenticate
        AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session);
        if (authProvider != null) {
            Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString());
            if (httpHeaders != null) {
                for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                    if (header.getKey() != null && isNotEmpty(header.getValue())) {
                        String key = header.getKey();
                        if (key.equalsIgnoreCase("user-agent")) {
                            request.setHeader("User-Agent", header.getValue().get(0));
                        } else {
                            for (String value : header.getValue()) {
                                if (value != null) {
                                    request.addHeader(key, value);
                                }
                            }
                        }
                    }
                }
            }
        }

        // range
        if ((offset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((offset == null) || (offset.signum() == -1)) {
                offset = BigInteger.ZERO;
            }

            sb.append(offset.toString());
            sb.append('-');

            if ((length != null) && (length.signum() == 1)) {
                sb.append(offset.add(length.subtract(BigInteger.ONE)).toString());
            }

            request.setHeader("Range", sb.toString());
        }

        // compression
        Object compression = session.get(SessionParameter.COMPRESSION);
        if ((compression != null) && Boolean.parseBoolean(compression.toString())) {
            request.setHeader("Accept-Encoding", "gzip,deflate");
        }

        // locale
        if (session.get(CmisBindingsHelper.ACCEPT_LANGUAGE) instanceof String) {
            request.setHeader("Accept-Language", session.get(CmisBindingsHelper.ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            final boolean clientCompressionFlag = (clientCompression != null)
                    && Boolean.parseBoolean(clientCompression.toString());
            if (clientCompressionFlag) {
                request.setHeader("Content-Encoding", "gzip");
            }

            AbstractHttpEntity streamEntity = new AbstractHttpEntity() {
                @Override
                public boolean isChunked() {
                    return true;
                }

                @Override
                public boolean isRepeatable() {
                    return false;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }

                @Override
                public boolean isStreaming() {
                    return false;
                }

                @Override
                public InputStream getContent() throws IOException {
                    throw new UnsupportedOperationException();
                }

                @Override
                public void writeTo(final OutputStream outstream) throws IOException {
                    OutputStream connOut = null;

                    if (clientCompressionFlag) {
                        connOut = new GZIPOutputStream(outstream, 4096);
                    } else {
                        connOut = outstream;
                    }

                    OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
                    try {
                        writer.write(out);
                    } catch (IOException ioe) {
                        throw ioe;
                    } catch (Exception e) {
                        throw new IOException(e);
                    }
                    out.flush();

                    if (connOut instanceof GZIPOutputStream) {
                        ((GZIPOutputStream) connOut).finish();
                    }
                }
            };
            ((HttpEntityEnclosingRequestBase) request).setEntity(streamEntity);
        }

        // connect
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        // get stream, if present
        respCode = response.getStatusLine().getStatusCode();
        InputStream inputStream = null;
        InputStream errorStream = null;

        if ((respCode == 200) || (respCode == 201) || (respCode == 203) || (respCode == 206)) {
            if (entity != null) {
                inputStream = entity.getContent();
            } else {
                inputStream = new ByteArrayInputStream(new byte[0]);
            }
        } else {
            if (entity != null) {
                errorStream = entity.getContent();
            } else {
                errorStream = new ByteArrayInputStream(new byte[0]);
            }
        }

        // collect headers
        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
        for (Header header : response.getAllHeaders()) {
            List<String> values = responseHeaders.get(header.getName());
            if (values == null) {
                values = new ArrayList<String>();
                responseHeaders.put(header.getName(), values);
            }
            values.add(header.getValue());
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace("Session {}: {} {} > Headers: {}", session.getSessionId(), method, url,
                    responseHeaders.toString());
        }

        // forward response HTTP headers
        if (authProvider != null) {
            authProvider.putResponseHeaders(url.toString(), respCode, responseHeaders);
        }

        // get the response
        return new Response(respCode, response.getStatusLine().getReasonPhrase(), responseHeaders, inputStream,
                errorStream);
    } catch (Exception e) {
        String status = (respCode > 0 ? " (HTTP status code " + respCode + ")" : "");
        throw new CmisConnectionException("Cannot access \"" + url + "\"" + status + ": " + e.getMessage(), e);
    }
}

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

/**
 * Test the reader for the table mantis_project_version_table.
 *
 * @throws Exception//from   ww  w .j  a  va 2  s  . c o  m
 *          Technical Exception
 */
@Test
public void testProjectVersionsReader() throws Exception {
    final ProjectVersionData[] expected = new ProjectVersionData[] {
            new ProjectVersionData(BigInteger.ONE, "version_1", BigInteger.ONE, null, null, null, null),
            new ProjectVersionData(BigInteger.valueOf(2), "version_2", BigInteger.ONE, null, null, null,
                    null) };

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

    projectVersionsReader.setClientStub(clientStub);

    for (int i = 0; i <= expected.length; i++) {
        final ProjectVersionData item = projectVersionsReader.read();
        if (i < expected.length) {
            assertNotNull(item);
            assertEquals(expected[i].getId(), item.getId());
            assertEquals(expected[i].getName(), item.getName());
            assertEquals(expected[i].getProject_id(), item.getProject_id());
        } else {
            assertNull(item);
        }
    }
}

From source file:com.netflix.imfutility.cpl._2013.Cpl2013ContextBuilderStrategy.java

private void processResource(BaseResourceType resource) {
    if (!(resource instanceof TrackFileResourceType)) {
        return;//  w w w .j a  v  a 2  s  .c om
    }
    TrackFileResourceType trackFileResource = (TrackFileResourceType) resource;

    BigInteger repeatCount = trackFileResource.getRepeatCount() != null ? trackFileResource.getRepeatCount()
            : BigInteger.ONE;

    for (long i = 0; i < repeatCount.longValue(); i++) {
        processResourceRepeat(trackFileResource, i);
    }
}