Example usage for java.math BigInteger valueOf

List of usage examples for java.math BigInteger valueOf

Introduction

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

Prototype

private static BigInteger valueOf(int val[]) 

Source Link

Document

Returns a BigInteger with the given two's complement representation.

Usage

From source file:jp.aegif.nemaki.cmis.service.impl.ObjectServiceImpl.java

private ContentStream getRenditionStream(String repositoryId, Content content, String streamId) {
    if (!content.isDocument() && !content.isFolder()) {
        exceptionService.constraint(content.getId(),
                "getRenditionStream cannnot be invoked to other than document or folder type.");
    }/*w ww  .  j  a v  a  2 s.  com*/

    exceptionService.constraintRenditionStreamDownload(content, streamId);

    Rendition rendition = contentService.getRendition(repositoryId, streamId);

    BigInteger length = BigInteger.valueOf(rendition.getLength());
    String mimeType = rendition.getMimetype();
    InputStream is = rendition.getInputStream();
    ContentStream cs = new ContentStreamImpl("preview_" + streamId, length, mimeType, is);

    return cs;
}

From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

@SuppressWarnings("unchecked")
List<IdentifiableType> invokeParameterizedQuery(ServerRequestContext context, String queryId,
        Map<String, String> queryParams, UserType user, int startIndex, int maxResults)
        throws RegistryException {

    List<IdentifiableType> ebRegistryObjectTypeList = null;

    try {/* w  ww .  ja va2  s  . c  o  m*/
        AdhocQueryRequest req = BindingUtility.getInstance()
                .createAdhocQueryRequest("SELECT * FROM DummyTable");
        req.setStartIndex(BigInteger.valueOf(startIndex));
        req.setMaxResults(BigInteger.valueOf(maxResults));

        Map<String, String> slotsMap = new HashMap<String, String>();
        slotsMap.put(BindingUtility.CANONICAL_SLOT_QUERY_ID, queryId);
        if ((queryParams != null) && (queryParams.size() > 0)) {
            slotsMap.putAll(queryParams);
        }
        BindingUtility.getInstance().addSlotsToRequest(req, slotsMap);

        // Now execute the query
        HashMap<String, Object> idToRepositoryItemMap = new HashMap<String, Object>();
        context.setRepositoryItemsMap(idToRepositoryItemMap);

        boolean doCommit = false;
        try {
            context.pushRegistryRequest(req);
            AdhocQueryResponse ebAdhocQueryResponse = qm.submitAdhocQuery(context);
            bu.checkRegistryResponse(ebAdhocQueryResponse);
            ebRegistryObjectTypeList = (List<IdentifiableType>) bu
                    .getIdentifiableTypeList(ebAdhocQueryResponse.getRegistryObjectList());
            doCommit = true;
        } finally {
            context.popRegistryRequest();
            try {
                closeContext(context, doCommit);
            } catch (Exception ex) {
                log.error(ex, ex);
            }
        }
    } catch (JAXBException e) {
        throw new RegistryException(e);
    } catch (JAXRException e) {
        throw new RegistryException(e);
    }

    return ebRegistryObjectTypeList;
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

@Override
public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey, Date notAfter) {
    signer = (signingKey == null ? signer : subjectDn);
    signingKey = (signingKey == null ? keys.getPrivate() : signingKey);
    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);/*from   w  w w.  j  ava 2 s  . com*/
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keys.getPublic()));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(keys.getPublic());
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:ch.oakmountain.tpa.solver.TrainPathAllocationProblemStatistics.java

