Example usage for java.math BigInteger ZERO

List of usage examples for java.math BigInteger ZERO

Introduction

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

Prototype

BigInteger ZERO

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

Click Source Link

Document

The BigInteger constant zero.

Usage

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Creates request for device SRP verification.
 *
 * @param challenge REQUIRED: {@link RespondToAuthChallengeResult} contains
 *            next challenge./*from   ww w  .java 2 s  .c  om*/
 * @param deviceSecret REQUIRED: Device secret verifier.
 * @param authenticationHelper REQUIRED: Internal helper class for SRP
 *            calculations.
 * @param deviceGroupKey the device group key
 * @return {@link RespondToAuthChallengeRequest}.
 */
public RespondToAuthChallengeRequest deviceSrpAuthRequest(RespondToAuthChallengeResult challenge,
        String deviceSecret, String deviceGroupKey, AuthenticationHelper authenticationHelper) {
    this.usernameInternal = challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_USERNAME);

    final BigInteger srpB = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16);
    if (srpB.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) {
        throw new CognitoInternalErrorException("SRP error, B cannot be zero");
    }

    final BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16);
    final byte[] key = authenticationHelper.getPasswordAuthenticationKey(deviceKey, deviceSecret, srpB, salt);

    final Date timestamp = new Date();
    byte[] hmac;
    String dateString;
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        final SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        mac.update(deviceGroupKey.getBytes(StringUtils.UTF8));
        mac.update(deviceKey.getBytes(StringUtils.UTF8));
        final byte[] secretBlock = Base64.decode(
                challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
        mac.update(secretBlock);

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        dateString = simpleDateFormat.format(timestamp);
        final byte[] dateBytes = dateString.getBytes(StringUtils.UTF8);

        hmac = mac.doFinal(dateBytes);
    } catch (final Exception e) {
        throw new CognitoInternalErrorException("SRP error", e);
    }

    secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret);

    final Map<String, String> srpAuthResponses = new HashMap<String, String>();
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SECRET_BLOCK,
            challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SIGNATURE,
            new String(Base64.encode(hmac), StringUtils.UTF8));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_TIMESTAMP, dateString);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_USERNAME, usernameInternal);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_DEVICE_KEY, deviceKey);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_SECRET_HASH, secretHash);

    final RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest();
    authChallengeRequest.setChallengeName(challenge.getChallengeName());
    authChallengeRequest.setClientId(clientId);
    authChallengeRequest.setSession(challenge.getSession());
    authChallengeRequest.setChallengeResponses(srpAuthResponses);

    return authChallengeRequest;
}

From source file:org.alfresco.opencmis.CMISTest.java

/**
 * MNT-8804 related test ://from w ww.j ava  2  s .com
 * Check CMISConnector.query for search nodes in environment with corrupted indexes
 */
@Test
public void testQueryNodesWithCorruptedIndexes() {
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    final String TEST_NAME = "mnt8804test-";
    final String docName = TEST_NAME + GUID.generate();

    /* Create node */
    final FileInfo document = transactionService.getRetryingTransactionHelper()
            .doInTransaction(new RetryingTransactionCallback<FileInfo>() {
                @Override
                public FileInfo execute() throws Throwable {
                    NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();

                    /* Create folder within companyHome */
                    String folderName = TEST_NAME + GUID.generate();
                    FileInfo folderInfo = fileFolderService.create(companyHomeNodeRef, folderName,
                            ContentModel.TYPE_FOLDER);
                    nodeService.setProperty(folderInfo.getNodeRef(), ContentModel.PROP_NAME, folderName);
                    assertNotNull(folderInfo);

                    /* Create document to query */
                    FileInfo document = fileFolderService.create(folderInfo.getNodeRef(), docName,
                            ContentModel.TYPE_CONTENT);
                    assertNotNull(document);
                    nodeService.setProperty(document.getNodeRef(), ContentModel.PROP_NAME, docName);

                    return document;
                }
            });

    final Pair<Long, NodeRef> nodePair = nodeDAO.getNodePair(document.getNodeRef());

    /* delete node's metadata directly */
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
        @Override
        public Void execute() throws Throwable {
            Pair<Long, ChildAssociationRef> childAssocPair = nodeDAO.getPrimaryParentAssoc(nodePair.getFirst());
            nodeDAO.deleteChildAssoc(childAssocPair.getFirst());
            nodeDAO.deleteNode(nodePair.getFirst());
            return null;
        }
    });

    /* ensure the node does not exist */
    assertTrue(!nodeService.exists(nodePair.getSecond()));

    String queryString = "SELECT * FROM cmis:document WHERE cmis:name='" + docName + "'";

    ObjectList resultList = cmisConnector.query(queryString, Boolean.FALSE, IncludeRelationships.NONE,
            "cmis:none", BigInteger.ONE, BigInteger.ZERO);
    assertEquals(resultList.getNumItems(), BigInteger.ZERO);

    // prepare cmis query
    CMISQueryOptions options = new CMISQueryOptions(queryString, cmisConnector.getRootStoreRef());
    CmisVersion cmisVersion = cmisConnector.getRequestCmisVersion();
    options.setCmisVersion(cmisVersion);
    options.setQueryMode(CMISQueryMode.CMS_WITH_ALFRESCO_EXTENSIONS);
    options.setSkipCount(0);
    options.setMaxItems(100);

    /* make query bypassing CMISConnector */
    org.alfresco.opencmis.search.CMISResultSet rs = cmisConnector.getOpenCMISQueryService().query(options);
    assertEquals(rs.getNumberFound(), 0);
}

From source file:com.ephesoft.dcma.batch.service.BatchSchemaServiceImpl.java

