Example usage for java.math BigInteger intValue

List of usage examples for java.math BigInteger intValue

Introduction

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

Prototype

public int intValue() 

Source Link

Document

Converts this BigInteger to an int .

Usage

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public int associateContentWithRunId(BigInteger runKey, int dataContentKey, int runDataDescriptionId)
        throws ApolloDatabaseException, ApolloDatabaseKeyNotFoundException {

    if (runDataDescriptionId >= 0) {
        String query = "INSERT IGNORE INTO run_data (run_id, description_id, content_id) values (?,?,?)";

        PreparedStatement pstmt;//from www.  j  a  v  a  2  s  . c  o m
        try (Connection conn = datasource.getConnection()) {

            pstmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
            pstmt.setInt(1, runKey.intValue());

            pstmt.setInt(2, runDataDescriptionId);
            pstmt.setInt(3, dataContentKey);
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                ResultSet rs = pstmt.getGeneratedKeys();
                rs.next();
                return rs.getInt(1);
            } else {
                pstmt.close();
                query = "SELECT id FROM run_data WHERE run_id = ? AND description_id = ? and content_id = ?";
                try {
                    pstmt = conn.prepareStatement(query);
                    pstmt.setInt(1, runKey.intValue());
                    pstmt.setInt(2, runDataDescriptionId);
                    pstmt.setInt(3, dataContentKey);
                    ResultSet rs = pstmt.executeQuery();
                    if (rs.next()) {
                        return rs.getInt(1);
                    } else {
                        throw new ApolloDatabaseException("Could not get id for apparently existing run_data.");
                    }
                } finally {
                    pstmt.close();
                }
            }
        } catch (SQLException ex) {
            throw new ApolloDatabaseException(
                    "SQLException associating content with run ID " + runKey + ": " + ex.getMessage());
        }
    } else {
        throw new ApolloDatabaseKeyNotFoundException(
                "associateContentWithRunId() called with an invalid key: " + runKey);
    }

}

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

@Override
public List<TypeDefinitionContainer> getTypeDescendants(String repositoryId, String typeId, BigInteger depth,
        Boolean includePropertyDefinitions, ExtensionsData extension) {
    checkRepositoryId(repositoryId);/*from  w ww . j  ava  2s  . co  m*/

    List<TypeDefinitionContainer> result = new ArrayList<TypeDefinitionContainer>();

    // check depth
    int d = (depth == null ? -1 : depth.intValue());
    if (d == 0) {
        throw new CmisInvalidArgumentException("Depth must not be 0!");
    }

    if (typeId == null) {
        for (TypeDefinitionWrapper tdw : connector.getOpenCMISDictionaryService().getBaseTypes(true)) {
            result.add(getTypesDescendants(d, tdw, includePropertyDefinitions));
        }
    } else {
        TypeDefinitionWrapper tdw = connector.getOpenCMISDictionaryService().findType(typeId);
        if (tdw == null) {
            throw new CmisObjectNotFoundException("Type '" + typeId + "' is unknown!");
        }
        List<TypeDefinitionWrapper> children = connector.getOpenCMISDictionaryService().getChildren(typeId);
        if (children != null) {
            for (TypeDefinitionWrapper child : children) {
                result.add(getTypesDescendants(d, child, includePropertyDefinitions));
            }
        }
    }

    return result;
}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

