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.langerhans.wallet.ui.SendCoinsFragment.java

private void handleGo() {
    state = State.PREPARATION;/* w ww  .  ja v  a 2  s  .  c  om*/
    updateView();

    // final payment intent
    final PaymentIntent finalPaymentIntent = paymentIntent.mergeWithEditedValues(
            amountCalculatorLink.getAmount(), validatedAddress != null ? validatedAddress.address : null);
    final BigInteger finalAmount = finalPaymentIntent.getAmount();

    // prepare send request
    final SendRequest sendRequest = finalPaymentIntent.toSendRequest();
    final Address returnAddress = WalletUtils.pickOldestKey(wallet).toAddress(Constants.NETWORK_PARAMETERS);
    sendRequest.changeAddress = returnAddress;
    sendRequest.emptyWallet = paymentIntent.mayEditAmount()
            && finalAmount.equals(wallet.getBalance(BalanceType.AVAILABLE));

    //Emptying a wallet with less than 2 DOGE can't be possible due to min fee 2 DOGE of such a tx.
    /*        if (amount.compareTo(BigInteger.valueOf(200000000)) < 0 && sendRequest.emptyWallet)
            {
    AlertDialog.Builder bld = new AlertDialog.Builder(activity);
        bld.setTitle(R.string.send_coins_error_msg);
        bld.setMessage(R.string.send_coins_error_desc);
        bld.setNeutralButton(activity.getResources().getString(android.R.string.ok), null);
        bld.setCancelable(false);
        bld.create().show();
    state = State.FAILED;
    updateView();
    return;
            }*/

    new SendCoinsOfflineTask(wallet, backgroundHandler) {
        @Override
        protected void onSuccess(final Transaction transaction) {
            sentTransaction = transaction;

            state = State.SENDING;
            updateView();

            sentTransaction.getConfidence().addEventListener(sentTransactionConfidenceListener);

            final Payment payment = PaymentProtocol.createPaymentMessage(sentTransaction, returnAddress,
                    finalAmount, null, paymentIntent.payeeData);

            directPay(payment);

            application.broadcastTransaction(sentTransaction);

            final ComponentName callingActivity = activity.getCallingActivity();
            if (callingActivity != null) {
                log.info("returning result to calling activity: {}", callingActivity.flattenToString());

                final Intent result = new Intent();
                BitcoinIntegration.transactionHashToResult(result, sentTransaction.getHashAsString());
                if (paymentIntent.standard == Standard.BIP70)
                    BitcoinIntegration.paymentToResult(result, payment.toByteArray());
                activity.setResult(Activity.RESULT_OK, result);
            }
        }

        private void directPay(final Payment payment) {
            if (directPaymentEnableView.isChecked()) {
                final DirectPaymentTask.ResultCallback callback = new DirectPaymentTask.ResultCallback() {
                    @Override
                    public void onResult(final boolean ack) {
                        directPaymentAck = ack;

                        if (state == State.SENDING)
                            state = State.SENT;

                        updateView();
                    }

                    @Override
                    public void onFail(final int messageResId, final Object... messageArgs) {
                        final DialogBuilder dialog = DialogBuilder.warn(activity,
                                R.string.send_coins_fragment_direct_payment_failed_title);
                        dialog.setMessage(paymentIntent.paymentUrl + "\n" + getString(messageResId, messageArgs)
                                + "\n\n" + getString(R.string.send_coins_fragment_direct_payment_failed_msg));
                        dialog.setPositiveButton(R.string.button_retry, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                directPay(payment);
                            }
                        });
                        dialog.setNegativeButton(R.string.button_dismiss, null);
                        dialog.show();
                    }
                };

                if (paymentIntent.isHttpPaymentUrl()) {
                    new DirectPaymentTask.HttpPaymentTask(backgroundHandler, callback, paymentIntent.paymentUrl,
                            application.httpUserAgent()).send(payment);
                } else if (paymentIntent.isBluetoothPaymentUrl() && bluetoothAdapter != null
                        && bluetoothAdapter.isEnabled()) {
                    new DirectPaymentTask.BluetoothPaymentTask(backgroundHandler, callback, bluetoothAdapter,
                            Bluetooth.getBluetoothMac(paymentIntent.paymentUrl)).send(payment);
                }
            }
        }

        @Override
        protected void onInsufficientMoney(@Nullable final BigInteger missing) {
            state = State.INPUT;
            updateView();

            final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED);
            final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE);
            final BigInteger pending = estimated.subtract(available);

            final int btcShift = config.getBtcShift();
            final int btcPrecision = config.getBtcMaxPrecision();
            final String btcPrefix = config.getBtcPrefix();

            final DialogBuilder dialog = DialogBuilder.warn(activity,
                    R.string.send_coins_fragment_insufficient_money_title);
            final StringBuilder msg = new StringBuilder();
            if (missing != null)
                msg.append(String.format(getString(R.string.send_coins_fragment_insufficient_money_msg1),
                        btcPrefix + ' ' + GenericUtils.formatValue(missing, btcPrecision, btcShift)))
                        .append("\n\n");
            if (pending.signum() > 0)
                msg.append(getString(R.string.send_coins_fragment_pending,
                        GenericUtils.formatValue(pending, btcPrecision, btcShift))).append("\n\n");
            msg.append(getString(R.string.send_coins_fragment_insufficient_money_msg2));
            dialog.setMessage(msg);
            dialog.setPositiveButton(R.string.send_coins_options_empty, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    handleEmpty();
                }
            });
            dialog.setNegativeButton(R.string.button_cancel, null);
            dialog.show();
        }

        @Override
        protected void onFailure() {
            state = State.FAILED;
            updateView();

            activity.longToast(R.string.send_coins_error_msg);
        }
    }.sendCoinsOffline(sendRequest); // send asynchronously
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