private void compileSummaryTable() throws IOException {
    TablePersistor summaryTable = new TablePersistor("summary", outputDir, "Train Path Allocation Problem",
            getHeader());/*from  www.  ja  va  2 s.co  m*/

    for (TrainPathSlot trainPathSlot : arcNodeUnitCapacityCounts.keySet()) {
        int count = arcNodeUnitCapacityCounts.get(trainPathSlot);
        arcNodeUnitCapacityConstraints += 1;
        arcNodeUnitCapacityConstraintTerms += count;
    }
    for (TrainPathSlot trainPathSlot : pathBasedConflictCounts.keySet()) {
        int count = pathBasedConflictCounts.get(trainPathSlot);
        pathBasedSolutionCandidateConflictConstraints += 1;
        pathBasedSolutionCandidateConflictTerms += count;
    }

    // arc-node
    // - flow constraints: sum of nb verticies of all DAGs (terms per constraint: nb of solution candidates)
    // - unit capacity: nb of slots of all DAGs (terms per constraint: at most one term per application)
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "feasible requests",
            String.valueOf(feasibleSimpleTrainPathApplications.size())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "infeasible requests",
            String.valueOf(infeasibleSimpleTrainPathApplications.size())));
    summaryTable.writeRow(
            Arrays.asList("arc-node/path-based", "total number of train paths", String.valueOf(totalNbPaths)));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global minimum dwell time",
            PeriodicalTimeFrame.formatDuration(
                    feasibleSimpleTrainPathApplications.get(0).getParams().getHARD_MINIMUM_DWELL_TIME())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global maximum earlier departure time",
            PeriodicalTimeFrame.formatDuration(feasibleSimpleTrainPathApplications.get(0).getParams()
                    .getHARD_MAXIMUM_EARLIER_DEPARTURE())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global maximum later arrival time",
            PeriodicalTimeFrame.formatDuration(
                    feasibleSimpleTrainPathApplications.get(0).getParams().getHARD_MAXIMUM_LATER_ARRIVAL())));

    summaryTable.writeRow(
            Arrays.asList("arc-node", "flow constraints", String.valueOf(arcNodeFlowConstraintsCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "terms in flow constraints",
            String.valueOf(arcNodeFlowConstraintTermsCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraints)));
    summaryTable.writeRow(Arrays.asList("arc-node", "terms in unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraintTerms)));
    BigInteger arcNodeConstraints = BigInteger
            .valueOf(arcNodeFlowConstraintsCount + arcNodeUnitCapacityConstraints);
    summaryTable.writeRow(Arrays.asList("arc-node", "rows (constraints)", String.valueOf(arcNodeConstraints)));
    summaryTable
            .writeRow(Arrays.asList("arc-node", "columns (variables)", String.valueOf(arcNodeVariablesCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "train path slots",
            String.valueOf(arcNodeUnitCapacityCounts.keySet().size())));
    BigInteger arcNodeTerms = BigInteger
            .valueOf(arcNodeFlowConstraintTermsCount + arcNodeUnitCapacityConstraintTerms);
    BigInteger arcNodeFlowConstraintMatrixSize = BigInteger.valueOf(arcNodeFlowConstraintTermsCount)
            .multiply(BigInteger.valueOf(arcNodeVariablesCount));
    BigInteger arcNodeUnitCapacityConstraintMatrixSize = BigInteger.valueOf(arcNodeUnitCapacityConstraintTerms)
            .multiply(BigInteger.valueOf(arcNodeVariablesCount));
    BigInteger arcNodeMatrixSize = arcNodeConstraints.multiply(BigInteger.valueOf(arcNodeVariablesCount));
    summaryTable.writeRow(Arrays.asList("arc-node", "sparsity in flow constraints",
            String.valueOf(arcNodeFlowConstraintTermsCount + "/" + arcNodeFlowConstraintMatrixSize + " ("
                    + (new BigDecimal(arcNodeFlowConstraintTermsCount))
                            .divide((new BigDecimal(arcNodeFlowConstraintMatrixSize)), 10, RoundingMode.HALF_UP)
                    + ")")));
    summaryTable.writeRow(Arrays.asList("arc-node", "sparsity in unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraintTerms + "/" + arcNodeUnitCapacityConstraintMatrixSize
                    + " ("
                    + (new BigDecimal(arcNodeUnitCapacityConstraintTerms)).divide(
                            (new BigDecimal(arcNodeUnitCapacityConstraintMatrixSize)), 10, RoundingMode.HALF_UP)
                    + ")")));
    summaryTable
            .writeRow(
                    Arrays.asList("arc-node", "sparsity in all constraints",
                            String.valueOf(arcNodeTerms
                                    + "/" + arcNodeMatrixSize + " (" + (new BigDecimal(arcNodeTerms))
                                            .divide(new BigDecimal(arcNodeMatrixSize), 10, RoundingMode.HALF_UP)
                                    + ")")));

    // path-based
    // - solution candidate choice: nb of applications (terms per constraint: nb of solution canidates)
    // - conflict sets: nb of slots of all DAGs (terms per constraint: possibly many terms per application)
    summaryTable.writeRow(Arrays.asList("path-based", "choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "terms in choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictConstraints)));
    summaryTable.writeRow(Arrays.asList("path-based", "terms in conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictTerms)));
    summaryTable.writeRow(Arrays.asList("path-based", "enumeration rate ",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount + "/" + totalNbPaths + "("
                    + ((double) pathBasedSolutionCandidateChoiceTermsCount / totalNbPaths) + ")")));
    BigInteger pathBasedConstraints = BigInteger.valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)
            .add(BigInteger.valueOf(pathBasedSolutionCandidateConflictConstraints));
    summaryTable
            .writeRow(Arrays.asList("path-based", "rows (constraints)", String.valueOf(pathBasedConstraints)));
    summaryTable.writeRow(
            Arrays.asList("path-based", "columns (variables)", String.valueOf(pathBasedVariablesCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "train path slots",
            String.valueOf(pathBasedConflictCounts.keySet().size())));
    BigInteger pathBasedTerms = BigInteger.valueOf(pathBasedSolutionCandidateConflictTerms)
            .add(BigInteger.valueOf(pathBasedSolutionCandidateChoiceTermsCount));
    BigInteger pathBasedMatrixSize = pathBasedConstraints.multiply(BigInteger.valueOf(pathBasedVariablesCount));
    BigInteger pathBasedSolutionCandidateChoiceMatrixSize = BigInteger
            .valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)
            .multiply(BigInteger.valueOf(pathBasedVariablesCount));
    BigInteger pathBasedSolutionCandidateConflictMatrixSize = BigInteger
            .valueOf(pathBasedSolutionCandidateConflictConstraints)
            .multiply(BigInteger.valueOf(pathBasedVariablesCount));
    summaryTable.writeRow(Arrays.asList("path-based", "sparsity in choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount + "/"
                    + pathBasedSolutionCandidateChoiceMatrixSize + " ("
                    + (new BigDecimal(pathBasedSolutionCandidateChoiceTermsCount)).divide(
                            new BigDecimal(pathBasedSolutionCandidateChoiceMatrixSize), 10,
                            RoundingMode.HALF_UP)
                    + ")")));
    summaryTable.writeRow(Arrays.asList("path-based", "sparsity in conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictTerms + "/"
                    + pathBasedSolutionCandidateConflictMatrixSize + " ("
                    + (new BigDecimal(pathBasedSolutionCandidateConflictTerms)).divide(
                            (new BigDecimal(pathBasedSolutionCandidateConflictMatrixSize)), 10,
                            RoundingMode.HALF_UP)
                    + ")")));
    summaryTable
            .writeRow(
                    Arrays.asList("path-based", "sparsity in all constraints",
                            String.valueOf(pathBasedTerms + "/" + pathBasedMatrixSize + " ("
                                    + (new BigDecimal(pathBasedTerms)).divide(
                                            (new BigDecimal(pathBasedMatrixSize)), 10, RoundingMode.HALF_UP)
                                    + ")")));

    summaryTable.finishTable();

    if (!(arcNodeUnitCapacityCounts.keySet().size() >= pathBasedConflictCounts.keySet().size())) {
        throw new IllegalStateException(
                "nb of train path slots in arc node model has to be larger or equal to the number of train path slots in the path based model (because of partial enumeration)");
    }

    // LaTeX table output
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance();
    //DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();

    //symbols.setGroupingSeparator(' ');
    //formatter.setDecimalFormatSymbols(symbols);
    File latexFile = new File(outputDir + File.separator + "computational.tex");
    FileUtils.writeStringToFile(latexFile, "Number of feasible applications:&\\multicolumn{2}{c|}{"
            + formatter.format(feasibleSimpleTrainPathApplications.size()) + "}\\\\\n");
    FileUtils.writeStringToFile(latexFile,
            "Number of variables      &" + formatter.format(arcNodeVariablesCount) + "&"
                    + formatter.format(pathBasedVariablesCount) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "Number of constraints   &" + formatter.format(arcNodeConstraints)
            + "&" + formatter.format(pathBasedConstraints) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of unit capacity / conflict constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&" + formatter.format(arcNodeUnitCapacityConstraints)
                    + "                                         &"
                    + formatter.format(pathBasedSolutionCandidateConflictConstraints) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "%    Matrix size                     &"
            + formatter.format(arcNodeMatrixSize) + "&" + formatter.format(pathBasedMatrixSize) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "%Number of terms           &" + formatter.format(arcNodeTerms) + "&"
            + formatter.format(pathBasedTerms) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of terms in unit capacity/", true);
    FileUtils.writeStringToFile(latexFile,
            "&" + formatter.format(arcNodeUnitCapacityConstraintTerms) + "& \\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "\\hspace{0.5cm}choice constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&&" + formatter.format(pathBasedSolutionCandidateChoiceTermsCount) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of terms in flow conservation/", true);
    FileUtils.writeStringToFile(latexFile, "&" + formatter.format(arcNodeFlowConstraintTermsCount) + "& \\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "\\hspace{0.5cm}conflict constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&&" + formatter.format(pathBasedSolutionCandidateConflictTerms) + "\\\\\n", true);
}

From source file:ch.admin.hermes.etl.load.cmis.AlfrescoCMISClient.java

/**
 * Laedt eine Datei von http://www.hermes.admin.ch in Alfresco hoch.
 * @param parentId Parent Id/*from  ww w. jav a 2s. c o m*/
 * @param name Name
 * @param properties Eigenschaften
 * @param localname Lokaler Name wenn Datei oder URL wenn von http://www.hermes.admin.ch
 * @return neu erstelles Dokument
 * @throws Exception Allgemeiner I/O Fehler
 */
private Document postFile(String parentId, String name, HashMap<String, Object> properties, URL url)
        throws IOException, URISyntaxException {
    Folder parent = (Folder) session.getObject(parentId, session.getDefaultContext());

    // Dokument von http://www.hermes.admin.ch holen
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (url != null) {
        HttpGet req = new HttpGet(url.toURI());
        req.addHeader("Accept", "application/json;odata=verbose;charset=utf-8");
        req.addHeader("Content-Type", "application/octet-stream");

        HttpResponse resp = client.execute(req);
        checkError(resp, url.toString());

        byte buf[] = new byte[128 * 32768];
        InputStream inp = resp.getEntity().getContent();
        for (int length; (length = inp.read(buf, 0, buf.length)) > 0;)
            out.write(buf, 0, length);
        out.close();

        EntityUtils.consume(resp.getEntity());
    }
    String mimeType = mimeTypesMap.getContentType(url.getFile());
    if (properties == null)
        properties = new HashMap<String, Object>();

    properties.put("cmis:name", name);
    // This works because we are using the OpenCMIS extension for Alfresco
    properties.put("cmis:objectTypeId", "cmis:document,P:cm:titled");

    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    ContentStream contentStream = new ContentStreamImpl(name, BigInteger.valueOf(out.size()), mimeType, in);
    properties.put(PropertyIds.CONTENT_STREAM_FILE_NAME, name);
    properties.put(PropertyIds.CONTENT_STREAM_LENGTH, out.size());
    properties.put(PropertyIds.CONTENT_STREAM_MIME_TYPE, mimeType);

    Document doc = parent.createDocument(properties, contentStream, VersioningState.MAJOR);
    in.close();
    return (doc);
}

From source file:it.cnr.icar.eric.server.query.QueryManagerImpl.java

/**
 * submitAdhocQuery//from   w ww.  j  a v  a2 s .  c om
 */
@SuppressWarnings({ "static-access", "unchecked" })
public AdhocQueryResponse submitAdhocQuery(RequestContext context) throws RegistryException {

    AdhocQueryResponse ebAdhocQueryResponse = null;
    context = ServerRequestContext.convert(context);

    AdhocQueryRequest ebAdhocQueryRequest = (AdhocQueryRequest) ((ServerRequestContext) context)
            .getCurrentRegistryRequest();
    ResponseOptionType ebResponseOptionType = ebAdhocQueryRequest.getResponseOption();
    ReturnType returnType = ebResponseOptionType.getReturnType();

    UserType user = ((ServerRequestContext) context).getUser();

    // The result of the query
    RegistryObjectListType ebRegistryObjectListType = null;

    try {
        ebAdhocQueryResponse = null;

        // Process request for the case where it is a parameterized
        // invocation of a stored query
        processForParameterizedQuery((ServerRequestContext) context);

        // TODO: May need a better way than checking
        // getSpecialQueryResults() to know if specialQuery was called.
        if (((ServerRequestContext) context).getSpecialQueryResults() != null) {
            ebAdhocQueryResponse = processForSpecialQueryResults((ServerRequestContext) context);
        } else {
            // Check if it is a federated query and process it using
            // FederatedQueryManager if so.
            boolean isFederated = ebAdhocQueryRequest.isFederated();
            if (isFederated) {
                // Initialize lazily. Otherwise we have an infinite create
                // loop
                if (fqm == null) {
                    fqm = FederatedQueryManager.getInstance();
                }
                ebAdhocQueryResponse = fqm.submitAdhocQuery((ServerRequestContext) context);
            } else {
                int startIndex = ebAdhocQueryRequest.getStartIndex().intValue();
                int maxResults = ebAdhocQueryRequest.getMaxResults().intValue();
                IterativeQueryParams paramHolder = new IterativeQueryParams(startIndex, maxResults);

                org.oasis.ebxml.registry.bindings.rim.AdhocQueryType adhocQuery = ebAdhocQueryRequest
                        .getAdhocQuery();

                QueryExpressionType queryExp = adhocQuery.getQueryExpression();
                String queryLang = queryExp.getQueryLanguage();
                if (queryLang.equals(BindingUtility.CANONICAL_QUERY_LANGUAGE_ID_SQL_92)) {
                    String queryStr = (String) queryExp.getContent().get(0);
                    queryStr = replaceSpecialVariables(user, queryStr);

                    ebRegistryObjectListType = sqlQueryProcessor.executeQuery((ServerRequestContext) context,
                            user, queryStr, ebResponseOptionType, paramHolder);

                    processDepthParameter((ServerRequestContext) context);

                    ebAdhocQueryResponse = BindingUtility.getInstance().queryFac.createAdhocQueryResponse();

                    ebAdhocQueryResponse.setRegistryObjectList(ebRegistryObjectListType);
                    ebAdhocQueryResponse.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);
                    ebAdhocQueryResponse.setStartIndex(BigInteger.valueOf(paramHolder.startIndex));
                    ebAdhocQueryResponse.setTotalResultCount(BigInteger.valueOf(paramHolder.totalResultCount));

                } else if (queryLang.equals(BindingUtility.CANONICAL_QUERY_LANGUAGE_ID_ebRSFilterQuery)) {
                    String queryStr = (String) queryExp.getContent().get(0);
                    Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext()
                            .createUnmarshaller();
                    JAXBElement<FilterQueryType> ebFilterQuery = (JAXBElement<FilterQueryType>) unmarshaller
                            .unmarshal(new StreamSource(new StringReader(queryStr)));

                    // take ComplexType from Element
                    FilterQueryType filterQuery = ebFilterQuery.getValue();

                    //                  FilterQueryType filterQuery = (FilterQueryType) queryExp.getContent().get(0);

                    ebRegistryObjectListType = filterQueryProcessor.executeQuery(
                            ((ServerRequestContext) context), user, filterQuery, ebResponseOptionType,
                            paramHolder);

                    ebAdhocQueryResponse = BindingUtility.getInstance().queryFac.createAdhocQueryResponse();
                    ebAdhocQueryResponse.setRegistryObjectList(ebRegistryObjectListType);
                    ebAdhocQueryResponse.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);
                    ebAdhocQueryResponse.setStartIndex(BigInteger.valueOf(paramHolder.startIndex));
                    ebAdhocQueryResponse.setTotalResultCount(BigInteger.valueOf(paramHolder.totalResultCount));

                } else {
                    throw new UnsupportedCapabilityException(
                            "Unsupported Query Language: ClassificationNode id: " + queryLang);
                }
            }
        }

        // fetch child objects
        if (fetchChildObjsSrv) {
            HashMap<String, Object> slotsMap = bu.getSlotsFromRequest(ebAdhocQueryRequest);
            boolean fetchChildObjsClt = Boolean
                    .valueOf((String) slotsMap.get(CanonicalConstants.CANONICAL_SLOT_GET_CHILD_OBJECTS))
                    .booleanValue();
            if (fetchChildObjsClt) {
                fetchChildObjects(ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable(),
                        (ServerRequestContext) context, ebResponseOptionType);
            }
        }

        // Add repositoryItems to repositoryItemMap if so requested in
        // responseOption
        if (returnType == returnType.LEAF_CLASS_WITH_REPOSITORY_ITEM) {
            addRepositoryItems(ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable(), context);
        }

        if (!bypassCMS) {
            // Now perform any Role-Based Content Filtering on query results
            ((ServerRequestContext) context).getQueryResults().clear();
            ((ServerRequestContext) context).getQueryResults()
                    .addAll(ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable());

            cmsm.invokeServices(((ServerRequestContext) context));
            ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable().clear();
            ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable()
                    .addAll(((ServerRequestContext) context).getQueryResults());

            ((ServerRequestContext) context).getQueryResults().clear();
        }
    } catch (RegistryException e) {
        ((ServerRequestContext) context).rollback();
        throw e;
    } catch (Exception e) {
        ((ServerRequestContext) context).rollback();

        throw new RegistryException(e);
    }

    removeObjectsDeniedAccess(((ServerRequestContext) context),
            ebAdhocQueryResponse.getRegistryObjectList().getIdentifiable());

    if (isQueryFilterRequestBeingMade((ServerRequestContext) context)) {
        // Handle filter query requests
        processForQueryFilterPlugins((ServerRequestContext) context);
        // Filter queries produce special query results
        ebAdhocQueryResponse = processForSpecialQueryResults((ServerRequestContext) context);
    }

    ((ServerRequestContext) context).commit();
    ebAdhocQueryResponse.setRequestId(ebAdhocQueryRequest.getId());

    return ebAdhocQueryResponse;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepTwoC() throws Exception {
    byte[] send;//from w  w  w . j av a2s  .  c o m
    IHttpRequestResponse response;
    byte[] request;

    BigInteger n = this.pubKey.getModulus();

    loggerInstance.log(getClass(), "Step 2c: Searching with one interval left", Logger.LogLevel.INFO);

    // initial ri computation - ri = 2(b*(si-1)-2*B)/n
    BigInteger ri = this.si.multiply(this.m[0].upper);
    ri = ri.subtract(BigInteger.valueOf(2).multiply(this.bigB));
    ri = ri.multiply(BigInteger.valueOf(2));
    ri = ri.divide(n);

    // initial si computation
    BigInteger upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
    BigInteger lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);

    // to counter .add operation in do while
    this.si = lowerBound.subtract(BigInteger.ONE);

    do {
        // Check if user has cancelled the worker
        if (isCancelled()) {
            loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user",
                    Logger.LogLevel.INFO);
            return;
        }

        this.si = this.si.add(BigInteger.ONE);
        // lowerBound <= si < upperBound
        if (this.si.compareTo(upperBound) > 0) {
            // new values
            ri = ri.add(BigInteger.ONE);
            upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower);
            lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper);
            this.si = lowerBound;
        }
        send = prepareMsg(this.c0, this.si);

        request = this.requestResponse.getRequest();
        String[] components = Decoder.getComponents(this.parameter.getJoseValue());
        components[1] = Decoder.base64UrlEncode(send);

        String newComponentsConcatenated = Decoder.concatComponents(components);

        request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated);

        response = callbacks.makeHttpRequest(this.httpService, request);
        updateAmountRequest();

    } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID);
    loggerInstance.log(getClass(), "Matching response: " + helpers.bytesToString(response.getResponse()),
            Logger.LogLevel.DEBUG);
}