/**
 * This API is used to generate the HocrPage object for input hocr file.
 * /*  ww  w.  j  a v  a2  s. c o  m*/
 * @param pageName {@link String}
 * @param pathOfHOCRFile {@link String}
 * @param outputFilePath {@link String}
 * @param batchClassIdentifier {@link String}
 * @param ocrEngineName {@link String}
 * @return {@link HocrPage}
 */
@Override
public HocrPage generateHocrPage(final String pageName, final String pathOfHOCRFile,
        final String outputFilePath, final String batchClassIdentifier, final String ocrEngineName) {

    if (null == pathOfHOCRFile || null == outputFilePath) {
        return null;
    }
    final BatchPluginConfiguration[] pluginConfiguration = batchClassPluginPropertiesService
            .getPluginProperties(batchClassIdentifier, TESSERACT_HOCR_PLUGIN,
                    TesseractVersionProperty.TESSERACT_VERSIONS);
    String tesseractVersion = BatchConstants.EMPTY;
    if (pluginConfiguration != null && pluginConfiguration.length > BatchConstants.ZERO
            && pluginConfiguration[BatchConstants.ZERO].getValue() != null
            && pluginConfiguration[BatchConstants.ZERO].getValue().length() > BatchConstants.ZERO) {
        tesseractVersion = pluginConfiguration[BatchConstants.ZERO].getValue();
    }
    final HocrPage hocrPage = new HocrPage();
    hocrPage.setPageID(pageName);
    FileInputStream inputStream = null;
    try {
        if (ocrEngineName.equalsIgnoreCase(IUtilCommonConstants.TESSERACT_HOCR_PLUGIN) && tesseractVersion
                .equalsIgnoreCase(TesseractVersionProperty.TESSERACT_VERSION_3.getPropertyKey())) {
            XMLUtil.htmlOutputStream(pathOfHOCRFile, outputFilePath);
            final String actualFolderLocation = new File(outputFilePath).getParent();
            OCREngineUtil.formatHOCRForTesseract(outputFilePath, actualFolderLocation, pageName);
        } else {
            XMLUtil.htmlOutputStream(pathOfHOCRFile, outputFilePath);
        }
        inputStream = new FileInputStream(outputFilePath);
        final org.w3c.dom.Document doc = XMLUtil.createDocumentFrom(inputStream);
        final NodeList titleNodeList = doc.getElementsByTagName(BatchConstants.TITLE);
        if (null != titleNodeList) {
            for (int index = BatchConstants.ZERO; index < titleNodeList.getLength(); index++) {
                final Node node = titleNodeList.item(index);
                final NodeList childNodeList = node.getChildNodes();
                final Node nodeChild = childNodeList.item(BatchConstants.ZERO);
                if (null != nodeChild) {
                    final String value = nodeChild.getNodeValue();
                    if (value != null) {
                        hocrPage.setTitle(value);
                        break;
                    }
                }
            }
        }

        final NodeList spanNodeList = doc.getElementsByTagName("span");
        final Spans spans = new Spans();
        hocrPage.setSpans(spans);
        final List<Span> spanList = spans.getSpan();
        if (null != spanNodeList) {
            final StringBuilder hocrContent = new StringBuilder();
            for (int index = 0; index < spanNodeList.getLength(); index++) {
                final Node node = spanNodeList.item(index);
                final NodeList childNodeList = node.getChildNodes();
                final Node nodeChild = childNodeList.item(BatchConstants.ZERO);
                final Span span = new Span();
                if (null != nodeChild) {
                    final String value = nodeChild.getNodeValue();
                    span.setValue(value);
                    hocrContent.append(value);
                    hocrContent.append(BatchConstants.SPACE);
                }
                spanList.add(span);
                final NamedNodeMap map = node.getAttributes();
                final Node nMap = map.getNamedItem(BatchConstants.TITLE);
                Coordinates hocrCoordinates = null;
                hocrCoordinates = getHOCRCoordinates(nMap, hocrCoordinates);
                if (null == hocrCoordinates) {
                    hocrCoordinates = new Coordinates();
                    hocrCoordinates.setX0(BigInteger.ZERO);
                    hocrCoordinates.setX1(BigInteger.ZERO);
                    hocrCoordinates.setY0(BigInteger.ZERO);
                    hocrCoordinates.setY1(BigInteger.ZERO);
                }
                span.setCoordinates(hocrCoordinates);
            }
            hocrPage.setHocrContent(hocrContent.toString());
        }
    } catch (final IOException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return hocrPage;
}

From source file:com.google.bitcoin.core.Wallet.java

/**
 * Given a spend request containing an incomplete transaction, makes it valid by adding outputs and signed inputs
 * according to the instructions in the request. The transaction in the request is modified by this method, as is
 * the fee parameter.// w  w w .ja v a  2 s  .c o m
 *
 * @param req a SendRequest that contains the incomplete transaction and details for how to make it valid.
 * @throws InsufficientMoneyException if the request could not be completed due to not enough balance.
 * @throws IllegalArgumentException if you try and complete the same SendRequest twice, or if the given send request
 *         cannot be completed without violating the protocol rules.
 */
public void completeTx(SendRequest req, boolean sign)
        throws InsufficientMoneyException, CSExceptions.CannotEncode {
    lock.lock();
    try {
        checkArgument(!req.completed, "Given SendRequest has already been completed.");
        // Calculate the amount of value we need to import.
        BigInteger value = BigInteger.ZERO;
        for (TransactionOutput output : req.tx.getOutputs()) {
            value = value.add(output.getValue());
        }
        BigInteger totalOutput = value;

        log.info("Completing send tx with {} outputs totalling {} satoshis (not including fees)",
                req.tx.getOutputs().size(), value);

        // If any inputs have already been added, we don't need to get their value from wallet
        BigInteger totalInput = BigInteger.ZERO;

        /* CSPK-mike START */
        /* Code commented out, input value is calculated after asset inputs were added            
                    for (TransactionInput input : req.tx.getInputs())
        if (input.getConnectedOutput() != null)
            totalInput = totalInput.add(input.getConnectedOutput().getValue());
        else
            log.warn("SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee.");
                    value = value.subtract(totalInput);
        */
        /* CSPK-mike START */

        List<TransactionInput> originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs());

        // We need to know if we need to add an additional fee because one of our values are smaller than 0.01 BTC
        boolean needAtLeastReferenceFee = false;
        if (req.ensureMinRequiredFee && !req.emptyWallet) { // min fee checking is handled later for emptyWallet
            for (TransactionOutput output : req.tx.getOutputs())
                if (output.getValue().compareTo(Utils.CENT) < 0) {
                    if (output.getValue().compareTo(output.getMinNonDustValue()) < 0)
                        throw new IllegalArgumentException(
                                "Tried to send dust with ensureMinRequiredFee set - no way to complete this");
                    needAtLeastReferenceFee = true;
                    break;
                }
        }

        // Calculate a list of ALL potential candidates for spending and then ask a coin selector to provide us
        // with the actual outputs that'll be used to gather the required amount of value. In this way, users
        // can customize coin selection policies.
        //
        // Note that this code is poorly optimized: the spend candidates only alter when transactions in the wallet
        // change - it could be pre-calculated and held in RAM, and this is probably an optimization worth doing.
        // Note that output.isMine(this) needs to test the keychain which is currently an array, so it's
        // O(candidate outputs ^ keychain.size())! There's lots of low hanging fruit here.
        LinkedList<TransactionOutput> candidates = calculateAllSpendCandidates(true);

        CoinSelection bestCoinSelection;
        TransactionOutput bestChangeOutput = null;
        if (!req.emptyWallet) {
            // This can throw InsufficientMoneyException.
            FeeCalculation feeCalculation;
            /* CSPK-mike START */
            //                feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee, candidates);
            // Fee and inputs calculation

            /*               
                            CoinSparkMessagePart [] MessageParts=new CoinSparkMessagePart[1];
                            MessageParts[0]=new CoinSparkMessagePart();
                            MessageParts[0].mimeType="text/plain";
                            MessageParts[0].fileName=null;
                            MessageParts[0].content="Hello World!".getBytes();
                            String [] DeliveryServers=new String [] {"assets1.coinspark.org/","assets1.coinspark.org/abc"};//,"144.76.175.228/" };
                            req.setMessage(MessageParts, DeliveryServers);
                    
                            CoinSparkPaymentRef paymentRef=new CoinSparkPaymentRef(125);
                            req.setPaymentRef(paymentRef);
            */

            if (CS.createAssetTransfers(req, originalInputs, candidates)) {
                totalInput = BigInteger.ZERO;
                for (TransactionInput input : req.tx.getInputs()) {
                    if (input.getConnectedOutput() != null) {
                        totalInput = totalInput.add(input.getConnectedOutput().getValue());
                    } else {
                        log.warn(
                                "SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee.");
                    }
                }
                value = totalOutput;
                value = value.subtract(totalInput);

                originalInputs = new ArrayList<TransactionInput>(req.tx.getInputs());
                // Coinspark transaction has to have change output even if there are no explicit transfers.
                feeCalculation = new FeeCalculation(req, value, originalInputs, needAtLeastReferenceFee,
                        candidates, Transaction.MIN_NONDUST_OUTPUT);
            } else {
                throw new InsufficientMoneyException.CouldNotAdjustDownwards();
            }

            /* CSPK-mike END */
            bestCoinSelection = feeCalculation.bestCoinSelection;
            bestChangeOutput = feeCalculation.bestChangeOutput;
        } else {
            // We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output
            // of the total value we can currently spend as determined by the selector, and then subtracting the fee.
            checkState(req.tx.getOutputs().size() == 1, "Empty wallet TX must have a single output only.");
            CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector;
            bestCoinSelection = selector.select(NetworkParameters.MAX_MONEY, candidates);
            req.tx.getOutput(0).setValue(bestCoinSelection.valueGathered);

            totalOutput = bestCoinSelection.valueGathered;
        }

        for (TransactionOutput output : bestCoinSelection.gathered)
            req.tx.addInput(output);

        /* CSPK-mike START */
        if (!CS.preparePaymentRef(req)) {
            throw new CSExceptions.CannotEncode("Cannot prepare payment reference");
        }
        if (!CS.prepareMessage(req)) {
            throw new CSExceptions.CannotEncode("Cannot prepare message");
        }
        /* CSPK-mike END */

        if (req.ensureMinRequiredFee && req.emptyWallet) {
            final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee;
            final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb;
            Transaction tx = req.tx;
            if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb))
                throw new InsufficientMoneyException.CouldNotAdjustDownwards();
        }

        /* CSPK-mike START */
        // Input calculation for "Empty wallet" request
        if (req.emptyWallet) {
            Transaction tx = req.tx;
            TransactionOutput output = tx.getOutput(0);
            if (CS.createAssetTransfersForEmptyWallet(req,
                    output.getValue().subtract(output.getMinNonDustValue()))) {
                if (req.ensureMinRequiredFee) {
                    final BigInteger baseFee = req.fee == null ? BigInteger.ZERO : req.fee;
                    final BigInteger feePerKb = req.feePerKb == null ? BigInteger.ZERO : req.feePerKb;
                    totalOutput = bestCoinSelection.valueGathered;
                    output.setValue(totalOutput);
                    if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb, req.assetFee)) {
                        CS.log.warning("Empty wallet: not enough bitcoins to transfer assets.");
                        tx.getOutputs().clear();
                        output.setValue(totalOutput);
                        tx.addOutput(output);
                        req.assetsEncoded = null;
                        req.assetFee = BigInteger.ZERO;
                        if (!adjustOutputDownwardsForFee(tx, bestCoinSelection, baseFee, feePerKb)) {
                            throw new InsufficientMoneyException.CouldNotAdjustDownwards();
                        }
                    }
                    totalOutput = output.getValue();
                    bestChangeOutput = null;
                }
            }
            totalOutput = output.getValue();
            bestChangeOutput = null;
        }
        /* CSPK-mike END */

        totalInput = totalInput.add(bestCoinSelection.valueGathered);

        if (bestChangeOutput != null) {
            req.tx.addOutput(bestChangeOutput);
            totalOutput = totalOutput.add(bestChangeOutput.getValue());
            log.info("  with {} coins change", bitcoinValueToFriendlyString(bestChangeOutput.getValue()));
        }
        final BigInteger calculatedFee = totalInput.subtract(totalOutput);
        if (calculatedFee.compareTo(BigInteger.ZERO) > 0) {
            log.info("  with a fee of {}", bitcoinValueToFriendlyString(calculatedFee));
        }

        // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs.
        if (sign) {
            sign(req);
        }

        // Check size.
        int size = req.tx.bitcoinSerialize().length;
        if (size > Transaction.MAX_STANDARD_TX_SIZE) {
            throw new IllegalArgumentException(
                    String.format("Transaction could not be created without exceeding max size: %d vs %d", size,
                            Transaction.MAX_STANDARD_TX_SIZE));
        }

        // Label the transaction as being self created. We can use this later to spend its change output even before
        // the transaction is confirmed. We deliberately won't bother notifying listeners here as there's not much
        // point - the user isn't interested in a confidence transition they made themselves.
        req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF);

        // Keep a track of the date the tx was created (used in MultiBitService
        // to work out the block it appears in).
        req.tx.setUpdateTime(new Date());

        // Label the transaction as being a user requested payment. This can be used to render GUI wallet
        // transaction lists more appropriately, especially when the wallet starts to generate transactions itself
        // for internal purposes.
        req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT);
        req.completed = true;
        req.fee = calculatedFee;
        log.info("  completed: {}", req.tx);
    } finally {
        lock.unlock();
    }
}

