Example usage for java.math BigInteger toString

List of usage examples for java.math BigInteger toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns the decimal String representation of this BigInteger.

Usage

From source file:nl.cyso.vcloud.client.vCloudClient.java

public Task resizeVMDisks(String org, String vdc, String vapp, String vm, String diskname,
        BigInteger disksize) {
    this.vccPreCheck();

    Task t = null;//  ww w  .  j a va2  s  . c  o m
    try {
        VM vmObj = this.getVM(org, vdc, vapp, vm);

        int length = 0;
        try {
            length = vmObj.getVMDiskChainLength();
        } catch (NullPointerException ne) {
            Formatter.printErrorLine(
                    "Could not retrieve VM disk chain length. Operation will continue, but may fail.");
        }

        if (length > 1) {
            Formatter.printErrorLine(
                    "VM has a disk chain length larger than one. This VM needs to be consolidated before the disk can be extended.");
            System.exit(1);
        }

        List<VirtualDisk> disks = vmObj.getDisks();
        List<VirtualDisk> newDisks = new ArrayList<VirtualDisk>(disks.size());
        for (VirtualDisk disk : disks) {
            if (disk.isHardDisk()) {
                RASDType d = new RASDType();
                d.setElementName(disk.getItemResource().getElementName());
                d.setResourceType(disk.getItemResource().getResourceType());
                d.setInstanceID(disk.getItemResource().getInstanceID());

                for (int i = 0; i < disk.getItemResource().getHostResource().size(); i++) {
                    CimString resource = disk.getItemResource().getHostResource().get(i);
                    d.getHostResource().add(resource);
                    if (disk.getItemResource().getElementName().getValue().equals(diskname)) {
                        if (disk.getHardDiskSize().compareTo(disksize) == 1) {
                            throw new VCloudException(
                                    "Failed to resize disk, shrinking disks is not supported");
                        }
                        for (QName key : resource.getOtherAttributes().keySet()) {
                            if (key.getLocalPart().equals("capacity")) {
                                resource.getOtherAttributes().put(key, disksize.toString());
                            }
                        }
                    }
                }
                newDisks.add(new VirtualDisk(d));
            }
        }
        t = vmObj.updateDisks(newDisks);

    } catch (VCloudException e) {
        Formatter.printErrorLine("An error occured while resizing disks");
        Formatter.printErrorLine(e.getLocalizedMessage());
        Formatter.printStackTrace(e);
        System.exit(1);
    }

    return t;
}

From source file:org.plasma.sdo.helper.DataConverter.java

public Object fromInteger(Type targetType, BigInteger value) {
    DataType targetDataType = DataType.valueOf(targetType.getName());
    switch (targetDataType) {
    case Integer:
        return value;
    case Double:
        return new Double(value.doubleValue());
    case Float:
        return new Float(value.floatValue());
    case Int:/*from   w  w w . j  a v a 2 s.c o  m*/
        return new Integer(value.intValue());
    case Long:
        return new Long(value.longValue());
    case Decimal:
        return new BigDecimal(value.doubleValue());
    case Bytes:
        return value.toByteArray();
    case String:
        //as per spec: ('+'|'-')? [0-9]+
        return value.toString();
    default:
        throw new InvalidDataConversionException(targetDataType, DataType.Integer, value);
    }
}

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  ava  2s .  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.sumatone.cloud.securecloud.Fragments.UploadFragment.java

private void informTrustedAuthority(final File aVoid, final BigInteger blindValue, final String originalName,
        final JSONObject policy) {
    uploadProgressBar.setVisibility(View.VISIBLE);
    progress.setText("Informing TA");
    selectFile.setEnabled(false);//w  w w  .  j a  v a 2 s.  com
    uploadButton.setEnabled(false);

    StringRequest stringRequest = new StringRequest(Request.Method.POST, taUrl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("response", response);
                    showMessage(response);
                    uploadProgressBar.setVisibility(View.GONE);
                    progress.setText("TA responded");
                    if (response.equals("exist")) {
                        showMessage("TA responded");
                        progress.setText("File already exist");

                        selectFile.setEnabled(true);
                        uploadButton.setEnabled(true);
                    } else if (response.equals("Error")) {
                        showMessage("Unknown Error");
                        progress.setText("Error");

                        selectFile.setEnabled(true);
                        uploadButton.setEnabled(true);
                    } else if (response.equals("success")) {
                        uploadFile(aVoid);
                    }
                }

            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    uploadProgressBar.setVisibility(View.GONE);
                    progress.setText("Error Occured");
                    showMessage(error.getMessage());
                    error.printStackTrace();
                    selectFile.setEnabled(true);
                    uploadButton.setEnabled(true);
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map postParams = new HashMap<String, String>();
            postParams.put("filename", aVoid.getName());
            postParams.put("acps", policy.toString());
            postParams.put("unblind", blindValue.toString());
            postParams.put("originalName", originalName);
            postParams.put("uploaderLevel", String
                    .valueOf(PreferenceManager.getDefaultSharedPreferences(getActivity()).getInt("level", 7)));
            postParams.put("uploaderId",
                    PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("email", ""));
            return postParams;
        }
    };

    stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 2, 2));
    AppController.getInstance().addToRequestQueue(stringRequest);

}