private BigInteger addDataServiceRunForAllMessageTypes(Object message, int md5CollisionId,
        Authentication authentication, SoftwareIdentification dataServiceSoftwareId, int sourceSoftwareId)
        throws ApolloDatabaseException, Md5UtilsException {

    String userName = authentication.getRequesterId();
    String password = authentication.getRequesterPassword();

    String[] userIdTokens = parseUserId(userName);
    userName = userIdTokens[0];/*from  w w  w .  j  a v  a 2  s  .co  m*/

    int softwareKey = getSoftwareIdentificationKey(dataServiceSoftwareId);
    int userKey = getUserKey(userName, password);

    try (Connection conn = datasource.getConnection()) {
        BigInteger simulationGroupId = getNewSimulationGroupId();

        String query = "INSERT INTO run (md5_hash_of_run_message, software_id, requester_id, last_service_to_be_called, simulation_group_id, md5_collision_id) VALUES (?, ?, ?, ?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, md5Utils.getMd5(message));
        pstmt.setInt(2, softwareKey);
        pstmt.setInt(3, userKey);
        pstmt.setInt(4, 1);
        pstmt.setInt(5, simulationGroupId.intValue());
        pstmt.setInt(6, md5CollisionId);
        pstmt.execute();

        ResultSet rs = pstmt.getGeneratedKeys();
        BigInteger runId;
        if (rs.next()) {
            runId = new BigInteger(rs.getString(1));
        } else {
            throw new ApolloDatabaseRecordNotInsertedException("Record not inserted!");
        }

        // ALSO NEED TO ADD serialized run data service message (JSON) to
        // run_data_content table...
        // use insertDataContentForRun for this
        int dataContentKey = addTextDataContent(jsonUtils.getJSONString(message));
        int runDataDescriptionId = getRunDataDescriptionId(ContentDataFormatEnum.TEXT,
                "data_retrieval_request_message.json", ContentDataTypeEnum.RUN_MESSAGE, sourceSoftwareId,
                getSoftwareIdentificationKey(dataServiceSoftwareId));
        // int runDataId = the following line returns the runDataId, but
        // it's not used at this point.
        associateContentWithRunId(new BigInteger(String.valueOf(runId)), dataContentKey, runDataDescriptionId);

        List<BigInteger> runIdsForDataService = new ArrayList<>();
        runIdsForDataService.add(runId);
        addRunIdsToSimulationGroup(simulationGroupId, runIdsForDataService);

        updateStatusOfRun(runId, MethodCallStatusEnum.LOADED_RUN_CONFIG_INTO_DATABASE,
                "Adding config information to the database for runId: " + runId.toString());

        return runId;
    } catch (SQLException ex) {
        throw new ApolloDatabaseException("SQLException attempting to add simulation run: " + ex.getMessage());
    }
}

From source file:com.sun.honeycomb.adm.client.AdminClientImpl.java

/**
 * @see com.sun.honeycomb.adm.client.AdminClient#powerNodeOff(cell,int,boolean)
 */// w w  w.j  a v a2 s . co  m
public int powerNodeOff(HCCell cell, int nodeId, boolean useIpmi)
        throws MgmtException, ConnectException, PermissionException {
    if (!loggedIn())
        throw new PermissionException();
    //
    // We are inconsistently using node nomenclature
    // sometimes nodeids are 101-116 and sometime they're
    // 0-15.
    //
    if (nodeId < 100)
        nodeId += 101;

    BigInteger result;

    String msg = (useIpmi ? AdminResourcesConstants.MSG_KEY_NODE_POWER_OFF_IPMI
            : AdminResourcesConstants.MSG_KEY_NODE_POWER_OFF);

    Object[] params = { Long.toString(this._sessionId), Integer.toString(nodeId),
            Integer.toString(cell.getCellId()) };
    this.extLog(ExtLevel.EXT_INFO, msg, params, "powerNodeOff");

    if (useIpmi) {
        result = cell.powerNodeOff(new StatusCallback(), BigInteger.valueOf(nodeId), BigInteger.valueOf(0));
    } else {
        result = cell.powerNodeOff(new StatusCallback(), BigInteger.valueOf(nodeId), BigInteger.valueOf(1));
    }
    return result.intValue();
}

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

