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:org.multibit.viewsystem.swing.action.SendAssetConfirmAction.java

/**
 * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog.
 *///from w  w w  .j a va  2 s .  co m
@Override
public void actionPerformed(ActionEvent e) {
    if (abort()) {
        return;
    }

    //        SendAssetConfirmDialog sendAssetConfirmDialog = null;
    AssetValidationErrorDialog validationErrorDialog = null;

    try {
        String sendAddress = dataProvider.getAddress();
        String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT);
        String sendMessage = null;
        boolean canSendMessage = false;

        final int assetId = dataProvider.getAssetId();
        String assetAmount = dataProvider.getAssetAmount();
        boolean isSenderPays = dataProvider.isSenderPays();

        /* Is there a payment charge?  If yes, the asset amount will change */
        CSAsset asset = bitcoinController.getModel().getActiveWallet().CS.getAsset(assetId);
        CoinSparkGenesis genesis = asset.getGenesis();
        BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, assetAmount);
        // Was there any rounding, which the user did not see because they clicked on send first,
        // without losing focus to any other widget which corrects field?
        String typedAmount = dataProvider.getAssetAmountText();
        BigDecimal bd1 = new BigDecimal(typedAmount);
        BigDecimal bd2 = new BigDecimal(assetAmount);
        bd1 = bd1.stripTrailingZeros();
        bd2 = bd2.stripTrailingZeros();
        if (bd1.equals(bd2) == false) {
            String displayUnit = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, BigInteger.ONE);
            String s = "The smallest transactable unit is " + displayUnit
                    + ", so we have rounded the sum down.\nPlease confirm the final amount and click 'Send' again.";
            JOptionPane.showMessageDialog(mainFrame, s);
            return;
        }
        // End rounding check/warning

        long desiredRawUnits = assetAmountRawUnits.longValue();
        short chargeBasisPoints = genesis.getChargeBasisPoints();
        long rawFlatChargeAmount = genesis.getChargeFlat();
        boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0);
        if (chargeExists) {
            if (isSenderPays) {
                long x = genesis.calcGross(desiredRawUnits);
                assetAmountRawUnits = new BigInteger(String.valueOf(x));
            } else {
                // We don't have to do anything if recipient pays, just send gross amount.
                // calcNet() returns what the recipient will receive, but it's not what we send.
                //          long x = genesis.calcNet(desiredRawUnits);
                //          assetAmountRawUnits = new BigInteger(String.valueOf(x));          
            }
        }

        // Todo: Allow invalid assets to be sent even if spendable balance is 0
        //if (CSMiscUtils.canSendInvalidAsset(bitcoinController) 
        final AssetValidator validator = new AssetValidator(super.bitcoinController);
        if (validator.validate(sendAddress, sendAmount, assetId, assetAmountRawUnits.toString())) {
            /* CoinSpark START */
            CoinSparkPaymentRef paymentRef = null;

            // We have already validated that the coinspark address and underlying bitcoin are good
            // and that the transfer flag is set on the coinspark address.  We just want the actual
            // underlying bitcoin address to send assets to, which is used to create SendRequest object.
            CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress);
            String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa);
            sendAddress = btcAddress;

            // Does a payment ref exist?
            int flags = csa.getAddressFlags();
            if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
                paymentRef = csa.getPaymentRef();
                log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString());
            }

            // Messages - can send message and BTC to CoinSpark address, without any assets.
            sendMessage = dataProvider.getMessage();
            canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0;
            /* CoinSpark END */

            // Create a SendRequest.
            Address sendAddressObject;

            sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress);
            //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));

            //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) {
            //BigInteger assetAmountRawUnits = new BigInteger(assetAmount);
            BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount);

            final SendRequest sendRequest = SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetId,
                    assetAmountRawUnits, 1);
            sendRequest.ensureMinRequiredFee = true;
            sendRequest.fee = BigInteger.ZERO;
            sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

            // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.

            // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
            if (paymentRef != null && paymentRef.getRef() != 0) {
                sendRequest.setPaymentRef(paymentRef);
            }

            // Send a message if the address will take it and message is not empty
            boolean willSendMessage = false;
            if (canSendMessage) {
                boolean isEmptyMessage = false;
                if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) {
                    isEmptyMessage = true;
                }
                if (!isEmptyMessage) {
                    willSendMessage = true;
                    //int numParts = 1;
                    CoinSparkMessagePart[] parts = {
                            CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) };
                    String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController);
                    sendRequest.setMessage(parts, serverURLs);

                    log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs));
                    log.debug(">>>> parts[0] = " + parts[0]);
                    log.debug(">>>> parts[0].fileName = " + parts[0].fileName);
                    log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType);
                    log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8"));
                    //String message = "Hello, the time is now..." + DateTime.now().toString();
                    //      parts[2].fileName = imagePath;
                    //      parts[2].mimeType = "image/png";
                    //      byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
                    //      parts[2].content = imageBytes;

                }
            }

            //
            // When sending a message, show a modal dialog.
            // CompleteTX now occurs in background thread so UI does not block
            // when "Send" is clicked with widget updates frozen.
            //

            // Show dialog with indeterminate progress bar
            final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame,
                    "SparkBit", "Contacting message delivery servers...");
            // Dialog is made visible after futures have been set up

            ListeningExecutorService service = MoreExecutors
                    .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10));
            ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() {
                public Boolean call() throws Exception {
                    try {
                        // Complete it (which works out the fee) but do not sign it yet.
                        log.debug("Just about to complete the tx (and calculate the fee)...");
                        bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                        log.debug("The fee after completing the transaction was " + sendRequest.fee);

                    } catch (Exception e) {
                        throw e;
                    }
                    return true;
                }
            });

            final BigInteger myAssetAmountRawUnits = assetAmountRawUnits;

            Futures.addCallback(future, new FutureCallback<Boolean>() {
                public void onSuccess(Boolean b) {

                    // There is enough money.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            SendAssetConfirmDialog mySendAssetConfirmDialog = new SendAssetConfirmDialog(
                                    bitcoinController, mainFrame, sendRequest, assetId, myAssetAmountRawUnits,
                                    validator);
                            mySendAssetConfirmDialog.setVisible(true);
                        }
                    });

                }

                public void onFailure(Throwable thrown) {
                    final String failureReason = thrown.getMessage();
                    final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode;
                    final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException;
                    // There is not enough money.
                    // TODO setup validation parameters accordingly so that it displays ok.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            if (isCSException) {
                                JOptionPane
                                        .showMessageDialog(mainFrame,
                                                "SparkBit is unable to proceed with this transaction:\n\n"
                                                        + failureReason,
                                                "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                            } else if (isInsufficientMoney) {
                                // Try to show a human friendly message, need to pass the missing satoshis from failure reason.
                                try {
                                    String numberOnly = failureReason.replaceAll("[^0-9]", "");
                                    BigInteger needed = new BigInteger(numberOnly);
                                    JOptionPane.showMessageDialog(mainFrame,
                                            "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require "
                                                    + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.",
                                            "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                                } catch (NumberFormatException e) {
                                    AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog(
                                            bitcoinController, mainFrame, sendRequest, true, validator);
                                    myValidationErrorDialog.setVisible(true);
                                }
                            } else {

                                AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog(
                                        bitcoinController, mainFrame, sendRequest, true, validator);
                                myValidationErrorDialog.setVisible(true);
                            }
                        }
                    });
                }
            });

            // Show message server dialog only if we are going to send
            if (willSendMessage) {
                dialog.setVisible(true);
            }

            /*      
                            // Complete it (which works out the fee) but do not sign it yet.
                            log.debug("Just about to complete the tx (and calculate the fee)...");
                            boolean completedOk;
                            try {
            bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                              completedOk = true;
                              log.debug("The fee after completing the transaction was " + sendRequest.fee);
                            } catch (InsufficientMoneyException ime) {
                              completedOk = false;
                            }
                            if (completedOk) {
            // There is enough money.
                    
            sendAssetConfirmDialog = new SendAssetConfirmDialog(super.bitcoinController, mainFrame, sendRequest, assetId, assetAmountRawUnits, validator);
            sendAssetConfirmDialog.setVisible(true);
                            } else {
            // There is not enough money.
            // TODO setup validation parameters accordingly so that it displays ok.
            validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true, validator);
            validationErrorDialog.setVisible(true);
                            }
            */

        } else {
            validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, null,
                    false, validator);
            validationErrorDialog.setVisible(true);
        }
    } catch (WrongNetworkException e1) {
        logMessage(e1);
    } catch (AddressFormatException e1) {
        logMessage(e1);
    } catch (KeyCrypterException e1) {
        logMessage(e1);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(mainFrame, "Please enter a valid amount.");
    } catch (Exception e1) {
        logMessage(e1);
    }
}