From source file:com.baasbox.controllers.Root.java

/**
 * /root/configuration (POST)// ww  w  .j ava  2 s  .  c  om
 * 
 * this method allows to set (or override) just two configuration parameter (at the moment)
 * the db size Threshold in bytes:
 *       baasbox.db.size 
 * A percentage needed by the console to show alerts on dashboard when DB size is near the defined Threshold
 *       baasbox.db.alert
 * 
 * @return a 200 OK with the new values
 */
@With({ RootCredentialWrapFilter.class })
public static Result overrideConfiguration() {
    Http.RequestBody body = request().body();
    JsonNode bodyJson = body.asJson();
    JsonNode newDBAlert = bodyJson.get(BBConfiguration.DB_ALERT_THRESHOLD);
    JsonNode newDBSize = bodyJson.get(BBConfiguration.DB_SIZE_THRESHOLD);
    try {
        if (newDBAlert != null && !newDBAlert.isInt() && newDBAlert.asInt() < 1)
            throw new IllegalArgumentException(
                    BBConfiguration.DB_ALERT_THRESHOLD + " must be a positive integer value");
        if (newDBSize != null && !newDBSize.isLong() && newDBSize.asInt() < 0)
            throw new IllegalArgumentException(BBConfiguration.DB_SIZE_THRESHOLD
                    + " must be a positive integer value, or 0 to disable it");
    } catch (Throwable e) {
        return badRequest(ExceptionUtils.getMessage(e));
    }
    if (newDBAlert != null)
        BBConfiguration.setDBAlertThreshold(newDBAlert.asInt());
    if (newDBSize != null)
        BBConfiguration.setDBSizeThreshold(BigInteger.valueOf(newDBSize.asLong()));
    HashMap returnMap = new HashMap();
    returnMap.put(BBConfiguration.DB_ALERT_THRESHOLD, BBConfiguration.getDBAlertThreshold());
    returnMap.put(BBConfiguration.DB_SIZE_THRESHOLD, BBConfiguration.getDBSizeThreshold());
    try {
        return ok(new ObjectMapper().writeValueAsString(returnMap));
    } catch (JsonProcessingException e) {
        return internalServerError(ExceptionUtils.getMessage(e));
    }
}