From source file:org.energy_home.jemma.javagal.layers.data.implementations.IDataLayerImplementation.DataFreescale.java

private Status WriteSasSync(long timeout, StartupAttributeInfo sai) throws InterruptedException, Exception {
    // TODO CHECK
    if (sai.getChannelMask() == null)
        sai = gal.getPropertiesManager().getSturtupAttributeInfo();

    LogicalType devType = sai.getDeviceType();

    ByteArrayObject res = new ByteArrayObject();
    res.addBytesShort(Short.reverseBytes(sai.getShortAddress().shortValue()), 2);

    /* Extended PanID */
    byte[] ExtendedPaniId = DataManipulation.toByteVect(sai.getExtendedPANId(), 8);
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("Extended PanID:" + DataManipulation.convertBytesToString(ExtendedPaniId));
    }/*from   w  w w  .ja  v  a  2 s.com*/

    for (byte b : DataManipulation.reverseBytes(ExtendedPaniId))
        res.addByte(b);

    /* Extended APS Use Extended PAN Id */
    byte[] APSUseExtendedPANId = DataManipulation.toByteVect(BigInteger.ZERO, 8);
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("APS Use Extended PAN Id:" + DataManipulation.convertBytesToString(APSUseExtendedPANId));
    }
    for (byte b : DataManipulation.reverseBytes(APSUseExtendedPANId))
        res.addByte(b);
    res.addBytesShort(Short.reverseBytes(sai.getPANId().shortValue()), 2);
    byte[] _channel = Utils.buildChannelMask(sai.getChannelMask().shortValue());

    if (gal.getPropertiesManager().getDebugEnabled())
        logger.info("Channel readed from PropertiesManager:" + sai.getChannelMask());

    if (gal.getPropertiesManager().getDebugEnabled())
        DataManipulation.logArrayHexRadix("Channel after conversion", _channel);

    for (byte x : DataManipulation.reverseBytes(_channel))
        res.addByte(x);

    res.addByte(sai.getProtocolVersion().byteValue());
    res.addByte(sai.getStackProfile().byteValue());
    res.addByte(sai.getStartupControl().byteValue());

    /* TrustCenterAddress */
    byte[] TrustCenterAddress = DataManipulation.toByteVect(sai.getTrustCenterAddress(), 8);
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("TrustCenterAddress:" + DataManipulation.convertBytesToString(TrustCenterAddress));
    }
    for (byte b : DataManipulation.reverseBytes(TrustCenterAddress))
        res.addByte(b);

    /* TrustCenterMasterKey */
    byte[] TrustCenterMasterKey = (devType == LogicalType.COORDINATOR) ? sai.getTrustCenterMasterKey()
            : DataManipulation.toByteVect(BigInteger.ZERO, 16);
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("TrustCenterMasterKey:" + DataManipulation.convertBytesToString(TrustCenterMasterKey));
    }
    for (byte b : DataManipulation.reverseBytes(TrustCenterMasterKey))
        res.addByte(b);

    /* NetworKey */
    byte[] NetworKey = (devType == LogicalType.COORDINATOR) ? sai.getNetworkKey()
            : DataManipulation.toByteVect(BigInteger.ZERO, 16);
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("NetworKey:" + DataManipulation.convertBytesToString(NetworKey));
    }
    for (byte b : DataManipulation.reverseBytes(NetworKey))
        res.addByte(b);

    res.addByte((sai.isUseInsecureJoin()) ? ((byte) 0x01) : ((byte) 0x00));

    /* PreconfiguredLinkKey */
    byte[] PreconfiguredLinkKey = sai.getPreconfiguredLinkKey();
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("PreconfiguredLinkKey:" + DataManipulation.convertBytesToString(PreconfiguredLinkKey));
    }
    for (byte b : PreconfiguredLinkKey)
        res.addByte(b);

    res.addByte(sai.getNetworkKeySeqNum().byteValue());
    res.addByte((byte) 0x01);

    res.addBytesShort(Short.reverseBytes(sai.getNetworkManagerAddress().shortValue()), 2);
    res.addByte(sai.getScanAttempts().byteValue());

    res.addBytesShort(sai.getTimeBetweenScans().shortValue(), 2);

    res.addBytesShort(Short.reverseBytes(sai.getRejoinInterval().shortValue()), 2);

    res.addBytesShort(Short.reverseBytes(sai.getMaxRejoinInterval().shortValue()), 2);

    res.addBytesShort(Short.reverseBytes(sai.getIndirectPollRate().shortValue()), 2);

    res.addByte(sai.getParentRetryThreshold().byteValue());

    res.addByte((sai.isConcentratorFlag()) ? ((byte) 0x01) : ((byte) 0x00));

    res.addByte(sai.getConcentratorRadius().byteValue());

    res.addByte(sai.getConcentratorDiscoveryTime().byteValue());

    res = Set_SequenceStart_And_FSC(res, FreescaleConstants.BlackBoxWriteSAS);
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("WriteSas Command:" + res.ToHexString());
    }

    ParserLocker lock = new ParserLocker();
    lock.setType(TypeMessage.WRITE_SAS);
    Status status = null;
    try {

        synchronized (listLocker) {
            listLocker.add(lock);
        }
        addToSendDataQueue(res);
        synchronized (lock) {
            try {
                lock.wait(timeout);
            } catch (InterruptedException e) {

            }
        }
        status = lock.getStatus();
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }
    } catch (Exception e) {
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }
    }
    if (status.getCode() == ParserLocker.INVALID_ID) {
        if (gal.getPropertiesManager().getDebugEnabled()) {
            logger.error("Timeout expired in write sas");
        }
        throw new GatewayException("Timeout expired in write sas");
    } else {
        if (status.getCode() != 0) {
            if (gal.getPropertiesManager().getDebugEnabled()) {
                logger.info("Returned Status: " + status.getCode());
            }
            throw new GatewayException("Error on BlackBox.WriteSAS. Status code:" + status.getCode()
                    + " Status Message: " + status.getMessage());
        }
        return status;
    }
}