From source file:com.ethercamp.harmony.service.ImportContractIndexTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    // ignore https errors
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    Unirest.setHttpClient(httpclient);/*from w ww. j  a v a 2s.  c om*/

    SystemProperties.getDefault()
            .setBlockchainConfig(new FrontierConfig(new FrontierConfig.FrontierConstants() {
                @Override
                public BigInteger getMINIMUM_DIFFICULTY() {
                    return BigInteger.ONE;
                }
            }));
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java

public ProtocolStackLoopbackLoadStress(boolean nio, boolean ssl)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();// w ww.  j av  a  2  s . c o  m

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(),
            new TrustManager[] { new PublicKeyMatchingX509ExtendedTrustManager(keyPair.getPublic()) }, null);

    hub = IOHub.create(executorService);
    serverSocketChannel = ServerSocketChannel.open();
    acceptor = new Acceptor(serverSocketChannel, nio, ssl);
}

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

/**
 * Test the reader for the table mantis_category_table.
 *
 * @throws Exception//from ww  w  .  j a v a  2 s .c  o  m
 *          Technical Exception
 */
@Test
public void testProjectCustomFieldsReader() throws Exception {
    final CustomFieldDefinitionData field1 = new CustomFieldDefinitionData();
    field1.setField(new ObjectRef(BigInteger.ONE, "field_1"));
    final CustomFieldDefinitionData field2 = new CustomFieldDefinitionData();
    field2.setField(new ObjectRef(BigInteger.valueOf(2), "field_2"));

    final CustomFieldDefinitionData[] expected = new CustomFieldDefinitionData[] { field1, field2 };

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

    projectCustomFieldsReader.setClientStub(clientStub);

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

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

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

    // calc 4^kmerSize
    BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize);

    BigInteger slice_width = kmerend.divide(BigInteger.valueOf(this.numPartitions));
    if (kmerend.mod(BigInteger.valueOf(this.numPartitions)).intValue() != 0) {
        slice_width = slice_width.add(BigInteger.ONE);
    }//www.j  a  va  2s.c  o  m

    for (int i = 0; i < this.numPartitions; i++) {
        BigInteger slice_begin = slice_width.multiply(BigInteger.valueOf(i));
        if (slice_begin.add(slice_width).compareTo(kmerend) > 0) {
            slice_width = kmerend.subtract(slice_begin);
        }

        BigInteger slice_end = slice_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;
    }

    return partitions;
}