From source file:opennlp.tools.similarity.apps.solr.WordDocBuilderEndNotes.java

public String buildWordDoc(List<HitBase> content, String title) {

    String outputDocFinename = absPath + "written/" + title.replace(' ', '_').replace('\"', ' ').trim()
            + ".docx";

    WordprocessingMLPackage wordMLPackage = null;

    List<String> imageURLs = getAllImageSearchResults(title);
    int count = 0;
    BigInteger refId = BigInteger.ONE;
    try {/*  www .j  a va  2s .  c  om*/
        wordMLPackage = WordprocessingMLPackage.createPackage();

        CTEndnotes endnotes = null;
        try {
            EndnotesPart ep = new EndnotesPart();
            endnotes = Context.getWmlObjectFactory().createCTEndnotes();
            ep.setJaxbElement(endnotes);
            wordMLPackage.getMainDocumentPart().addTargetPart(ep);
        } catch (InvalidFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", title.toUpperCase());
        for (HitBase para : content) {
            if (para.getFragments() == null || para.getFragments().size() < 1) // no found content in this hit
                continue;
            try {
                String processedParaTitle = processParagraphTitle(para.getTitle());

                if (processedParaTitle != null && !processedParaTitle.endsWith("..")
                        || StringUtils.isAlphanumeric(processedParaTitle)) {
                    wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle",
                            processedParaTitle);
                }
                String paraText = processParagraphText(para.getFragments().toString());
                wordMLPackage.getMainDocumentPart().addParagraphOfText(paraText);

                CTFtnEdn endnote = Context.getWmlObjectFactory().createCTFtnEdn();
                endnotes.getEndnote().add(endnote);

                endnote.setId(refId);
                refId.add(BigInteger.ONE);
                String url = para.getUrl();
                String endnoteBody = "<w:p xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ><w:pPr><w:pStyle w:val=\"EndnoteText\"/></w:pPr><w:r><w:rPr>"
                        + "<w:rStyle w:val=\"EndnoteReference\"/></w:rPr><w:endnoteRef/></w:r><w:r><w:t xml:space=\"preserve\"> "
                        + url + "</w:t></w:r></w:p>";
                try {
                    endnote.getEGBlockLevelElts().add(XmlUtils.unmarshalString(endnoteBody));
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // Add the body text referencing it
                String docBody = "<w:p xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ><w:r><w:t>"//+ paraText
                        /*+ refId.toString()*/ + "</w:t></w:r><w:r><w:rPr><w:rStyle w:val=\"EndnoteReference\"/></w:rPr><w:endnoteReference w:id=\""
                        + refId.toString() + "\"/></w:r></w:p>";

                try {
                    wordMLPackage.getMainDocumentPart().addParagraph(docBody);
                } catch (JAXBException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    addImageByImageURLToPackage(count, wordMLPackage, imageURLs);
                } catch (Exception e) {
                    // no need to report issues
                    //e.printStackTrace();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            count++;
        }
        // now add URLs
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle", "REFERENCES");
        for (HitBase para : content) {
            if (para.getFragments() == null || para.getFragments().size() < 1) // no found content in this hit
                continue;
            try {
                wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Subtitle", para.getTitle());
                String paraText = para.getUrl();
                wordMLPackage.getMainDocumentPart().addParagraphOfText(paraText);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try {
            wordMLPackage.save(new File(outputDocFinename));
            System.out.println("Finished creating docx =" + outputDocFinename);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            String fileNameToDownload = "/var/www/wrt_latest/"
                    + title.replace(' ', '_').replace('\"', ' ').trim() + ".docx";
            wordMLPackage.save(new File(fileNameToDownload));
            System.out.println("Wrote a doc for download :" + fileNameToDownload);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return outputDocFinename;
}

From source file:org.egov.billsaccounting.services.CreateVoucher.java

public String getFiscalPeriod(final String vDate) throws TaskFailedException {
    BigInteger fiscalPeriod = null;
    final String sql = "select id from fiscalperiod  where '" + vDate + "' between startingdate and endingdate";
    try {/*from   w w  w .ja va 2s .  com*/
        final Query pst = persistenceService.getSession().createSQLQuery(sql);
        final List<BigInteger> rset = pst.list();
        fiscalPeriod = rset != null ? rset.get(0) : BigInteger.ZERO;
    } catch (final Exception e) {
        LOGGER.error("Exception..." + e.getMessage());
        throw new TaskFailedException(e.getMessage());
    }
    return fiscalPeriod.toString();
}

From source file:com.netflix.imfutility.cpl.AbstractCplContextBuilderStrategy.java

/**
 * <ul>//from  ww w. java 2  s  .co  m
 * <li>Calculate other Resource parameters (such as millisecond-based parameters and timecode-based parameters)
 * using edit-unit-based parameters filled by a concrete strategy.</li>
 * </ul>
 */
private void calculateMsAndTcParameters() {
    ResourceTemplateParameterContext resourceContext = contextProvider.getResourceContext();
    for (SequenceType seqType : contextProvider.getSequenceContext().getSequenceTypes()) {
        for (SequenceUUID seqUuid : contextProvider.getSequenceContext().getUuids(seqType)) {
            for (SegmentUUID segmUuid : contextProvider.getSegmentContext().getUuids()) {
                ResourceKey resourceKey = ResourceKey.create(segmUuid, seqUuid, seqType);
                for (ResourceUUID resUuid : resourceContext.getUuids(resourceKey)) {
                    ContextInfo contextInfo = new ContextInfoBuilder().setResourceUuid(resUuid)
                            .setSegmentUuid(segmUuid).setSequenceUuid(seqUuid).setSequenceType(seqType).build();

                    // 1. already filled from CPL: startTime/endTime/duration in EU and edit rate
                    BigFraction editRate = ConversionHelper.parseEditRate(contextProvider.getResourceContext()
                            .getParameterValue(ResourceContextParameters.EDIT_RATE, contextInfo));
                    BigInteger durationEU = new BigInteger(contextProvider.getResourceContext()
                            .getParameterValue(ResourceContextParameters.DURATION_EDIT_UNIT, contextInfo));
                    BigInteger startTimeEU = new BigInteger(contextProvider.getResourceContext()
                            .getParameterValue(ResourceContextParameters.START_TIME_EDIT_UNIT, contextInfo));
                    BigInteger endTimeEU = new BigInteger(contextProvider.getResourceContext()
                            .getParameterValue(ResourceContextParameters.END_TIME_EDIT_UNIT, contextInfo));

                    // 2. startTime, endTime and duration in MS
                    long durationMs = ConversionHelper.editUnitToMilliSeconds(durationEU, editRate);
                    long startTimeMs = ConversionHelper.editUnitToMilliSeconds(startTimeEU, editRate);
                    long endTimeMs = ConversionHelper.editUnitToMilliSeconds(endTimeEU, editRate);
                    resourceContext.addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.DURATION_MS, String.valueOf(durationMs));
                    resourceContext.addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.START_TIME_MS, String.valueOf(startTimeMs));
                    resourceContext.addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.END_TIME_MS, String.valueOf(endTimeMs));

                    // 3. startTime, endTime and Duration in TC
                    String durationTimecode = ConversionHelper.editUnitToTimecode(durationEU, editRate);
                    String startTimeTimeCode = ConversionHelper.editUnitToTimecode(startTimeEU, editRate);
                    String endTimeTimeCode = ConversionHelper.editUnitToTimecode(endTimeEU, editRate);
                    resourceContext.addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.DURATION_TIMECODE, String.valueOf(durationTimecode));
                    resourceContext.addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.START_TIME_TIMECODE, String.valueOf(startTimeTimeCode));
                    resourceContext.addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.END_TIME_TIMECODE, String.valueOf(endTimeTimeCode));

                    // 4. startTime and duration in frameEditUnits (will be re-calculated later)
                    // assume essence has only one seq type (either video or audio),
                    // so start time in frames is equal to start time in edit units.
                    contextProvider.getResourceContext().addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.DURATION_FRAME_EDIT_UNIT, durationEU.toString());
                    contextProvider.getResourceContext().addResourceParameter(resourceKey, resUuid,
                            ResourceContextParameters.START_TIME_FRAME_EDIT_UNIT, startTimeEU.toString());
                }
            }
        }
    }
}