@Override
public ObjectList getCheckedOutDocs(String repositoryId, String folderId, String filter, String orderBy,
        Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
        BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {
    long start = System.currentTimeMillis();

    checkRepositoryId(repositoryId);/*from   w  w  w  . j  av  a2  s.  co m*/

    // convert BigIntegers to int
    int max = (maxItems == null ? Integer.MAX_VALUE : maxItems.intValue());
    int skip = (skipCount == null || skipCount.intValue() < 0 ? 0 : skipCount.intValue());

    // prepare query
    SearchParameters params = new SearchParameters();
    params.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);

    if (folderId == null) {
        params.setQuery("+=cm:workingCopyOwner:\"" + AuthenticationUtil.getFullyAuthenticatedUser() + "\"");
        params.addStore(connector.getRootStoreRef());
    } else {
        CMISNodeInfo folderInfo = getOrCreateFolderInfo(folderId, "Folder");

        params.setQuery("+=cm:workingCopyOwner:\"" + AuthenticationUtil.getFullyAuthenticatedUser()
                + "\" AND +=PARENT:\"" + folderInfo.getNodeRef().toString() + "\"");
        params.addStore(folderInfo.getNodeRef().getStoreRef());
    }

    // set up order
    if (orderBy != null) {
        String[] parts = orderBy.split(",");
        for (int i = 0; i < parts.length; i++) {
            String[] sort = parts[i].split(" +");

            if (sort.length < 1) {
                continue;
            }

            PropertyDefinitionWrapper propDef = connector.getOpenCMISDictionaryService()
                    .findPropertyByQueryName(sort[0]);
            if (propDef != null) {
                if (propDef.getPropertyDefinition().isOrderable()) {
                    QName sortProp = propDef.getPropertyAccessor().getMappedProperty();
                    if (sortProp != null) {
                        boolean sortAsc = (sort.length == 1) || sort[1].equalsIgnoreCase("asc");
                        params.addSort(propDef.getPropertyLuceneBuilder().getLuceneFieldName(), sortAsc);
                    } else {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Ignore sort property '" + sort[0] + " - mapping not found");
                        }
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Ignore sort property '" + sort[0] + " - not orderable");
                    }
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Ignore sort property '" + sort[0] + " - query name not found");
                }
            }
        }
    }

    // execute query
    ResultSet resultSet = null;
    List<NodeRef> nodeRefs;
    try {
        resultSet = connector.getSearchService().query(params);
        nodeRefs = resultSet.getNodeRefs();
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }

    // collect results
    ObjectListImpl result = new ObjectListImpl();
    List<ObjectData> list = new ArrayList<ObjectData>();
    result.setObjects(list);

    int skipCounter = skip;
    if (max > 0) {
        for (NodeRef nodeRef : nodeRefs) {
            // TODO - perhaps filter by path in the query instead?
            if (connector.filter(nodeRef)) {
                continue;
            }

            if (skipCounter > 0) {
                skipCounter--;
                continue;
            }

            if (list.size() == max) {
                break;
            }

            try {
                // create a CMIS object
                CMISNodeInfo ni = createNodeInfo(nodeRef);
                ObjectData object = connector.createCMISObject(ni, filter, includeAllowableActions,
                        includeRelationships, renditionFilter, false, false);

                boolean isObjectInfoRequired = getContext().isObjectInfoRequired();
                if (isObjectInfoRequired) {
                    getObjectInfo(repositoryId, ni.getObjectId(), includeRelationships);
                }

                // add it
                list.add(object);
            } catch (InvalidNodeRefException e) {
                // ignore invalid objects
            } catch (CmisObjectNotFoundException e) {
                // ignore objects that have not been found (perhaps because their type is unknown to CMIS)
            }
        }
    }

    // has more ?
    result.setHasMoreItems(nodeRefs.size() - skip > list.size());

    logGetObjectsCall("getCheckedOutDocs", start, folderId, list.size(), filter, includeAllowableActions,
            includeRelationships, renditionFilter, null, extension, skipCount, maxItems, orderBy, null);

    return result;
}

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