From source file:de.jfachwert.post.Postfach.java

/**
 * Validiert das uebergebene Postfach auf moegliche Fehler.
 *
 * @param nummer    Postfach-Nummer (muss positiv sein)
 * @param ort       Ort mit PLZ//from   w w  w. j  av  a2s.  c o  m
 */
public static void validate(BigInteger nummer, Ort ort) {
    if (nummer.compareTo(BigInteger.ONE) < 0) {
        throw new InvalidValueException(nummer, "number");
    }
    validate(ort);
}

From source file:edu.brown.utils.MathUtil.java

/**
 * Calculate n! Derived from http://chaosinmotion.com/blog/?p=622
 * /*from w w  w .j  a  v a 2 s . c  o m*/
 * @param n
 * @return
 */
public static final BigInteger factorial(int n) {
    BigInteger ret;

    if (n == 0)
        return BigInteger.ONE;
    if (null != (ret = CACHE_FACTORIAL.get(n)))
        return ret;
    ret = BigInteger.valueOf(n).multiply(factorial(n - 1));
    CACHE_FACTORIAL.put(n, ret);
    return ret;
}

From source file:gedi.util.math.stat.distributions.OccupancyNumberDistribution.java

private void computeRational() {
    int maxA = b == 0 ? k : Math.min(k, n / b);
    aToProb = new double[maxA + 1];

    BigFraction[] aToProb = new BigFraction[maxA + 1];

    BigInteger bfac = factorial(b);

    long start = System.currentTimeMillis();
    double maxDiff = 0;

    aToProb[maxA] = BigFraction.ONE;// w w  w.ja v  a  2s .  c om
    for (int a = maxA - 1; a >= 0; a--) {
        int m = Math.min(k - a + 1, aToProb.length - a);
        aToProb[a] = BigFraction.ZERO;
        for (int i = 1; i < m; i++) {
            BigInteger rat = binomialCoefficientLargeInteger(k - a, i).multiply(factorial(n - a * b, i * b));
            if (n - a * b - i * b > 0)
                rat = rat.multiply(BigInteger.valueOf(k - a - i).pow(n - a * b - i * b));
            if (m - i > 0)
                rat = rat.multiply(bfac.pow(m - i));
            aToProb[a] = aToProb[a].add(new BigFraction(rat, BigInteger.ONE).multiply(aToProb[a + i]));
        }

        BigInteger rat = bfac.pow(m).multiply(BigInteger.valueOf(k - a).pow(n - a * b));

        aToProb[a] = BigFraction.ONE.subtract(aToProb[a].multiply(new BigFraction(BigInteger.ONE, rat)));
        this.aToProb[a] = new BigFraction(binomialCoefficientLargeInteger(k, a), BigInteger.ONE)
                .multiply(aToProb[a].multiply(rationalv(a, b, k, n))).doubleValue();

        maxDiff = max(maxDiff, abs(this.aToProb[a] - approximateProbability(a)));
        if (System.currentTimeMillis() - start > 500) {
            aToProxProb = this.aToProb = computeApproximateNormal();
            return;
        }
    }
    //      System.out.printf(Locale.US,"%d\t%d\t%d\t%d\t%.4g\t%.4f\n",b,k,n,maxDigit,maxDiff,(System.currentTimeMillis()-start)/1000.0);
}