From source file:com.google.bitcoin.core.Wallet.java

/**
 * Returns the balance of this wallet as calculated by the provided balanceType.
 *///from   ww w .j a  va2 s .  c  o  m
public BigInteger getBalance(BalanceType balanceType) {
    lock.lock();
    try {
        if (balanceType == BalanceType.AVAILABLE) {
            return getBalance(coinSelector);
        } else if (balanceType == BalanceType.ESTIMATED) {
            LinkedList<TransactionOutput> all = calculateAllSpendCandidates(false);
            BigInteger value = BigInteger.ZERO;
            for (TransactionOutput out : all)
                value = value.add(out.getValue());
            return value;
        } else {
            throw new AssertionError("Unknown balance type"); // Unreachable.
        }
    } finally {
        lock.unlock();
    }
}

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  ww. j ava2s  .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.google.bitcoin.core.Wallet.java

/**
 * <p>Don't call this directly. It's not intended for API users.</p>
 *
 * <p>Called by the {@link BlockChain} when the best chain (representing total work done) has changed. This can
 * cause the number of confirmations of a transaction to go higher, lower, drop to zero and can even result in
 * a transaction going dead (will never confirm) due to a double spend.</p>
 *
 * <p>The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last.</p>
 *///from  ww  w . j  a  v a2s.c  o  m