@Override
public ObjectInFolderList getChildren(String repositoryId, String folderId, String filter, String orderBy,
        Boolean includeAllowableActions, IncludeRelationships includeRelationships, String renditionFilter,
        Boolean includePathSegment, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {
    long start = System.currentTimeMillis();

    checkRepositoryId(repositoryId);/*  w ww .  jav  a  2 s. co  m*/

    // convert BigIntegers to int
    int max = (maxItems == null ? Integer.MAX_VALUE : maxItems.intValue());
    int skip = (skipCount == null || skipCount.intValue() < 0 ? 0 : skipCount.intValue());

    ObjectInFolderListImpl result = new ObjectInFolderListImpl();
    List<ObjectInFolderData> list = new ArrayList<ObjectInFolderData>();
    result.setObjects(list);

    // get the children references
    NodeRef folderNodeRef = getOrCreateFolderInfo(folderId, "Folder").getNodeRef();

    // convert orderBy to sortProps
    List<Pair<QName, Boolean>> sortProps = null;
    if (orderBy != null) {
        sortProps = new ArrayList<Pair<QName, Boolean>>(1);

        String[] parts = orderBy.split(",");
        int len = parts.length;
        final int origLen = len;

        if (origLen > 0) {
            int maxSortProps = GetChildrenCannedQuery.MAX_FILTER_SORT_PROPS;
            if (len > maxSortProps) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Too many sort properties in 'orderBy' - ignore those above max (max="
                            + maxSortProps + ",actual=" + len + ")");
                }
                len = maxSortProps;
            }
            for (int i = 0; i < len; i++) {
                String[] sort = parts[i].split(" +");

                if (sort.length > 0) {
                    // MNT-10529: Leading spaces result in an empty string value after the split operation. Leading spaces may occur in the 'orderBy' statement when the
                    // elements of statement separated by a comma and a space(s)
                    int index = (sort[0].isEmpty()) ? (1) : (0);

                    Pair<QName, Boolean> sortProp = connector.getSortProperty(sort[index],
                            sort.length > (index + 1) ? sort[index + 1] : null);
                    sortProps.add(sortProp);
                }
            }
        }

        if (sortProps.size() < origLen) {
            logger.warn("Sort properties trimmed - either too many and/or not found: \n" + "   orig:  "
                    + orderBy + "\n" + "   final: " + sortProps);
        }
    }

    PagingRequest pageRequest = new PagingRequest(skip, max, null);
    pageRequest.setRequestTotalCountMax(skip + 10000); // TODO make this optional/configurable
                                                       // - affects whether numItems may be returned 
    Set<QName> typeqnames = new HashSet<QName>();
    List<TypeDefinitionWrapper> allTypes = connector.getOpenCMISDictionaryService().getAllTypes();
    for (TypeDefinitionWrapper type : allTypes) {
        typeqnames.add(type.getAlfrescoClass());
    }
    PagingResults<FileInfo> pageOfNodeInfos = connector.getFileFolderService().list(folderNodeRef, typeqnames,
            null, //ignoreAspectQNames, 
            sortProps, pageRequest);

    if (max > 0) {
        for (FileInfo child : pageOfNodeInfos.getPage()) {
            try {
                // TODO this will break the paging if filtering is performed...
                if (connector.filter(child.getNodeRef())) {
                    continue;
                }

                // create a child CMIS object
                CMISNodeInfo ni = createNodeInfo(child.getNodeRef(), child.getType(), child.getProperties(),
                        null, false); // note: checkExists=false (don't need to check again)

                // ignore invalid children
                // Skip non-cmis objects
                if (ni.getObjectVariant() == CMISObjectVariant.INVALID_ID
                        || ni.getObjectVariant() == CMISObjectVariant.NOT_EXISTING
                        || ni.getObjectVariant() == CMISObjectVariant.NOT_A_CMIS_OBJECT
                        || ni.getObjectVariant() == CMISObjectVariant.PERMISSION_DENIED) {
                    continue;
                }

                ObjectData object = connector.createCMISObject(ni, filter, includeAllowableActions,
                        includeRelationships, renditionFilter, false, false/*, getContext().getCmisVersion()*/);

                boolean isObjectInfoRequired = getContext().isObjectInfoRequired();
                if (isObjectInfoRequired) {
                    getObjectInfo(repositoryId, ni.getObjectId(), includeRelationships);
                }

                ObjectInFolderDataImpl childData = new ObjectInFolderDataImpl();
                childData.setObject(object);

                // include path segment
                if (includePathSegment) {
                    childData.setPathSegment(child.getName());
                }

                // add it
                list.add(childData);
            } catch (InvalidNodeRefException e) {
                // ignore invalid children
            } catch (CmisObjectNotFoundException e) {
                // ignore objects that have not been found (perhaps because their type is unknown to CMIS)
            }
        }
    }

    // has more ?
    result.setHasMoreItems(pageOfNodeInfos.hasMoreItems());

    // total count ?
    Pair<Integer, Integer> totalCounts = pageOfNodeInfos.getTotalResultCount();
    if (totalCounts != null) {
        Integer totalCountLower = totalCounts.getFirst();
        Integer totalCountUpper = totalCounts.getSecond();
        if ((totalCountLower != null) && (totalCountLower.equals(totalCountUpper))) {
            result.setNumItems(BigInteger.valueOf(totalCountLower));
        }
    }

    logGetObjectsCall("getChildren", start, folderId, list.size(), filter, includeAllowableActions,
            includeRelationships, renditionFilter, includePathSegment, extension, skipCount, maxItems, orderBy,
            null);

    return result;
}

From source file:org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService.java