From source file:org.rascalmpl.library.Prelude.java

public IValue toInt(IString s, IInteger r) {
    try {/*  w w  w . j a va 2s. co m*/
        java.lang.String sval = s.getValue();
        boolean isNegative = false;
        int radix = r.intValue();

        if (sval.equals("0")) {
            return values.integer(0);
        }

        if (sval.startsWith("-")) {
            isNegative = true;
            sval = sval.substring(1);
        }
        BigInteger bi = new BigInteger(isNegative ? "-" + sval : sval, radix);
        return values.integer(bi.toString());
    } catch (NumberFormatException e) {
        throw RuntimeExceptionFactory.illegalArgument(null, null);
    }
}

From source file:org.rascalmpl.library.Prelude.java

public IValue toInt(IString s)
//@doc{toInt -- convert a string s to integer}
{
    try {/*from   w  w w . java  2s.  co  m*/
        java.lang.String sval = s.getValue();
        boolean isNegative = false;
        int radix = 10;

        if (sval.equals("0")) {
            return values.integer(0);
        }

        if (sval.startsWith("-")) {
            isNegative = true;
            sval = sval.substring(1);
        }
        if (sval.startsWith("0x") || sval.startsWith("0X")) {
            radix = 16;
            sval = sval.substring(2);
        } else if (sval.startsWith("0")) {
            radix = 8;
            sval = sval.substring(1);
        }
        BigInteger bi = new BigInteger(isNegative ? "-" + sval : sval, radix);
        return values.integer(bi.toString());
    } catch (NumberFormatException e) {
        throw RuntimeExceptionFactory.illegalArgument(null, null);
    }
}

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 {/*  w  ww .  j a v a 2  s .  c  o m*/
        // 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);
    }
}