public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks)
        throws VerificationException {
    lock.lock();
    try {
        // This runs on any peer thread with the block chain locked.
        //
        // The reorganize functionality of the wallet is tested in ChainSplitTest.java
        //
        // receive() has been called on the block that is triggering the re-org before this is called, with type
        // of SIDE_CHAIN.
        //
        // Note that this code assumes blocks are not invalid - if blocks contain duplicated transactions,
        // transactions that double spend etc then we can calculate the incorrect result. This could open up
        // obscure DoS attacks if someone successfully mines a throwaway invalid block and feeds it to us, just
        // to try and corrupt the internal data structures. We should try harder to avoid this but it's tricky
        // because there are so many ways the block can be invalid.

        // Avoid spuriously informing the user of wallet/tx confidence changes whilst we're re-organizing.
        checkState(confidenceChanged.size() == 0);
        checkState(!insideReorg);
        insideReorg = true;
        checkState(onWalletChangedSuppressions == 0);
        onWalletChangedSuppressions++;

        // Map block hash to transactions that appear in it. We ensure that the map values are sorted according
        // to their relative position within those blocks.
        ArrayListMultimap<Sha256Hash, TxOffsetPair> mapBlockTx = ArrayListMultimap.create();
        for (Transaction tx : getTransactions(true)) {
            Map<Sha256Hash, Integer> appearsIn = tx.getAppearsInHashes();
            if (appearsIn == null)
                continue; // Pending.
            for (Map.Entry<Sha256Hash, Integer> block : appearsIn.entrySet())
                mapBlockTx.put(block.getKey(), new TxOffsetPair(tx, block.getValue()));
        }
        for (Sha256Hash blockHash : mapBlockTx.keySet())
            Collections.sort(mapBlockTx.get(blockHash));

        List<Sha256Hash> oldBlockHashes = new ArrayList<Sha256Hash>(oldBlocks.size());

        /* CSPK-mike START */
        int MinHeight = -1;
        int MaxHeight = -1;
        /* CSPK-mike END */

        log.info("Old part of chain (top to bottom):");
        for (StoredBlock b : oldBlocks) {
            /* CSPK-mike START */
            if (MinHeight == -1) {
                MinHeight = b.getHeight();
                MaxHeight = b.getHeight();
            } else {
                if (b.getHeight() < MinHeight) {
                    MinHeight = b.getHeight();
                }
                if (b.getHeight() > MaxHeight) {
                    MaxHeight = b.getHeight();
                }
            }
            /* CSPK-mike END */
            log.info("  {}", b.getHeader().getHashAsString());
            oldBlockHashes.add(b.getHeader().getHash());
        }

        /* CSPK-mike START */
        // Asset references for removed blocks should be cleared.
        CS.log.info("Blockchain reorganizing. Removing blocks " + MinHeight + " - " + MaxHeight);
        CS.clearAssetRefs(MinHeight, MaxHeight);
        /* CSPK-mike END */

        log.info("New part of chain (top to bottom):");
        for (StoredBlock b : newBlocks) {
            /* CSPK-mike START */
            CS.log.info("New block " + b.getHeight() + ": " + b.getHeader().getHashAsString());
            /* CSPK-mike END */
            log.info("  {}", b.getHeader().getHashAsString());
        }

        Collections.reverse(newBlocks); // Need bottom-to-top but we get top-to-bottom.

        // For each block in the old chain, disconnect the transactions in reverse order.
        LinkedList<Transaction> oldChainTxns = Lists.newLinkedList();
        for (Sha256Hash blockHash : oldBlockHashes) {
            for (TxOffsetPair pair : mapBlockTx.get(blockHash)) {
                Transaction tx = pair.tx;
                final Sha256Hash txHash = tx.getHash();
                if (tx.isCoinBase()) {
                    // All the transactions that we have in our wallet which spent this coinbase are now invalid
                    // and will never confirm. Hopefully this should never happen - that's the point of the maturity
                    // rule that forbids spending of coinbase transactions for 100 blocks.
                    //
                    // This could be recursive, although of course because we don't have the full transaction
                    // graph we can never reliably kill all transactions we might have that were rooted in
                    // this coinbase tx. Some can just go pending forever, like the Satoshi client. However we
                    // can do our best.
                    //
                    // TODO: Is it better to try and sometimes fail, or not try at all?
                    killCoinbase(tx);
                } else {
                    for (TransactionOutput output : tx.getOutputs()) {
                        TransactionInput input = output.getSpentBy();
                        if (input != null)
                            input.disconnect();
                    }
                    for (TransactionInput input : tx.getInputs()) {
                        input.disconnect();
                    }
                    oldChainTxns.add(tx);
                    unspent.remove(txHash);
                    spent.remove(txHash);
                    checkState(!pending.containsKey(txHash));
                    checkState(!dead.containsKey(txHash));
                }
            }
        }

        // Put all the disconnected transactions back into the pending pool and re-connect them.
        for (Transaction tx : oldChainTxns) {
            // Coinbase transactions on the old part of the chain are dead for good and won't come back unless
            // there's another re-org.
            if (tx.isCoinBase())
                continue;
            log.info("  ->pending {}", tx.getHash());
            tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); // Wipe height/depth/work data.
            confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE);
            addWalletTransaction(Pool.PENDING, tx);
            updateForSpends(tx, false);
        }

        // Note that dead transactions stay dead. Consider a chain that Finney attacks T1 and replaces it with
        // T2, so we move T1 into the dead pool. If there's now a re-org to a chain that doesn't include T2, it
        // doesn't matter - the miners deleted T1 from their mempool, will resurrect T2 and put that into the
        // mempool and so T1 is still seen as a losing double spend.

        // The old blocks have contributed to the depth and work done for all the transactions in the
        // wallet that are in blocks up to and including the chain split block.
        // The total depth and work done is calculated here and then subtracted from the appropriate transactions.
        int depthToSubtract = oldBlocks.size();
        BigInteger workDoneToSubtract = BigInteger.ZERO;
        for (StoredBlock b : oldBlocks) {
            workDoneToSubtract = workDoneToSubtract.add(b.getHeader().getWork());
        }
        log.info("depthToSubtract = " + depthToSubtract + ", workDoneToSubtract = " + workDoneToSubtract);
        // Remove depthToSubtract and workDoneToSubtract from all transactions in the wallet except for pending.
        subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, spent.values());
        subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, unspent.values());
        subtractDepthAndWorkDone(depthToSubtract, workDoneToSubtract, dead.values());

        // The effective last seen block is now the split point so set the lastSeenBlockHash.
        setLastBlockSeenHash(splitPoint.getHeader().getHash());

        // For each block in the new chain, work forwards calling receive() and notifyNewBestBlock().
        // This will pull them back out of the pending pool, or if the tx didn't appear in the old chain and
        // does appear in the new chain, will treat it as such and possibly kill pending transactions that
        // conflict.
        for (StoredBlock block : newBlocks) {
            log.info("Replaying block {}", block.getHeader().getHashAsString());
            for (TxOffsetPair pair : mapBlockTx.get(block.getHeader().getHash())) {
                log.info("  tx {}", pair.tx.getHash());
                try {
                    receive(pair.tx, block, BlockChain.NewBlockType.BEST_CHAIN, pair.offset);
                } catch (ScriptException e) {
                    throw new RuntimeException(e); // Cannot happen as these blocks were already verified.
                }
            }
            notifyNewBestBlock(block);
        }
        checkState(isConsistent());
        final BigInteger balance = getBalance();
        log.info("post-reorg balance is {}", Utils.bitcoinValueToFriendlyString(balance));
        // Inform event listeners that a re-org took place.
        queueOnReorganize();
        insideReorg = false;
        onWalletChangedSuppressions--;
        maybeQueueOnWalletChanged();
        checkBalanceFuturesLocked(balance);
        informConfidenceListenersIfNotReorganizing();
        saveLater();
    } finally {
        lock.unlock();
    }
}