From source file:com.gisnet.cancelacion.webservices.RegistraActualizaYConsultaCaso.java

public InfoDeActualizacion actualizaCaso(String numeroDeCredito, String numeroDeCaso, Date fecha, int status,
        byte[] cartaDeCancelacionPdf, Date fechaEmisionCarta, String numeroDeFolio, String md5,
        String identificadorUnicoNotario) {

    InfoDeActualizacion ida = new InfoDeActualizacion();

    /**com.gisnet.cancelacion.wsclient.pms.Pms_Service pmsService = new com.gisnet.cancelacion.wsclient.pms.Pms_Service();
    com.gisnet.cancelacion.wsclient.pms.Pms pmsPort = pmsService.getPmsPort();
    com.gisnet.cancelacion.wsclient.pms.InfoStatusCaso isc = new com.gisnet.cancelacion.wsclient.pms.InfoStatusCaso(); 
    return port.suma(sumador1, sumador2);
     * **//*from   ww w.  j a  va 2  s.co  m*/

    com.gisnet.cancelacion.wsclient.microflujo.SICANCELACIONOUService microService = new com.gisnet.cancelacion.wsclient.microflujo.SICANCELACIONOUService();
    com.gisnet.cancelacion.wsclient.microflujo.DTCANCELACIONREQ entradas = new com.gisnet.cancelacion.wsclient.microflujo.DTCANCELACIONREQ();
    com.gisnet.cancelacion.wsclient.microflujo.DTCANCELACIONRESP salidas = new com.gisnet.cancelacion.wsclient.microflujo.DTCANCELACIONRESP();

    try {
        //Busca nmero de caso a actualizar   
        FindByRequest fbr = new FindByRequest("numeroCaso", numeroDeCaso);
        FindResponse<CasoInfo> casoresponse = service.find(fbr);

        //System.out.println("CASO ID:      "+ casoresponse.getInfo().getId());

        // si existe el caso
        if (casoresponse.getInfo() != null) {

            // busca la clave del status de caso a actualizar
            FindByRequest clave = new FindByRequest("clave", status);
            FindResponse<StatusCasoInfo> sciResponse = statusService.find(clave);

            //System.out.println("CLAVE 1:    "+ sciResponse.getInfo().getId());

            if (sciResponse.getInfo() != null) {
                //System.out.println("sci Response"+sciResponse.getInfo());
                casoresponse.getInfo().setStatusCaso(sciResponse.getInfo());

            }

            casoresponse.getInfo().setFechaActualizacion(fecha);

            //Agregar nuevos campos
            //AQU?

            long idCarta = casoresponse.getInfo().getCartaCancelacionId();

            //System.out.println("CARTA ID:      "+idCarta);

            if (idCarta != 0) {

                FindByRequest fbr2 = new FindByRequest(idCarta);
                FindResponse<CartaCancelacionInfo> response2 = ccService.find(fbr2);

                response2.getInfo().setCodigoCarta(numeroDeFolio);
                response2.getInfo().setPdf(cartaDeCancelacionPdf);
                response2.getInfo().setFechaEmisionCarta(fechaEmisionCarta);

                UpdateRequest<CartaCancelacionInfo> updateCarta = new UpdateRequest();
                updateCarta.setInfo(response2.getInfo());
                ccService.update(updateCarta);
                //System.out.println("Carta de cancelacin actualizada");
            } else {

                CartaCancelacionInfo cci = new CartaCancelacionInfo();
                SaveRequest<CartaCancelacionInfo> saveRequest = new SaveRequest<>();
                cci.setCodigoCarta(numeroDeFolio);
                cci.setPdf(cartaDeCancelacionPdf);
                cci.setFechaEmisionCarta(fechaEmisionCarta);
                saveRequest.setInfo(cci);
                SaveResponse<CartaCancelacionInfo> save = ccService.save(saveRequest);

                casoresponse.getInfo().setCartaCancelacionId(save.getInfo().getId());

                //System.out.println("Carta de cancelacin creada y asociada.");

                /**ida.setCodigo(4);
                ida.setDescripcion("No se actualiz la informacin del caso");
                ida.setNumeroDeCaso(numeroDeCaso);
                ida.setNumeroDeCredito(numeroDeCredito);**/
            }

            //String id = "YOLIZETH,303,EM";

            String[] datos;
            datos = identificadorUnicoNotario.split(",");

            /**for(int i=0;i<5;i++){
               System.out.println("dato " +i+ " " + datos[i]);
            }**/

            System.out.println("notariaNumero :" + datos[0]);
            System.out.println("nombreNotario :" + datos[1]);
            System.out.println("entidad :" + datos[2]);

            MultipleParams params = new MultipleParams();
            params.add("nombreNotario", datos[1]);
            params.add("notariaNumero", datos[0]);
            params.add("entidadClave", datos[2]);
            //params.add("entidadId", new Long(datos[2]));

            FindResponse<NotarioInfo> notarioResponse = notarioService
                    .find(new FindByRequest("nombreNotarioYentidadIdYnumeroNotariaTxt", params));

            //FindByRequest notario = new FindByRequest(identificadorUnicoNotario);
            //FindResponse<NotarioInfo> notarioResponse = notarioService.find(notario);

            if (notarioResponse.getInfo() != null) {
                //Actualiza el caso              
                casoresponse.getInfo().setNotarioId(notarioResponse.getInfo().getId());
            } else {
                //manda error
                System.out.println(
                        new Date() + ":No encontr notario al momento de actualizar el caso con el notario");
            }

            UpdateRequest<CasoInfo> update = new UpdateRequest();
            update.setInfo(casoresponse.getInfo());
            service.update(update);

            ida.setCodigo(0);
            ida.setDescripcion("Se actualiz correctamente el caso.");
            ida.setNumeroDeCaso(numeroDeCaso);
            ida.setNumeroDeCredito(numeroDeCredito);

            //System.out.println("IDA CODIGO:   "+ ida.getCodigo());

            if (ida.getCodigo() == 0) {

                try {

                    //System.out.println("CLAVE 2:    "+ sciResponse.getInfo().getId());

                    if (sciResponse.getInfo().getId() != 0) {

                        entradas.setEstatus(BigInteger.valueOf(sciResponse.getInfo().getClave()));
                        entradas.setDescripcion(sciResponse.getInfo().getDescripcion());
                    }

                    entradas.setNumeroCredito(numeroDeCredito);
                    entradas.setNumeroCaso(numeroDeCaso);
                    entradas.setTipoOperacion(BigInteger.valueOf(4));

                    entradas.setCarta(null);
                    entradas.setFechaEmision(null);
                    entradas.setNombreAcreditado("");
                    entradas.setEntidad(null);

                    salidas = microService.getHTTPPort().siCANCELACIONOU(entradas);
                    //isc = pmsPort.statusCaso(numeroDeCredito, numeroDeCaso, null, status, null, null, null, null, 4);

                    System.out.println(
                            "Respuesta de WS PI -> Estatus : " + salidas.getDatosCredito().getEstatus());
                    System.out.println("Respuesta de WS PI -> Descripcin : "
                            + salidas.getDatosCredito().getDescripcion());
                }

                catch (Exception e) {

                    ida.setCodigo(2);
                    ida.setDescripcion("Error conexin con web service actualizar status del caso.");
                    ida.setNumeroDeCaso(numeroDeCaso);
                    ida.setNumeroDeCredito(numeroDeCredito);

                }
            }

        } else {
            ida.setCodigo(3);
            ida.setDescripcion("No existe el caso");
            ida.setNumeroDeCaso(numeroDeCaso);
            ida.setNumeroDeCredito(numeroDeCredito);
        }

    } catch (Exception e) {

        //System.out.println("ACTUALIZA ERROR:               "+e.getMessage());

        if (e.getMessage().equals(
                "Could not open connection; nested exception is org.hibernate.exception.JDBCConnectionException: Could not open connection")) {
            ida.setCodigo(2);
            ida.setDescripcion("No hay conexin con la base de datos.");
            ida.setNumeroDeCaso(numeroDeCaso);
            ida.setNumeroDeCredito(numeroDeCredito);
            //System.out.println(e.toString());
        } else {

            ida.setCodigo(4);
            ida.setDescripcion("No se actualiz la informacin del caso");
            ida.setNumeroDeCaso(numeroDeCaso);
            ida.setNumeroDeCredito(numeroDeCredito);
            //System.out.println(e);
        }

    }

    return ida;
}

