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:com.lenovo.tensorhusky.common.utils.ProcfsBasedProcessTree.java

private BigInteger getTotalProcessJiffies() {
    BigInteger totalStime = BigInteger.ZERO;
    long totalUtime = 0;
    for (ProcessInfo p : processTree.values()) {
        if (p != null) {
            totalUtime += p.getUtime();// ww w . j  a  va  2s  .co  m
            totalStime = totalStime.add(p.getStime());
        }
    }
    return totalStime.add(BigInteger.valueOf(totalUtime));
}

From source file:io.instacount.client.InstacountClientTest.java

@Test
public void testIncrement_NoPayload() throws InstacountClientException {
    final String counterName = UUID.randomUUID().toString();
    client.incrementShardedCounter(counterName);
    assertThat(client.getShardedCounter(counterName).getShardedCounter().getCount(),
            is(BigInteger.valueOf(1L)));
}

From source file:org.alfresco.jive.cmis.dao.AlfrescoNavigationDAOImpl.java

/**
 * {@inheritDoc}/*  w w  w .  j a va2s .  c  o  m*/
 */
@Override
public Document updateDocument(RemoteDocument doc, String fileName, String contentType, long size,
        InputStream data) throws CmisConstraintException {
    Document document = null;
    Session session = getSession();

    try {
        document = (Document) session.getObject(doc);

        // Properties
        Map<String, Object> properties = new HashMap<String, Object>();

        AlfrescoDocument alfDoc = (AlfrescoDocument) document;

        if (!alfDoc.hasAspect("P:jive:socialized")) {
            alfDoc.addAspect("P:jive:socialized");
        }

        properties.put(PropertyIds.NAME, fileName);
        document.updateProperties(properties);
        // Content
        ContentStream cs = new ContentStreamImpl(fileName, BigInteger.valueOf(size), contentType, data);
        document.setContentStream(cs, true);

    } finally {
        try {
            data.close();
        } catch (IOException ex) {
            // Do nothing
        }
    }
    return document;
}

From source file:com.trsst.Common.java