From source file:com.google.bitcoin.core.Wallet.java

@Nullable
private Transaction rekeyOneBatch(long keyRotationTimestamp, final TransactionBroadcaster broadcaster) {
    final Transaction rekeyTx;

    lock.lock();/*  ww w.java2 s . c  o m*/
    try {
        // Firstly, see if we have any keys that are beyond the rotation time, and any before.
        ECKey safeKey = null;
        boolean haveRotatingKeys = false;
        for (ECKey key : keychain) {
            final long t = key.getCreationTimeSeconds();
            if (t < keyRotationTimestamp) {
                haveRotatingKeys = true;
            } else {
                safeKey = key;
            }
        }
        if (!haveRotatingKeys)
            return null;
        if (safeKey == null) {
            log.warn("Key rotation requested but no keys newer than the timestamp are available.");
            return null;
        }
        // Build the transaction using some custom logic for our special needs. Last parameter to
        // KeyTimeCoinSelector is whether to ignore pending transactions or not.
        //
        // We ignore pending outputs because trying to rotate these is basically racing an attacker, and
        // we're quite likely to lose and create stuck double spends. Also, some users who have 0.9 wallets
        // have already got stuck double spends in their wallet due to the Bloom-filtering block reordering
        // bug that was fixed in 0.10, thus, making a re-key transaction depend on those would cause it to
        // never confirm at all.
        CoinSelector selector = new KeyTimeCoinSelector(this, keyRotationTimestamp, true);
        CoinSelection toMove = selector.select(BigInteger.ZERO, calculateAllSpendCandidates(true));
        if (toMove.valueGathered.equals(BigInteger.ZERO))
            return null; // Nothing to do.
        rekeyTx = new Transaction(params);
        for (TransactionOutput output : toMove.gathered) {
            rekeyTx.addInput(output);
        }
        rekeyTx.addOutput(toMove.valueGathered, safeKey);
        if (!adjustOutputDownwardsForFee(rekeyTx, toMove, BigInteger.ZERO,
                Transaction.REFERENCE_DEFAULT_MIN_TX_FEE)) {
            log.error("Failed to adjust rekey tx for fees.");
            return null;
        }
        rekeyTx.getConfidence().setSource(TransactionConfidence.Source.SELF);
        rekeyTx.setPurpose(Transaction.Purpose.KEY_ROTATION);
        rekeyTx.signInputs(Transaction.SigHash.ALL, this);
        // KeyTimeCoinSelector should never select enough inputs to push us oversize.
        checkState(rekeyTx.bitcoinSerialize().length < Transaction.MAX_STANDARD_TX_SIZE);
        commitTx(rekeyTx);
    } catch (VerificationException e) {
        throw new RuntimeException(e); // Cannot happen.
    } finally {
        lock.unlock();
    }
    if (broadcaster == null)
        return rekeyTx;

    log.info("Attempting to send key rotation tx: {}", rekeyTx);
    // We must broadcast the tx in a separate thread to avoid inverting any locks. Otherwise we may be running
    // with the blockchain lock held (whilst receiving a block) and thus re-entering the peerGroup would invert
    // blockchain <-> peergroup.
    new Thread() {
        @Override
        public void run() {
            // Handle the future results just for logging.
            try {
                Futures.addCallback(broadcaster.broadcastTransaction(rekeyTx),
                        new FutureCallback<Transaction>() {
                            @Override
                            public void onSuccess(Transaction transaction) {
                                log.info("Successfully broadcast key rotation tx: {}", transaction);
                            }

                            @Override
                            public void onFailure(Throwable throwable) {
                                log.error("Failed to broadcast key rotation tx", throwable);
                            }
                        });
            } catch (Exception e) {
                log.error("Failed to broadcast rekey tx, will try again later", e);
            }
        }
    }.start();
    return rekeyTx;
}