From source file:mil.jpeojtrs.sca.util.AnyUtils.java

/**
 * Attempts to convert the string value to the appropriate Java type.
 * //from   w w w  . ja v a  2s  .c om
 * @param stringValue the string form of the value
 * @param type the string form of the TypeCode
 * @return A Java object of theString corresponding to the typecode
 */
private static Object primitiveConvertString(final String stringValue, final String type) {
    if (stringValue == null) {
        return null;
    }
    if ("string".equals(type)) {
        return stringValue;
    } else if ("wstring".equals(type)) {
        return stringValue;
    } else if ("boolean".equals(type)) {
        if ("true".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue)) {
            return Boolean.parseBoolean(stringValue);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid boolean value");
    } else if ("char".equals(type)) {
        switch (stringValue.length()) {
        case 1:
            return stringValue.charAt(0);
        case 0:
            return null;
        default:
            throw new IllegalArgumentException(stringValue + " is not a valid char value");
        }
    } else if ("wchar".equals(type)) {
        return stringValue.charAt(0);
    } else if ("double".equals(type)) {
        return Double.parseDouble(stringValue);
    } else if ("float".equals(type)) {
        return Float.parseFloat(stringValue);
    } else if ("short".equals(type)) {
        return Short.decode(stringValue);
    } else if ("long".equals(type)) {
        return Integer.decode(stringValue);
    } else if ("longlong".equals(type)) {
        return Long.decode(stringValue);
    } else if ("ulong".equals(type)) {
        final long MAX_UINT = 2L * Integer.MAX_VALUE + 1L;
        final Long retVal = Long.decode(stringValue);
        if (retVal < 0 || retVal > MAX_UINT) {
            throw new IllegalArgumentException(
                    "ulong value must be greater than '0' and less than " + MAX_UINT);
        }
        return retVal;
    } else if ("ushort".equals(type)) {
        final int MAX_USHORT = 2 * Short.MAX_VALUE + 1;
        final Integer retVal = Integer.decode(stringValue);
        if (retVal < 0 || retVal > MAX_USHORT) {
            throw new IllegalArgumentException(
                    "ushort value must be greater than '0' and less than " + MAX_USHORT);
        }
        return retVal;
    } else if ("ulonglong".equals(type)) {
        final BigInteger MAX_ULONG_LONG = BigInteger.valueOf(Long.MAX_VALUE).multiply(BigInteger.valueOf(2))
                .add(BigInteger.ONE);
        final BigInteger retVal = AnyUtils.bigIntegerDecode(stringValue);
        if (retVal.compareTo(BigInteger.ZERO) < 0 || retVal.compareTo(MAX_ULONG_LONG) > 0) {
            throw new IllegalArgumentException(
                    "ulonglong value must be greater than '0' and less than " + MAX_ULONG_LONG.toString());
        }
        return retVal;
    } else if ("objref".equals(type)) {
        if ("".equals(stringValue)) {
            return null;
        }
        final List<String> objrefPrefix = Arrays.asList("IOR:", "corbaname:", "corbaloc:");
        for (final String prefix : objrefPrefix) {
            if (stringValue.startsWith(prefix)) {
                return stringValue;
            }
        }
        throw new IllegalArgumentException(stringValue + " is not a valid objref value");
    } else if ("octet".equals(type)) {
        final short MIN_OCTET = 0;
        final short MAX_OCTET = 0xFF;
        final short val = Short.decode(stringValue);
        if (val <= MAX_OCTET && val >= MIN_OCTET) {
            return Short.valueOf(val);
        }
        throw new IllegalArgumentException(stringValue + " is not a valid octet value");
    } else {
        throw new IllegalArgumentException("Unknown CORBA Type: " + type);
    }
}

From source file:org.nimbustools.ctxbroker.security.CertificateAuthority.java

private void initializeGenerator() {
    this.certGen.reset();

    this.certGen.setSerialNumber(this.caX509.getSerialNumber().add(BigInteger.ONE));
    this.certGen.setSignatureAlgorithm(this.caX509.getSigAlgName());
    this.certGen.setIssuerDN(this.caX509Name);

    this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    this.certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
}