From source file:org.mule.modules.quickbooks.windows.api.DefaultQuickBooksWindowsClient.java

/**
 * Returns all the results from QB//from  www .  j a v a  2  s  . c o m
 * 
 * @return List with all the results
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Iterable findObjects(final OAuthCredentials credentials, final WindowsEntityType type, Integer startPage,
        Integer chunkSize, final Object query) {
    Validate.notNull(type);

    List<Object> listOfResults = new ArrayList<Object>();
    Boolean hasMoreResults = true;
    Boolean externalPagination = false;
    Integer pageNumber = 1;

    if (startPage != null && chunkSize != null) {
        setResultsPerPage(chunkSize);
        pageNumber = startPage;
        externalPagination = true;
    }

    HttpUriRequest httpRequest;
    Object responseObject;

    String str = String.format("%s/%s/v2/%s", credentials.getBaseUri(), type.getResouceName(),
            credentials.getRealmId());

    while (hasMoreResults) {
        httpRequest = new HttpPost(str);
        httpRequest.addHeader("Content-Type", "text/xml");

        ((QueryBase) query).setStartPage(BigInteger.valueOf(pageNumber));
        ((QueryBase) query).setChunkSize(getResultsPerPage());

        prepareToPost(query, httpRequest);

        try {
            responseObject = makeARequestToQuickbooks(httpRequest, credentials, false);
            if (responseObject instanceof ErrorResponse) {
                throw new QuickBooksRuntimeException(new ErrorInfo(responseObject));
            }
        } catch (QuickBooksRuntimeException e) {
            if (e.isAExpiredTokenFault()) {
                destroyAccessToken(credentials);
                responseObject = makeARequestToQuickbooks(httpRequest, credentials, false);
            } else {
                throw e;
            }
        }

        List intuitList = getListFromIntuitResponse(responseObject, type);

        if (intuitList != null) {
            listOfResults.addAll(intuitList);
            hasMoreResults = (intuitList.size() >= getResultsPerPage()) && !externalPagination;
            pageNumber++;
        } else {
            hasMoreResults = false;
        }
    }

    return listOfResults;
}