From source file:com.peterbochs.PeterBochsDebugger.java

private void jRefreshAddressTranslateButtonActionPerformed(ActionEvent evt) {
    AddressTranslateTableModel model = (AddressTranslateTableModel) this.jAddressTranslateTable2.getModel();

    if (jSearchAddressRadioButton1.isSelected()) {
        if (!this.jAddressTextField.getText().contains(":")
                || this.jAddressTextField.getText().replaceAll("[^:]", "").length() != 1) {
            JOptionPane.showMessageDialog(this,
                    "Error, please input <segment selector>:<offset>\n\ne.g. : 0x10:0x12345678", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }/*from   w ww.  j a  v a2s  .c  o m*/
        BigInteger segSelector = CommonLib.string2BigInteger(this.jAddressTextField.getText().split(":")[0]);
        BigInteger address = CommonLib.string2BigInteger(this.jAddressTextField.getText().split(":")[1]);

        // for (int x = 0; x < model.getRowCount(); x++) {
        // if (model.searchType.get(x).equals(1) &&
        // model.searchSegSelector.get(x).equals(segSelector) &&
        // model.searchAddress.get(x).equals(address)) {
        // return;
        // }
        // }

        model.searchType.add(1);
        model.searchSegSelector.add(segSelector);
        model.searchAddress.add(address);

        model.virtualAddress.add(address);
        BigInteger segNo = segSelector.shiftRight(3);
        model.segNo.add(segNo);

        // read GDT descriptor
        int descriptor[] = PeterBochsCommonLib
                .getMemoryFromBochs(CommonLib.string2BigInteger(this.registerPanel.jGDTRTextField.getText())
                        .add(segNo.multiply(BigInteger.valueOf(8))), 8);
        BigInteger baseAddress = CommonLib.getBigInteger(descriptor[2], descriptor[3], descriptor[4],
                descriptor[7], 0, 0, 0, 0);
        BigInteger linearAddress = baseAddress.add(address);
        model.baseAddress.add(baseAddress);
        model.linearAddress.add(linearAddress);

        BigInteger pdNo = CommonLib.getBigInteger(linearAddress, 31, 22);
        model.pdNo.add(pdNo);
        int pdeBytes[] = PeterBochsCommonLib
                .getMemoryFromBochs(CommonLib.string2BigInteger(this.registerPanel.jCR3TextField.getText())
                        .add(pdNo.multiply(BigInteger.valueOf(4))), 4);
        BigInteger pde = CommonLib.getBigInteger(pdeBytes, 0);
        model.pde.add(pde);

        BigInteger ptNo = CommonLib.getBigInteger(linearAddress, 21, 12);
        model.ptNo.add(ptNo);
        BigInteger pageTableBaseAddress = pde.and(CommonLib.string2BigInteger("0xfffff000"));
        int pteBytes[] = PeterBochsCommonLib
                .getMemoryFromBochs(pageTableBaseAddress.add(ptNo.multiply(BigInteger.valueOf(4))), 4);
        BigInteger pte = CommonLib.getBigInteger(pteBytes, 0);
        BigInteger pagePhysicalAddress = pte.and(CommonLib.string2BigInteger("0xfffff000"));
        model.pte.add(pte);

        BigInteger physicalAddress = pagePhysicalAddress.add(CommonLib.getBigInteger(linearAddress, 11, 0));
        model.physicalAddress.add(physicalAddress);
        int bytesAtPhysicalAddress[] = PeterBochsCommonLib.getMemoryFromBochs(physicalAddress, 8);
        model.bytes.add(PeterBochsCommonLib.convertToString(bytesAtPhysicalAddress));

        model.fireTableDataChanged();
    } else if (jSearchAddressRadioButton2.isSelected()) {
        // for (int x = 0; x < model.getRowCount(); x++) {
        // if (model.searchType.get(x).equals(2) &&
        // model.searchAddress.get(x).equals(CommonLib.string2long(this.jAddressTextField.getText())))
        // {
        // return;
        // }
        // }
        BigInteger address = CommonLib.string2BigInteger(this.jAddressTextField.getText());

        model.searchType.add(2);
        model.searchAddress.add(address);

        BigInteger baseAddress = BigInteger.ZERO;
        BigInteger linearAddress = baseAddress.add(address);
        model.baseAddress.add(baseAddress);
        model.linearAddress.add(linearAddress);

        BigInteger pdNo = CommonLib.getBigInteger(linearAddress, 31, 22);
        model.pdNo.add(pdNo);
        int pdeBytes[] = PeterBochsCommonLib
                .getMemoryFromBochs(CommonLib.string2BigInteger(this.registerPanel.jCR3TextField.getText())
                        .add(pdNo.multiply(BigInteger.valueOf(4))), 4);
        BigInteger pde = CommonLib.getBigInteger(pdeBytes, 0);
        model.pde.add(pde);

        BigInteger ptNo = CommonLib.getBigInteger(linearAddress, 21, 12);
        model.ptNo.add(ptNo);
        BigInteger pageTableBaseAddress = pde.and(CommonLib.string2BigInteger("0xfffff000"));
        int pteBytes[] = PeterBochsCommonLib
                .getMemoryFromBochs(pageTableBaseAddress.add(ptNo.multiply(BigInteger.valueOf(4))), 4);
        BigInteger pte = CommonLib.getBigInteger(pteBytes, 0);
        BigInteger pagePhysicalAddress = pte.and(CommonLib.string2BigInteger("0xfffff000"));
        model.pte.add(pte);

        BigInteger physicalAddress = pagePhysicalAddress.add(CommonLib.getBigInteger(linearAddress, 11, 0));
        model.physicalAddress.add(physicalAddress);
        int bytesAtPhysicalAddress[] = PeterBochsCommonLib.getMemoryFromBochs(physicalAddress, 8);
        model.bytes.add(PeterBochsCommonLib.convertToString(bytesAtPhysicalAddress));

        model.fireTableDataChanged();
    } else if (jSearchAddressRadioButton3.isSelected()) {
        for (int x = 0; x < model.getRowCount(); x++) {
            if (model.searchType.get(x).equals(3) && model.searchAddress.get(x)
                    .equals(CommonLib.string2long(this.jAddressTextField.getText()))) {
                return;
            }
        }
        BigInteger addr = CommonLib.string2BigInteger(this.jAddressTextField.getText());
        model.searchType.add(3);
        model.searchSegSelector.add(BigInteger.ZERO);
        model.searchAddress.add(addr);
        model.virtualAddress.add(BigInteger.ZERO);
        model.segNo.add(BigInteger.ZERO);
        model.linearAddress.add(BigInteger.ZERO);
        model.pdNo.add(BigInteger.ZERO);
        model.ptNo.add(BigInteger.ZERO);
        model.physicalAddress.add(BigInteger.ZERO);
        model.bytes.add("");

        model.fireTableDataChanged();
    }
}