Example usage for java.math BigInteger signum

List of usage examples for java.math BigInteger signum

Introduction

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

Prototype

int signum

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

Click Source Link

Document

The signum of this BigInteger: -1 for negative, 0 for zero, or 1 for positive.

Usage

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float ccnBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from   w ww .ja va2 s  .  c  o  m

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion))
                                        .toBigInteger();

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

private static Response invoke(UrlBuilder url, String method, String contentType,
        Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset,
        BigInteger length, Map<String, String> params) {
    try {/*from w  w w  . jav  a  2  s.c om*/
        // Log.d("URL", url.toString());

        // connect
        HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null || forceOutput);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT);

        // set content type
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        // set other headers
        if (httpHeaders != null) {
            for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                if (header.getValue() != null) {
                    for (String value : header.getValue()) {
                        conn.addRequestProperty(header.getKey(), value);
                    }
                }
            }
        }

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

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

            sb.append(tmpOffset.toString());
            sb.append("-");

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

            conn.setRequestProperty("Range", sb.toString());
        }

        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // add url form parameters
        if (params != null) {
            DataOutputStream ostream = null;
            OutputStream os = null;
            try {
                os = conn.getOutputStream();
                ostream = new DataOutputStream(os);

                Set<String> parameters = params.keySet();
                StringBuffer buf = new StringBuffer();

                int paramCount = 0;
                for (String it : parameters) {
                    String parameterName = it;
                    String parameterValue = (String) params.get(parameterName);

                    if (parameterValue != null) {
                        parameterValue = URLEncoder.encode(parameterValue, "UTF-8");
                        if (paramCount > 0) {
                            buf.append("&");
                        }
                        buf.append(parameterName);
                        buf.append("=");
                        buf.append(parameterValue);
                        ++paramCount;
                    }
                }
                ostream.writeBytes(buf.toString());
            } finally {
                if (ostream != null) {
                    ostream.flush();
                    ostream.close();
                }
                IOUtils.closeStream(os);
            }
        }

        // send data

        if (writer != null) {
            // conn.setChunkedStreamingMode((64 * 1024) - 1);
            OutputStream connOut = null;
            connOut = conn.getOutputStream();
            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:com.livinglogic.ul4.FunctionFormat.java

public static String call(BigInteger obj, String formatString, Locale locale) {
    IntegerFormat format = new IntegerFormat(formatString);

    if (locale == null)
        locale = Locale.ENGLISH;/*from   www  .j a  v  a2  s . com*/

    String output = null;

    boolean neg = obj.signum() < 0;
    if (neg)
        obj = obj.negate();

    switch (format.type) {
    case 'b':
        output = obj.toString(2);
        break;
    case 'c':
        if (neg || obj.compareTo(new BigInteger("65535")) > 0)
            throw new RuntimeException("value out of bounds for c format");
        output = Character.toString((char) obj.intValue());
        break;
    case 'd':
        output = obj.toString();
        break;
    case 'o':
        output = obj.toString(8);
        break;
    case 'x':
        output = obj.toString(16);
        break;
    case 'X':
        output = obj.toString(16).toUpperCase();
        break;
    case 'n':
        // FIXME: locale formatting
        output = obj.toString();
        break;
    }
    return formatIntegerString(output, neg, format);
}

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from   w w w . j a v  a  2s .  c  o  m*/

    try {

        Double btcRate = 0.0;
        boolean cryptsyValue = true;
        Object result = getCoinValueBTC();

        if (result == null) {
            result = getCoinValueBTC_BTER();
            cryptsyValue = false;
            if (result == null)
                return null;
        }
        btcRate = (Double) result;

        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                double rateForBTC = Double.parseDouble(rateStr);

                                rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", ".");

                                final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, rate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }

                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            //Add Bitcoin information
            if (rates.size() == 0) {
                int i = 0;
                i++;
            } else {
                rates.put(CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate(CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
                rates.put("m" + CoinDefinition.cryptsyMarketCurrency,
                        new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency,
                                GenericUtils.toNanoCoins(
                                        String.format("%.5f", btcRate * 1000).replace(",", "."), 0),
                                cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com"));
            }

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.google.uzaygezen.core.BigIntegerContent.java

public BigIntegerContent(BigInteger v) {
    Preconditions.checkArgument(v.signum() >= 0);
    this.value = v;
}

From source file:com.github.fge.jsonschema.format.draftv3.UTCMillisecAttribute.java

@Override
public void validate(final ProcessingReport report, final MessageBundle bundle, final FullData data)
        throws ProcessingException {
    final JsonNode instance = data.getInstance().getNode();

    BigInteger epoch = instance.bigIntegerValue();

    if (epoch.signum() == -1) {
        report.warn(newMsg(data, bundle, "warn.format.epoch.negative").putArgument("value", instance));
        return;//from  w w  w .  j  av  a 2s  .  co  m
    }

    epoch = epoch.divide(ONE_THOUSAND);

    if (epoch.bitLength() > EPOCH_BITLENGTH)
        report.warn(newMsg(data, bundle, "warn.format.epoch.overflow").putArgument("value", instance));
}

From source file:com.google.uzaygezen.core.ranges.BigIntegerRange.java

public BigIntegerRange(BigInteger start, BigInteger end) {
    Preconditions.checkArgument(end.compareTo(start) > 0 & start.signum() >= 0,
            "start must be nonnegative and less than end.");
    this.start = start;
    this.end = end;
}

From source file:edu.illinois.ncsa.domain.FileDescriptor.java

/**
 * @param md5sum//from  www.  j  av a  2 s . co  m
 *            the md5sum to set
 */
@JsonIgnore
public void setMd5sum(BigInteger md5sum) {
    if (md5sum.signum() < 0) {
        md5sum = new BigInteger(1, md5sum.toByteArray());
    }
    this.md5sum = md5sum.toString(16);
    if (this.md5sum.length() < 16) {
        this.md5sum = "00000000000000000000000000000000".substring(this.md5sum.length()) + this.md5sum;
    }
}

From source file:org.calrissian.mango.types.encoders.lexi.BigIntegerEncoder.java

@Override
public String encode(BigInteger value) {
    checkNotNull(value, "Null values are not allowed");

    byte[] bytes = value.toByteArray();
    int length = bytes.length;

    //Length is always positive so use it to encode the actual sign of the big int.
    if (value.signum() < 0)
        length = -length;//  ww w .  j  av  a2  s .c om

    return integerEncoder.encode(length) + new String(encodeHex(bytes));
}

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

/**
 * Constructs a {@link Id} from {@link BigInteger}s.
 * @param data id value//w w w.j  a va  2  s .c o  m
 * @param limit limit value
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if {@code data > limit}, or if either argument is {@code < 0}
 */
private Id(BigInteger data, BigInteger limit) {
    Validate.notNull(data);
    Validate.notNull(limit);
    Validate.isTrue(data.compareTo(limit) <= 0 && data.signum() >= 0 && limit.signum() >= 0);

    this.data = data;
    this.limit = limit;
}