/**
 * Converts NSS key ID from a signed, variable-length hexadecimal number
 * into a 20 byte array, which will be identical to the original byte array.
 *///from   w  w w .  j a v a  2s . c  om
public static byte[] decodeKeyID(String id) {

    BigInteger value = new BigInteger(id, 16);
    byte[] array = value.toByteArray();

    if (array.length > KEY_ID_LENGTH) {
        throw new IllegalArgumentException("Unable to decode Key ID: " + id);
    }

    if (array.length < KEY_ID_LENGTH) {

        // extend the array with most significant bit
        byte[] tmp = array;
        array = new byte[KEY_ID_LENGTH];

        // calculate the extension
        int p = KEY_ID_LENGTH - tmp.length;

        // create filler byte based op the most significant bit
        byte b = (byte) (value.signum() >= 0 ? 0x00 : 0xff);

        // fill the extension with the filler byte
        Arrays.fill(array, 0, p, b);

        // copy the original array
        System.arraycopy(tmp, 0, array, p, tmp.length);
    }

    return array;
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this / value)}.
 *
 * @param value the value by which this {@link Rational} is to be divided.
 * @return The division result./*  www  .ja v  a2  s .c o  m*/
 */
@Nullable
public Rational divide(@Nullable BigInteger value) {
    if (value == null) {
        return null;
    }
    if (isNaN()) {
        return NaN;
    }

    if (value.signum() == 0) {
        if (signum() == 0) {
            return NaN;
        }
        return signum() > 0 ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
    }

    if (signum() == 0 || isInfinite() || BigInteger.ONE.equals(value.abs())) {
        return value.signum() < 0 ? negate() : this;
    }

    // Keep the sign in the numerator and the denominator positive
    if (value.signum() < 0) {
        return valueOf(reducedNumerator.negate(), reducedDenominator.multiply(value.negate()));
    }
    return valueOf(reducedNumerator, reducedDenominator.multiply(value));
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this + value)}.
 *
 * @param value the value to be added to this {@link Rational}.
 * @return The addition result.//w w w. jav a  2s .co m
 */