@Override
public ObjectList getContentChanges(String repositoryId, Holder<String> changeLogTokenHolder,
        Boolean includeProperties, String filter, Boolean includePolicyIds, Boolean includeAcl,
        BigInteger maxItems, ExtensionsData extension) {
    if (changeLogTokenHolder == null) {
        throw new CmisInvalidArgumentException("Missing change log token holder");
    }/*from   w ww  . j av a  2 s.c om*/
    String changeLogToken = changeLogTokenHolder.getValue();
    long minDate;
    if (changeLogToken == null) {
        minDate = 0;
    } else {
        try {
            minDate = Long.parseLong(changeLogToken);
        } catch (NumberFormatException e) {
            throw new CmisInvalidArgumentException("Invalid change log token");
        }
    }
    try {
        AuditReader reader = Framework.getService(AuditReader.class);
        if (reader == null) {
            throw new CmisRuntimeException("Cannot find audit service");
        }
        int max = maxItems == null ? -1 : maxItems.intValue();
        if (max <= 0) {
            max = DEFAULT_CHANGE_LOG_SIZE;
        }
        if (max > MAX_CHANGE_LOG_SIZE) {
            max = MAX_CHANGE_LOG_SIZE;
        }
        List<ObjectData> ods = null;
        // retry with increasingly larger page size if some items are
        // skipped
        for (int scale = 1; scale < 128; scale *= 2) {
            int pageSize = max * scale + 1;
            if (pageSize < 0) { // overflow
                pageSize = Integer.MAX_VALUE;
            }
            ods = readAuditLog(repositoryId, minDate, max, pageSize);
            if (ods != null) {
                break;
            }
            if (pageSize == Integer.MAX_VALUE) {
                break;
            }
        }
        if (ods == null) {
            // couldn't find enough, too many items were skipped
            ods = Collections.emptyList();

        }
        boolean hasMoreItems = ods.size() > max;
        if (hasMoreItems) {
            ods = ods.subList(0, max);
        }
        String latestChangeLogToken;
        if (ods.size() == 0) {
            latestChangeLogToken = null;
        } else {
            ObjectData last = ods.get(ods.size() - 1);
            latestChangeLogToken = String.valueOf(last.getChangeEventInfo().getChangeTime().getTimeInMillis());
        }
        ObjectListImpl ol = new ObjectListImpl();
        ol.setHasMoreItems(Boolean.valueOf(hasMoreItems));
        ol.setObjects(ods);
        ol.setNumItems(BigInteger.valueOf(-1));
        changeLogTokenHolder.setValue(latestChangeLogToken);
        return ol;
    } catch (Exception e) {
        throw new CmisRuntimeException(e.toString(), e);
    }
}

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public Map<String, ByteArrayOutputStream> getDataContentForSoftware(BigInteger runKey)
        throws ApolloDatabaseException {
    Map<String, ByteArrayOutputStream> result = new HashMap<>();

    String query = "SELECT " + "rddv.label, " + "rdc.text_content " + "FROM " + "run_data_content rdc, "
            + "run_data rd, " + "run_data_description_view rddv " + "WHERE " + "rd.content_id = rdc.id AND "
            + "rd.run_id = ? AND " + "rddv.run_data_description_id = rd.description_id";

    PreparedStatement pstmt = null;
    try {/*from  ww w .  j a va  2  s  .  com*/
        try (Connection conn = datasource.getConnection()) {
            pstmt = conn.prepareStatement(query);
            pstmt.setInt(1, runKey.intValue());
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String label = rs.getString(1);
                String dataContent = rs.getString(2);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                baos.write(dataContent.getBytes());
                result.put(label, baos);
            }
        } finally {
            pstmt.close();
        }

    } catch (IOException ex) {
        throw new ApolloDatabaseException("IOException attempting to get data content for software for run ID "
                + runKey + ": " + ex.getMessage());
    } catch (SQLException ex) {
        throw new ApolloDatabaseException("SQLException attempting to get data content for software for run ID "
                + runKey + ": " + ex.getMessage());
    }

    return result;
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

private int getLatestCRLNumber(final String caName, final boolean delta)
        throws CADoesntExistsException_Exception, EjbcaException_Exception, CRLException {
    final byte[] crlBytes = ejbcaraws.getLatestCRL(caName, delta);
    final X509CRL crl = CertTools.getCRLfromByteArray(crlBytes);
    final BigInteger crlNumber = CrlExtensions.getCrlNumber(crl);
    log.info("getLatestCRLNumber for " + caName + " delta=" + delta + " crlNumber=" + crlNumber.intValue());
    return crlNumber.intValue();
}

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

@Override
public List<ObjectInFolderContainer> getDescendants(String repositoryId, String folderId, BigInteger depth,
        String filter, Boolean includeAllowableActions, IncludeRelationships includeRelationships,
        String renditionFilter, Boolean includePathSegment, ExtensionsData extension) {
    long start = System.currentTimeMillis();

    checkRepositoryId(repositoryId);/*from  w  w w  . j a v  a 2s  .  c  om*/

    List<ObjectInFolderContainer> result = new ArrayList<ObjectInFolderContainer>();

    getDescendantsTree(repositoryId, getOrCreateFolderInfo(folderId, "Folder").getNodeRef(), depth.intValue(),
            filter, includeAllowableActions, includeRelationships, renditionFilter, includePathSegment, false,
            result);

    logGetObjectsCall("getDescendants", start, folderId, countDescendantsTree(result), filter,
            includeAllowableActions, includeRelationships, renditionFilter, includePathSegment, extension, null,
            null, null, depth);

    return result;
}