public static byte[] fromBase58(String s) {
    try {//  ww w.j  ava2  s . c  om
        boolean leading = true;
        int lz = 0;
        BigInteger b = BigInteger.ZERO;
        for (char c : s.toCharArray()) {
            if (leading && c == '1') {
                ++lz;
            } else {
                leading = false;
                b = b.multiply(BigInteger.valueOf(58));
                b = b.add(BigInteger.valueOf(r58[c]));
            }
        }
        byte[] encoded = b.toByteArray();
        if (encoded[0] == 0) {
            if (lz > 0) {
                --lz;
            } else {
                byte[] e = new byte[encoded.length - 1];
                System.arraycopy(encoded, 1, e, 0, e.length);
                encoded = e;
            }
        }
        byte[] result = new byte[encoded.length + lz];
        System.arraycopy(encoded, 0, result, lz, encoded.length);

        return result;
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new IllegalArgumentException("Invalid character in address");
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.nuxeo.ecm.core.opencmis.impl.NuxeoSessionTestCase.java

@Test
public void testContentStream() throws Exception {
    Document file = (Document) session.getObjectByPath("/testfolder1/testfile1");

    // check ETag header
    if (isAtomPub || isBrowser) {
        RepositoryInfo ri = session.getRepositoryInfo();
        String uri = ri.getThinClientUri() + ri.getId() + "/";
        uri += isAtomPub ? "content?id=" : "root?objectId=";
        uri += file.getId();/*from   www  .  ja v a  2  s.  c  o m*/
        String eTag = file.getPropertyValue("nuxeo:contentStreamDigest");
        String encoding = Base64.encodeBytes(new String(USERNAME + ":" + PASSWORD).getBytes());
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        request.setHeader("Authorization", "Basic " + encoding);
        request.setHeader("If-None-Match", eTag);
        try {
            HttpResponse response = client.execute(request);
            assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    // get stream
    ContentStream cs = file.getContentStream();
    assertNotNull(cs);
    assertEquals("text/plain", cs.getMimeType());
    assertEquals("testfile.txt", cs.getFileName());
    if (!(isAtomPub || isBrowser)) {
        // TODO fix AtomPub/Browser case where the length is unknown (streaming)
        assertEquals(Helper.FILE1_CONTENT.length(), cs.getLength());
    }
    assertEquals(Helper.FILE1_CONTENT, Helper.read(cs.getStream(), "UTF-8"));

    // set stream
    // TODO convenience constructors for ContentStreamImpl
    byte[] streamBytes = STREAM_CONTENT.getBytes("UTF-8");
    ByteArrayInputStream stream = new ByteArrayInputStream(streamBytes);
    cs = new ContentStreamImpl("foo.txt", BigInteger.valueOf(streamBytes.length), "text/plain; charset=UTF-8",
            stream);
    file.setContentStream(cs, true);

    // refetch stream
    file = (Document) session.getObject(file);
    cs = file.getContentStream();
    assertNotNull(cs);
    // AtomPub lowercases charset -> TODO proper mime type comparison
    String mimeType = cs.getMimeType().toLowerCase().replace(" ", "");
    assertEquals("text/plain;charset=utf-8", mimeType);
    // TODO fix AtomPub case where the filename is null
    assertEquals("foo.txt", cs.getFileName());
    if (!(isAtomPub || isBrowser)) {
        // TODO fix AtomPub/Browser case where the length is unknown (streaming)
        assertEquals(streamBytes.length, cs.getLength());
    }
    assertEquals(STREAM_CONTENT, Helper.read(cs.getStream(), "UTF-8"));

    // delete
    file.deleteContentStream();
    file.refresh();
    assertEquals(null, file.getContentStream());
}

From source file:com.cisco.dvbu.ps.deploytool.services.TriggerManagerImpl.java

private TriggerConditionChoiceType populateTriggerCondition(String conditionType,
        AttributeList conditionAttributes, Schedule conditionSchedule, String triggerId,
        TriggerScheduleListType scheduleList) {

    TriggerConditionChoiceType tcct = new TriggerConditionChoiceType();
    TriggerScheduleType tst = null;/* ww w.jav  a 2s  .c  o m*/

    if (conditionType.equals(TriggerConditionTypeValidationList.USER_DEFINED.name())) {
        TriggerConditionUserDefinedEventType triggerCondition = new TriggerConditionUserDefinedEventType();

        if (logger.isDebugEnabled()) {
            logger.debug("Processing User Defined Event Condition");
        }

        for (Attribute attr : conditionAttributes.getAttribute()) {
            if (attr.getName().equals("NAME")) {
                triggerCondition.setEventName(attr.getValue());
            }
        }
        tcct.setUserDefinedEvent(triggerCondition);
    }

    if (conditionType.equals(TriggerConditionTypeValidationList.JMS.name())) {
        TriggerConditionJmsEventType triggerCondition = new TriggerConditionJmsEventType();

        if (logger.isDebugEnabled()) {
            logger.debug("Processing JMS Condition");
        }

        for (Attribute attr : conditionAttributes.getAttribute()) {
            if (attr.getName().equals("JMS_DESTINATION")) {
                triggerCondition.setDestination(attr.getValue());
            }
            if (attr.getName().equals("JMS_SELECTOR")) {
                triggerCondition.setSelector(attr.getValue());
            }
            if (attr.getName().equals("JMS_CONNECTOR")) {
                triggerCondition.setConnector(attr.getValue());
            }
        }
        tcct.setJmsEvent(triggerCondition);
    }

    if (conditionType.equals(TriggerConditionTypeValidationList.SYSTEM_EVENT.name())) {
        TriggerConditionSystemEventType triggerCondition = new TriggerConditionSystemEventType();

        if (logger.isDebugEnabled()) {
            logger.debug("Processing System Event Condition");
        }

        for (Attribute attr : conditionAttributes.getAttribute()) {
            if (attr.getName().equals("EVENT_NAME")) {
                String value = attr.getValue();
                triggerCondition.setEventName(TriggerConditionSystemEventValidationList.fromValue(value));
            }
        }
        tcct.setSystemEvent(triggerCondition);
    }

    if (conditionType.equals(TriggerConditionTypeValidationList.TIMER.name())) {
        TriggerConditionTimerEventType triggerCondition = new TriggerConditionTimerEventType();
        scheduleCount++;

        if (logger.isDebugEnabled()) {
            logger.debug("Processing Timer Event Condition");
        }

        triggerCondition.setScheduleId(triggerId + "-SCH-" + scheduleCount);
        tcct.setTimerEvent(triggerCondition);

        tst = new TriggerScheduleType();
        logger.debug("Step 1: set scheduleId");
        tst.setScheduleId(triggerId + "-SCH-" + scheduleCount);

        logger.debug("Step 2: set mode");
        if (conditionSchedule.getMode().name().equalsIgnoreCase("NONE")) {
            tst.setMode(TriggerModeValidationList.NONE);
            // Set the startTime
            tst.setStartTime(conditionSchedule.getStartTime());
        } else {
            tst.setMode(TriggerModeValidationList.PERIODIC);

            logger.debug("Step 3: set condition schedule startTime, period and count");

            // Set the startTime
            tst.setStartTime(conditionSchedule.getStartTime());

            // Set the period and count
            if (conditionSchedule.getPeriod() == null) {
                logger.debug("Step 4: set period and count for INTERVAL (Period is null)");
                if (conditionSchedule.getInterval() != null) {
                    tst.setPeriod(TriggerPeriodValidationList.fromValue("MINUTE"));
                    tst.setCount(BigInteger.valueOf(conditionSchedule.getInterval()));
                }
            } else {
                logger.debug("Step 5: set period and count for CALENDAR (Period is NOT NULL)");
                tst.setPeriod(TriggerPeriodValidationList.fromValue(conditionSchedule.getPeriod().name()));
                tst.setCount(BigInteger.valueOf(conditionSchedule.getCount()));
            }
        }

        logger.debug("Step 6: set fromTimeInADay");
        if (conditionSchedule.getFromTimeInADay() == null) {
            logger.debug("FromTimeInADay is null");
            tst.setFromTimeInADay(BigInteger.valueOf(-1));
        } else {
            logger.debug("FromTimeInADay is NOT null");
            tst.setFromTimeInADay(BigInteger.valueOf(conditionSchedule.getFromTimeInADay()));
        }

        logger.debug("Step 7: set endTimeInADay");
        if (conditionSchedule.getEndTimeInADay() == null) {
            logger.debug("EndTimeInADay is null");
            tst.setEndTimeInADay(BigInteger.valueOf(-1));
        } else {
            logger.debug("EndTimeInADay is NOT null");
            tst.setEndTimeInADay(BigInteger.valueOf(conditionSchedule.getEndTimeInADay()));
        }

        logger.debug("Step 8: set recurringDay");
        if (conditionSchedule.getRecurringDay() == null) {
            logger.debug("RecurringDay is null");
            tst.setRecurringDay(BigInteger.valueOf(-1));
        } else {
            logger.debug("RecurringDay is NOT null");
            tst.setRecurringDay(BigInteger.valueOf(conditionSchedule.getRecurringDay()));
        }

        logger.debug("Step 9: set isCluster");
        if (conditionSchedule.isIsCluster() == null) {
            logger.debug("IsCluster is null");
            tst.setIsCluster(Boolean.TRUE);
        } else {
            logger.debug("IsCluster is NOT null");
            tst.setIsCluster(conditionSchedule.isIsCluster());
        }

        logger.debug("Step 10: add schedule to list");
        scheduleList.getSchedule().add(tst);
    }

    return tcct;
}

From source file:io.s4.util.LoadGenerator.java

@SuppressWarnings("unchecked")
private Object makeSettableValue(Property property, Object value) {
    String propertyName = property.getName();
    Class propertyType = property.getType();

    if (propertyType.isArray()) {
        if (!(value instanceof JSONArray)) {
            System.err.println("Type mismatch for field " + propertyName);
            return null;
        }/*w w  w  .  j a v a  2 s  .  com*/
        System.out.println("Is array!");
        return makeArray(property, (JSONArray) value);
    } else if (property.isList()) {
        if (!(value instanceof JSONArray)) {
            System.err.println("Type mismatch for field " + propertyName);
            return null;
        }
        return makeList(property, (JSONArray) value);
    } else if (propertyType.isPrimitive()) {
        if (!(value instanceof Number || value instanceof Boolean)) {
            System.err.println("Type mismatch for field " + propertyName
                    + "; expected number or boolean, found " + value.getClass());
            return null;
        }
        return value; // hmm... does this work?
    } else if (propertyType.equals(String.class)) {
        if (!(value instanceof String)) {
            System.err.println(
                    "Type mismatch for field " + propertyName + "; expected String, found " + value.getClass());
            return null;
        }
        return value;
    } else if (property.isNumber()) {
        if (!(value instanceof Integer || value instanceof Long || value instanceof Float
                || value instanceof Double || value instanceof BigDecimal || value instanceof BigInteger)) {
            return null;
        }

        Number adjustedValue = (Number) value;
        if (propertyType.equals(Long.class) && !(value instanceof Long)) {
            adjustedValue = new Long(((Number) value).longValue());
        } else if (propertyType.equals(Integer.class) && !(value instanceof Integer)) {
            adjustedValue = new Integer(((Number) value).intValue());
        } else if (propertyType.equals(Double.class) && !(value instanceof Double)) {
            adjustedValue = new Double(((Number) value).doubleValue());
        } else if (propertyType.equals(Float.class) && !(value instanceof Float)) {
            adjustedValue = new Float(((Number) value).floatValue());
        } else if (propertyType.equals(BigDecimal.class)) {
            adjustedValue = new BigDecimal(((Number) value).longValue());
        } else if (propertyType.equals(BigInteger.class)) {
            adjustedValue = BigInteger.valueOf(((Number) value).longValue());
        }
        return adjustedValue;
    } else if (value instanceof JSONObject) {
        return makeRecord((JSONObject) value, property.getSchema());
    }

    return null;
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

protected boolean isInRange(Number value, String stringValue, Class toType) {
    Number bigValue = null;//from   w  w  w.j a  va  2 s. co  m
    Number lowerBound = null;
    Number upperBound = null;

    try {
        if (double.class == toType || Double.class == toType) {
            bigValue = new BigDecimal(stringValue);
            // Double.MIN_VALUE is the smallest positive non-zero number
            lowerBound = BigDecimal.valueOf(Double.MAX_VALUE).negate();
            upperBound = BigDecimal.valueOf(Double.MAX_VALUE);
        } else if (float.class == toType || Float.class == toType) {
            bigValue = new BigDecimal(stringValue);
            // Float.MIN_VALUE is the smallest positive non-zero number
            lowerBound = BigDecimal.valueOf(Float.MAX_VALUE).negate();
            upperBound = BigDecimal.valueOf(Float.MAX_VALUE);
        } else if (byte.class == toType || Byte.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Byte.MIN_VALUE);
            upperBound = BigInteger.valueOf(Byte.MAX_VALUE);
        } else if (char.class == toType || Character.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Character.MIN_VALUE);
            upperBound = BigInteger.valueOf(Character.MAX_VALUE);
        } else if (short.class == toType || Short.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Short.MIN_VALUE);
            upperBound = BigInteger.valueOf(Short.MAX_VALUE);
        } else if (int.class == toType || Integer.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Integer.MIN_VALUE);
            upperBound = BigInteger.valueOf(Integer.MAX_VALUE);
        } else if (long.class == toType || Long.class == toType) {
            bigValue = new BigInteger(stringValue);
            lowerBound = BigInteger.valueOf(Long.MIN_VALUE);
            upperBound = BigInteger.valueOf(Long.MAX_VALUE);
        }
    } catch (NumberFormatException e) {
        //shoult it fail here? BigInteger doesnt seem to be so nice parsing numbers as NumberFormat
        return true;
    }

    return ((Comparable) bigValue).compareTo(lowerBound) >= 0
            && ((Comparable) bigValue).compareTo(upperBound) <= 0;
}

From source file:ch.bfh.evoting.verifier.Verifier.java

/**
 * Return all the important data of the participant that should be used in the hash used in ZK proofs
 * @param p participant//from w  w  w.  j  av  a 2s. c  om
 * @return all the important data of the participant that should be used in the hash used in ZK proofs
 */
private static Tuple prepareParticipantOtherInput(XMLParticipant p) {
    Element index = N.getInstance().getElement(BigInteger.valueOf(p.getProtocolParticipantIndex()));
    ByteArrayElement proverId = ByteArrayMonoid.getInstance().getElement(p.getUniqueId().getBytes());

    return Tuple.getInstance(index, proverId);
}

From source file:io.instacount.appengine.counter.service.ShardedCounterServiceImpl.java

/**
 * The cache will expire after {@code defaultCounterCountExpiration} seconds, so the counter will be accurate after
 * a minute because it performs a load from the datastore.
 *
 * @param counterName//from w w  w.  j av a2  s  .c om
 * @param skipCache A boolean that allows a caller to skip memcache when retrieving a counter. Set to {@code true}
 *            to load the counter and all of its shards directly from the Datastore. Set to {@code false} to attempt
 *            to load the count from memcache, with fallback to the datastore.
 * @return
 */
@Override
public Optional<Counter> getCounter(final String counterName, final boolean skipCache) {
    Preconditions.checkNotNull(counterName);

    // This method always load the CounterData from the Datastore (or its Objectify cache), but sometimes returns
    // the
    // cached count value.

    // //////////////
    // ShortCircuit: If nothing is present in the datastore.
    // //////////////
    final Optional<CounterData> optCounterData = this.getCounterData(counterName);
    if (!optCounterData.isPresent()) {
        logger.log(Level.FINEST, String.format("Counter '%s' was not found in hte Datastore!", counterName));
        return Optional.absent();
    }

    final CounterData counterData = optCounterData.get();

    // //////////////
    // ShortCircuit: If the counter is in an indeterminate state, then return its count as 0.
    // //////////////
    if (this.counterStatusYieldsIndeterminateCount(counterData.getCounterStatus())) {
        logger.log(Level.FINEST,
                String.format("Counter '%s' was in an indeterminate state.  Returning 0!", counterName));
        return Optional.of(new CounterBuilder(counterData).withCount(BigInteger.ZERO).build());
    }

    // //////////////
    // ShortCircuit: If the counter was found in memcache.
    // //////////////
    final String memCacheKey = this.assembleCounterKeyforMemcache(counterName);
    if (!skipCache) {
        final BigInteger cachedCounterCount = this.memcacheSafeGet(memCacheKey);
        if (cachedCounterCount != null) {
            // /////////////////////////////////////
            // The count was found in memcache, so return it.
            // /////////////////////////////////////
            logger.log(Level.FINEST, String.format("Cache Hit for Counter Named '%s': value=%s", counterName,
                    cachedCounterCount));
            return Optional.of(new CounterBuilder(counterData).withCount(cachedCounterCount).build());
        } else {
            logger.log(Level.FINE,
                    String.format(
                            "Cache Miss for CounterData Named '%s': value='%s'.  Checking Datastore instead!",
                            counterName, cachedCounterCount));
        }
    }

    // /////////////////////////////////////
    // skipCache was true or the count was NOT found in memcache!
    // /////////////////////////////////////

    // Note: No Need to clear the Objectify session cache here because it will be cleared automatically and
    // repopulated upon every request.

    logger.log(Level.FINE,
            String.format("Aggregating counts from '%s' CounterDataShards for CounterData named '%s'!",
                    counterData.getNumShards(), counterData.getName()));

    // ///////////////////
    // Assemble a List of CounterShardData Keys to retrieve in parallel!
    final List<Key<CounterShardData>> keysToLoad = Lists.newArrayList();
    for (int i = 0; i < counterData.getNumShards(); i++) {
        final Key<CounterShardData> counterShardKey = CounterShardData.key(counterData.getTypedKey(), i);
        keysToLoad.add(counterShardKey);
    }

    long sum = 0;

    // For added performance, we could spawn multiple threads to wait for each value to be returned from the
    // DataStore, and then aggregate that way. However, the simple summation below is not very expensive, so
    // creating multiple threads to get each value would probably be overkill. Just let objectify do this for
    // us. Even though we have to wait for all entities to return before summation begins, the summation is a quick
    // in-memory operation with a relatively small number of shards, so parallelizing it would likely not increase
    // performance.

    // No TX - get is Strongly consistent by default, and we will exceed the TX limit for high-shard-count
    // counters if we try to do this in a TX.
    final Map<Key<CounterShardData>, CounterShardData> counterShardDatasMap = ObjectifyService.ofy()
            .transactionless().load().keys(keysToLoad);
    final Collection<CounterShardData> counterShardDatas = counterShardDatasMap.values();
    for (CounterShardData counterShardData : counterShardDatas) {
        if (counterShardData != null) {
            sum += counterShardData.getCount();
        }
    }

    logger.log(Level.FINE,
            String.format(
                    "The Datastore is reporting a count of %s for CounterData '%s' count.  Resetting memcache "
                            + "count to %s for this counter name.",
                    sum, counterData.getName(), sum));

    final BigInteger bdSum = BigInteger.valueOf(sum);
    try {
        // This method will only get here if there was nothing in Memcache, or if the caller requested to skip
        // reading the Counter count from memcache. In these cases, the value in memcache should always be replaced.
        memcacheService.put(memCacheKey, bdSum, config.getDefaultCounterCountExpiration(),
                SetPolicy.SET_ALWAYS);
    } catch (MemcacheServiceException mse) {
        // Do nothing. The method will still return even though memcache is not available.
    }

    return Optional.of(new CounterBuilder(counterData).withCount(bdSum).build());
}