@Nullable
public Rational add(@Nullable BigInteger value) {
    if (value == null) {
        return null;
    }

    if (isNaN()) {
        return NaN;
    }
    if (isInfinite() || value.signum() == 0) {
        return this;
    }

    if (BigInteger.ONE.equals(denominator)) {
        return valueOf(numerator.add(value), denominator);
    }
    return valueOf(numerator.add(value.multiply(denominator)), denominator);
}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this * value)}.
 *
 * @param value the value to be multiplied by this {@link Rational}.
 * @return The multiplication result.//from w ww .  jav a2s  .c om
 */
@Nullable
public Rational multiply(@Nullable BigInteger value) {
    if (value == null) {
        return null;
    }
    if (isNaN()) {
        return NaN;
    }
    if (isInfinite()) {
        if (value.signum() == 0) {
            return NaN; // Infinity by zero
        }
        return numerator.signum() == value.signum() ? POSITIVE_INFINITY : NEGATIVE_INFINITY;
    }
    if (value.signum() == 0) {
        return ZERO;
    }

    if (BigInteger.ONE.equals(value.abs())) {
        return value.signum() < 0 ? negate() : this;
    }

    return valueOf(reducedNumerator.multiply(value), reducedDenominator);
}

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

protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers,
        Output writer, BindingSession session, BigInteger offset, BigInteger length) {
    try {//from   w w w .ja  v a  2s  .com
        // log before connect
        //Log.d("URL", url.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug(method + " " + url);
        }

        // connect
        HttpURLConnection conn = getHttpURLConnection(new URL(url.toString()));
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT);

        // timeouts
        int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1);
        if (connectTimeout >= 0) {
            conn.setConnectTimeout(connectTimeout);
        }

        int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1);
        if (readTimeout >= 0) {
            conn.setReadTimeout(readTimeout);
        }

        // set content type
        if (contentType != null) {
            conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType);
        }
        // set other headers
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                conn.addRequestProperty(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.getValue() != null) {
                        for (String value : header.getValue()) {
                            conn.addRequestProperty(header.getKey(), value);
                        }
                    }
                }
            }

            if (conn instanceof HttpsURLConnection) {
                SSLSocketFactory sf = authProvider.getSSLSocketFactory();
                if (sf != null) {
                    ((HttpsURLConnection) conn).setSSLSocketFactory(sf);
                }

                HostnameVerifier hv = authProvider.getHostnameVerifier();
                if (hv != null) {
                    ((HttpsURLConnection) conn).setHostnameVerifier(hv);
                }
            }
        }

        // 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());
            }

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

        // compression
        Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING);
        if (compression == null) {
            conn.setRequestProperty("Accept-Encoding", "");
        } else {
            Boolean compressionValue;
            try {
                compressionValue = Boolean.parseBoolean(compression.toString());
                if (compressionValue) {
                    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                } else {
                    conn.setRequestProperty("Accept-Encoding", "");
                }
            } catch (Exception e) {
                conn.setRequestProperty("Accept-Encoding", compression.toString());
            }
        }

        // locale
        if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String
                && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) {
            conn.setRequestProperty("Accept-Language",
                    session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString());
        }

        // send data
        if (writer != null) {
            Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT);
            if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) {
                conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked");
                conn.setChunkedStreamingMode(0);
            }

            conn.setConnectTimeout(900000);

            OutputStream connOut = null;

            Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION);
            if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip");
                connOut = new GZIPOutputStream(conn.getOutputStream(), 4096);
            } else {
                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();
        }

        // log after connect
        if (LOG.isTraceEnabled()) {
            LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields());
        }

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

        // 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: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  . j  a v  a2 s .c  o 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:io.warp10.continuum.gts.GTSHelper.java

/**
 * Convert a GTS Id packed as a BigInteger into an array of bytes
 * containing classId/labelsId in big endian representation
 * @param bi// w  w w .j a  v a  2 s.  c om
 * @return
 */
public static byte[] unpackGTSId(BigInteger bi) {
    byte[] bytes = bi.toByteArray();

    if (bytes.length < 16) {
        byte[] tmp = new byte[16];
        if (bi.signum() < 0) {
            Arrays.fill(tmp, (byte) 0xff);
        }
        System.arraycopy(bytes, 0, tmp, tmp.length - bytes.length, bytes.length);
        return tmp;
    } else {
        return bytes;
    }
}