Example usage for java.math BigInteger ONE

List of usage examples for java.math BigInteger ONE

Introduction

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

Prototype

BigInteger ONE

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

Click Source Link

Document

The BigInteger constant one.

Usage

From source file:org.mule.module.extension.internal.capability.xml.schema.SchemaBuilder.java

private void generateNestedProcessorElement(ExplicitGroup all, Parameter parameter, String maxOccurs) {
    LocalComplexType collectionComplexType = new LocalComplexType();
    GroupRef group = generateNestedProcessorGroup(parameter, maxOccurs);
    collectionComplexType.setGroup(group);
    collectionComplexType.setAnnotation(createDocAnnotation(parameter.getDescription()));

    TopLevelElement collectionElement = new TopLevelElement();
    collectionElement.setName(hyphenize(parameter.getName()));
    collectionElement.setMinOccurs(parameter.isRequired() ? BigInteger.ONE : BigInteger.ZERO);
    collectionElement.setComplexType(collectionComplexType);
    collectionElement.setAnnotation(createDocAnnotation(EMPTY));
    all.getParticle().add(objectFactory.createElement(collectionElement));
}

From source file:CentralLimitTheorem.CLT.java

static BigInteger factorial(int n) {
    BigInteger res = BigInteger.ONE;

    for (int i = n; i > 1; i--) {
        res = res.multiply(BigInteger.valueOf(i));
    }/*  w ww .j  a  v  a2 s. c om*/
    return (res);
}

From source file:org.matheclipse.commons.parser.client.eval.bigfraction.BigFractionEvaluator.java

/**
 * Evaluate an already parsed in abstract syntax tree node into a
 * <code>BigFraction</code> number value.
 * //from   w ww .  j  ava 2 s.co m
 * @param node
 *            abstract syntax tree node
 * 
 * @return the evaluated BigFraction number
 * 
 * @throws ArithmeticMathException
 *             if the <code>node</code> cannot be evaluated.
 */
@Override
public BigFraction evaluateNode(final ASTNode node) {
    if (node instanceof BigFractionNode) {
        return ((BigFractionNode) node).getValue();
    }
    if (node instanceof FunctionNode) {
        return evaluateFunction((FunctionNode) node);
    }
    if (node instanceof SymbolNode) {
        FieldElementVariable<BigFraction> v = fVariableMap.get(node.toString());
        if (v != null) {
            return v.getValue();
        }
        BigFraction dbl = SYMBOL_MAP.get(node.toString());
        if (dbl != null) {
            return dbl;
        }
    } else if (node instanceof NumberNode) {
        if (node instanceof FractionNode) {
            return new BigFraction(new BigInteger(((FractionNode) node).getNumerator().getString()),
                    new BigInteger(((FractionNode) node).getDenominator().getString()));
        } else if (node instanceof IntegerNode) {
            String iStr = ((NumberNode) node).getString();
            if (iStr != null) {
                return new BigFraction(new BigInteger(iStr), BigInteger.ONE);
            } else {
                return new BigFraction(((IntegerNode) node).getIntValue(), 1);
            }
        }

        return new BigFraction(((NumberNode) node).doubleValue());
    }

    throw new ArithmeticMathException(
            "BigFractionEvaluator#evaluateNode(ASTNode) not possible for: " + node.toString());
}

From source file:org.mule.module.extension.internal.capability.xml.schema.SchemaBuilder.java

private GroupRef generateNestedProcessorGroup(Parameter parameter, String maxOccurs) {
    QName ref = MULE_MESSAGE_PROCESSOR_OR_OUTBOUND_ENDPOINT_TYPE;
    TypeRestrictionCapability restrictionCapability = getSingleCapability(parameter,
            TypeRestrictionCapability.class);
    if (restrictionCapability != null) {
        ref = getSubstitutionGroup(restrictionCapability.getType());
        ref = new QName(ref.getNamespaceURI(), getGroupName(ref.getLocalPart()), ref.getPrefix());
    }/*from w  ww  .  ja v  a2  s  .com*/

    GroupRef group = new GroupRef();
    group.setRef(ref);
    group.setMinOccurs(parameter.isRequired() ? BigInteger.ONE : BigInteger.ZERO);
    group.setMaxOccurs(maxOccurs);

    return group;
}

From source file:org.apache.juddi.samples.JuddiAdminService.java

void autoMagicDirected() throws Exception {

    //1 > 2 >3 >1
    List<Node> uddiNodeList = clerkManager.getClientConfig().getUDDINodeList();

    Transport transport = clerkManager.getTransport("default");
    String authtoken = transport.getUDDISecurityService().getAuthToken(new GetAuthToken("root", "root"))
            .getAuthInfo();/*from   w  w  w  .  java2  s.co m*/

    JUDDIApiPortType juddiApiService = transport.getJUDDIApiService();
    System.out.println("fetching...");

    ReplicationConfiguration replicationNodes = null;
    try {
        replicationNodes = juddiApiService.getReplicationNodes(authtoken);
    } catch (Exception ex) {
        System.out.println("Error getting replication config");
        ex.printStackTrace();
        replicationNodes = new ReplicationConfiguration();

    }
    if (replicationNodes.getCommunicationGraph() == null) {
        replicationNodes.setCommunicationGraph(new CommunicationGraph());
    }
    Operator op = new Operator();
    op.setOperatorNodeID("uddi:juddi.apache.org:node1");
    op.setSoapReplicationURL(clerkManager.getClientConfig().getUDDINode("default").getReplicationUrl());
    op.setOperatorStatus(OperatorStatusType.NORMAL);
    op.getContact().add(new Contact());
    op.getContact().get(0).getPersonName().add(new PersonName("bob", "en"));
    op.getContact().get(0).setUseType("admin");
    replicationNodes.getOperator().clear();
    replicationNodes.getOperator().add(op);

    op = new Operator();
    op.setOperatorNodeID("uddi:another.juddi.apache.org:node2");
    op.setSoapReplicationURL(clerkManager.getClientConfig().getUDDINode("uddi:another.juddi.apache.org:node2")
            .getReplicationUrl());
    op.setOperatorStatus(OperatorStatusType.NORMAL);
    op.getContact().add(new Contact());
    op.getContact().get(0).getPersonName().add(new PersonName("mary", "en"));
    op.getContact().get(0).setUseType("admin");
    replicationNodes.getOperator().add(op);
    op = new Operator();

    op.setOperatorNodeID("uddi:yet.another.juddi.apache.org:node3");
    op.setSoapReplicationURL(clerkManager.getClientConfig()
            .getUDDINode("uddi:yet.another.juddi.apache.org:node3").getReplicationUrl());
    op.setOperatorStatus(OperatorStatusType.NORMAL);
    op.getContact().add(new Contact());
    op.getContact().get(0).getPersonName().add(new PersonName("mary", "en"));
    op.getContact().get(0).setUseType("admin");
    replicationNodes.getOperator().add(op);
    replicationNodes.getCommunicationGraph().getNode().clear();
    replicationNodes.getCommunicationGraph().getNode().add("uddi:another.juddi.apache.org:node2");
    replicationNodes.getCommunicationGraph().getNode().add("uddi:juddi.apache.org:node1");
    replicationNodes.getCommunicationGraph().getNode().add("uddi:yet.another.juddi.apache.org:node3");
    replicationNodes.getCommunicationGraph().getEdge().clear();
    Edge e = new CommunicationGraph.Edge();
    e.setMessageSender("uddi:juddi.apache.org:node1");
    e.setMessageReceiver("uddi:another.juddi.apache.org:node2");
    replicationNodes.getCommunicationGraph().getEdge().add(e);

    e = new CommunicationGraph.Edge();
    e.setMessageSender("uddi:another.juddi.apache.org:node2");
    e.setMessageReceiver("uddi:yet.another.juddi.apache.org:node3");
    replicationNodes.getCommunicationGraph().getEdge().add(e);

    e = new CommunicationGraph.Edge();
    e.setMessageSender("uddi:yet.another.juddi.apache.org:node3");
    e.setMessageReceiver("uddi:juddi.apache.org:node1");
    replicationNodes.getCommunicationGraph().getEdge().add(e);

    replicationNodes.setSerialNumber(0L);
    replicationNodes.setTimeOfConfigurationUpdate("");
    replicationNodes.setMaximumTimeToGetChanges(BigInteger.ONE);
    replicationNodes.setMaximumTimeToSyncRegistry(BigInteger.ONE);

    if (replicationNodes.getRegistryContact().getContact() == null) {
        replicationNodes.getRegistryContact().setContact(new Contact());
        replicationNodes.getRegistryContact().getContact().getPersonName().add(new PersonName("unknown", null));
    }

    JAXB.marshal(replicationNodes, System.out);

    juddiApiService.setReplicationNodes(authtoken, replicationNodes);
    System.out.println("Saved to node1");
    TestEquals(replicationNodes, juddiApiService.getReplicationNodes(authtoken));

    transport = clerkManager.getTransport("uddi:another.juddi.apache.org:node2");
    authtoken = transport.getUDDISecurityService().getAuthToken(new GetAuthToken("root", "root")).getAuthInfo();
    juddiApiService = transport.getJUDDIApiService();
    juddiApiService.setReplicationNodes(authtoken, replicationNodes);
    System.out.println("Saved to node2");
    TestEquals(replicationNodes, juddiApiService.getReplicationNodes(authtoken));

    transport = clerkManager.getTransport("uddi:yet.another.juddi.apache.org:node3");
    authtoken = transport.getUDDISecurityService().getAuthToken(new GetAuthToken("root", "root")).getAuthInfo();
    juddiApiService = transport.getJUDDIApiService();
    juddiApiService.setReplicationNodes(authtoken, replicationNodes);
    System.out.println("Saved to node3");
    TestEquals(replicationNodes, juddiApiService.getReplicationNodes(authtoken));

}

From source file:net.pms.util.Rational.java

/**
 * Returns a {@link Rational} whose value is {@code (this + value)}.
 *
 * @param value the value to be added to this {@link Rational}.
 * @return The addition result./*from ww  w  . ja  va 2s . c  o  m*/
 */
@Nullable
public Rational add(@Nullable BigInteger value) {
    if (value == null) {
        return null;
    }

    if (isNaN()) {
        return NaN;
    }
    if (isInfinite() || value.signum() == 0) {
        return this;
    }

    if (BigInteger.ONE.equals(denominator)) {
        return valueOf(numerator.add(value), denominator);
    }
    return valueOf(numerator.add(value.multiply(denominator)), denominator);
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

/**
 * Helper function to create a new node.
 *
 * @param con             an open and valid connection
 * @param seq             reference to a sequencer
 * @param ce              reference to the content engine
 * @param mode            Live or Edit mode
 * @param parentNodeId    the parent node (1=root)
 * @param name            the name of the new node (only informative value)
 * @param label           label for Caption property (only used if new reference is created)
 * @param position        the position within the childs (0 based, Integer.MAX_VALUE may be used to
 *                        append to the end)
 * @param reference       a reference to an existing content (must exist!)
 * @param data            the optional data
 * @param nodeId          the id to use or create a new one if < 0
 * @param activateContent change the step of contents that have no live step to live in the max version?
 * @return the used or created node id/*  w  ww.j av a2  s . c o  m*/
 * @throws FxTreeException if the function fails
 */
private long _createNode(Connection con, SequencerEngine seq, ContentEngine ce, FxTreeMode mode,
        long parentNodeId, String name, FxString label, int position, FxPK reference, String data, long nodeId,
        boolean activateContent) throws FxApplicationException {

    // acquire exclusive lock for parent node
    acquireLocksForUpdate(con, mode, Arrays.asList(parentNodeId));

    //        makeSpace(con, seq/*irrelevant*/, mode, parentNodeId, position/*irrelevant*/, 1);
    FxTreeNodeInfoSpreaded parentNode = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, parentNodeId);
    BigInteger boundaries[] = getBoundaries(con, parentNode, position);
    BigInteger leftBoundary = boundaries[0]; //== left border
    BigInteger rightBoundary = boundaries[1]; //== right border

    // Node has to be inserted between the left and right boundary and needs 2 slots for its left and right border
    BigInteger spacing = rightBoundary.subtract(leftBoundary).subtract(TWO);
    // Compute spacing for left,inner and right part
    spacing = spacing.divide(THREE);

    // We need at least 2 open slots (for the left and right boundary of the new node)
    //if the spacing is <= 0 we need more space
    if (spacing.compareTo(BigInteger.ZERO) <= 0/*less than*/) {
        throw new FxTreeException("ex.tree.create.noSpace", parentNodeId);
    }

    // try to use space more efficiently for flat structures, otherwise the first node of a folder
    // will get a third of the subtree space, the second one ninth, and so on.
    // Maxspacing indicates the number of nodes (*2) we expect to put in this node before space reorg
    spacing = spacing.compareTo(DEFAULT_NODE_SPACING) > 0 ? DEFAULT_NODE_SPACING : spacing;

    //        final BigInteger left = leftBoundary.add(spacing).add(BigInteger.ONE);
    // don't add gap to left boundary (doesn't seem to have any benefits since that space is lost
    // unless the tree is reorganized anyway
    final BigInteger left = leftBoundary.add(BigInteger.ONE);
    final BigInteger right = left.add(spacing).add(BigInteger.ONE);

    NodeCreateInfo nci = getNodeCreateInfo(mode, seq, ce, nodeId, name, label, reference, activateContent);

    // Create the node
    PreparedStatement ps = null;
    try {
        ps = con.prepareStatement("INSERT INTO " + getTable(mode) + " (ID,PARENT,DEPTH,DIRTY,REF,LFT,RGT,"
                + "CHILDCOUNT,NAME,MODIFIED_AT,TEMPLATE) VALUES " + "(" + nci.id + "," + parentNodeId + ","
                + (parentNode.getDepth() + 1) + ",?," + nci.reference.getId() + ",?,?,0,?,"
                + StorageManager.getTimestampFunction() + ",?)");
        ps.setBoolean(1, mode != FxTreeMode.Live);
        setNodeBounds(ps, 2, left);
        setNodeBounds(ps, 3, right);
        ps.setString(4, FxFormatUtils.escapeTreePath(nci.name));
        if (StringUtils.isEmpty(data)) {
            ps.setNull(5, java.sql.Types.VARCHAR);
        } else {
            ps.setString(6, data);
        }
        ps.executeUpdate();
        ps.close();

        //update the parents childcount
        ps = con.prepareStatement(
                "UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT+1 WHERE ID=" + parentNodeId);
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new FxTreeException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (Throwable t) {
            /*ignore*/
        }
    }
    return nci.id;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private WorkDocument convertToSAFTWorkDocument(Invoice document,
        Map<String, oecd.standardauditfile_tax.pt_1.Customer> baseCustomers,
        Map<String, oecd.standardauditfile_tax.pt_1.Product> baseProducts) {
    WorkDocument workDocument = new WorkDocument();

    // Find the Customer in BaseCustomers
    oecd.standardauditfile_tax.pt_1.Customer customer = null;

    if (baseCustomers.containsKey(document.getDebtAccount().getCustomer().getCode())) {
        customer = baseCustomers.get(document.getDebtAccount().getCustomer().getCode());
    } else {//from   w w w. j a v a 2s  .c om
        // If not found, create a new one and add it to baseCustomers
        customer = convertCustomerToSAFTCustomer(document.getDebtAccount().getCustomer());
        baseCustomers.put(customer.getCustomerID(), customer);
    }

    //check the PayorDebtAccount
    if (document.getPayorDebtAccount() != null) {
        if (baseCustomers.containsKey(document.getPayorDebtAccount().getCustomer().getCode())) {
            //do nothing
        } else {
            // If not found, create a new one and add it to baseCustomers
            oecd.standardauditfile_tax.pt_1.Customer payorCustomer = convertCustomerToSAFTCustomer(
                    document.getPayorDebtAccount().getCustomer());
            baseCustomers.put(payorCustomer.getCustomerID(), payorCustomer);
        }
    }

    // MovementDate
    DatatypeFactory dataTypeFactory;
    try {
        dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = document.getDocumentDate();

        // SystemEntryDate
        workDocument.setSystemEntryDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        workDocument.setWorkDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        // DocumentNumber
        workDocument.setDocumentNumber(document.getUiDocumentNumber());

        // CustomerID
        workDocument.setCustomerID(document.getDebtAccount().getCustomer().getCode());

        //PayorID
        if (document.getPayorDebtAccount() != null) {
            workDocument.setPayorCustomerID(document.getPayorDebtAccount().getCustomer().getCode());
        }

        // DocumentStatus
        /*
         * Deve ser preenchido com: ?N? ? Normal; Texto 1 ?T? ? Por conta de
         * terceiros; ?A? ? Documento anulado.
         */
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus status = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus();
        if (document.isAnnulled()) {
            status.setWorkStatus("A");
        } else {
            status.setWorkStatus("N");
        }

        status.setWorkStatusDate(workDocument.getSystemEntryDate());
        // status.setReason("");
        // Utilizador responsvel pelo estado atual do docu-mento.
        status.setSourceID(document.getVersioningUpdatedBy());
        // Deve ser preenchido com:
        // 'P' - Documento produzido na aplicacao;
        if (Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getExternSeries())) {
            status.setSourceBilling(SAFTPTSourceBilling.I);
        } else {
            status.setSourceBilling(SAFTPTSourceBilling.P);
        }

        workDocument.setDocumentStatus(status);

        // DocumentTotals
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals docTotals = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals();
        docTotals.setGrossTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setNetTotal(document.getTotalNetAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setTaxPayable(document.getTotalAmount().subtract(document.getTotalNetAmount()).setScale(2,
                RoundingMode.HALF_EVEN));
        workDocument.setDocumentTotals(docTotals);

        // WorkType
        /*
         * Deve ser preenchido com: Texto 2 "DC"  Documentos emitidos que
         * sejam suscetiveis de apresentacao ao cliente para conferencia de
         * entrega de mercadorias ou da prestacao de servicos. "FC"  Fatura
         * de consignacao nos termos do artigo 38 do codigo do IVA.
         */
        workDocument.setWorkType("DC");

        // Period
        /*
         * Per?odo contabil?stico (Period) . . . . . . . . . . Deve ser
         * indicado o n?mero do m?s do per?odo de tributa??o, de ?1? a ?12?,
         * contado desde a data do in?cio. Pode ainda ser preenchido com
         * ?13?, ?14?, ?15? ou ?16? para movimentos efectuados no ?ltimo m?s
         * do per?odo de tributa??o, relacionados com o apuramento do
         * resultado. Ex.: movimentos de apuramentos de invent?rios,
         * deprecia??es, ajustamentos ou apuramentos de resultados.
         */
        workDocument.setPeriod(document.getDocumentDate().getMonthOfYear());

        // SourceID
        /*
         * C?digo do utilizador que registou o movimento (SourceID).
         */
        workDocument.setSourceID(document.getVersioningCreator());

    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    List<oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line> productLines = workDocument
            .getLine();

    // Process individual
    BigInteger i = BigInteger.ONE;
    for (FinantialDocumentEntry docLine : document.getFinantialDocumentEntriesSet()) {
        InvoiceEntry orderNoteLine = (InvoiceEntry) docLine;
        oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line line = convertToSAFTWorkDocumentLine(
                orderNoteLine, baseProducts);

        // LineNumber
        line.setLineNumber(i);

        // Add to productLines
        i = i.add(BigInteger.ONE);
        productLines.add(line);
    }

    return workDocument;
}

From source file:org.signserver.server.log.SystemLoggingTest.java

/**
 * Tests that importing a certificate chain to a token is audit logged
 * including the complete chain./*from ww w . j a v  a2 s.  c om*/
 * @throws Exception 
 */
@Test
public void test01LogCertChainInstalledToToken() throws Exception {
    LOG.info(">test01LogCertChainInstalledToToken");

    final String tokenName = "TestCryptoTokenP12_001";
    final String alias = "testkeyalias10";

    try {
        setupCryptoToken(WORKERID_CRYPTOWORKER1, tokenName, "foo123");
        workerSession.generateSignerKey(WORKERID_CRYPTOWORKER1, "RSA", "512", alias, null);

        PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=testkeyalias10,C=SE", null);
        ICertReqData req = workerSession.getCertificateRequest(WORKERID_CRYPTOWORKER1, certReqInfo, false);
        Base64SignerCertReqData reqData = (Base64SignerCertReqData) req;
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                Base64.decode(reqData.getBase64CertReq()));

        int linesBefore = readEntriesCount(auditLogFile);

        // Test with uploadSignerCertificateChain method (global scope)
        KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
        final X509Certificate issuerCert = new JcaX509CertificateConverter().getCertificate(
                new CertBuilder().setSelfSignKeyPair(issuerKeyPair).setSubject("CN=Issuer, C=SE").build());
        final X509Certificate cert = new JcaX509CertificateConverter()
                .getCertificate(new X509v3CertificateBuilder(new X500Name("CN=Issuer, C=SE"), BigInteger.ONE,
                        new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)),
                        csr.getSubject(), csr.getSubjectPublicKeyInfo())
                                .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                                        .build(issuerKeyPair.getPrivate())));

        workerSession.importCertificateChain(WORKERID_CRYPTOWORKER1,
                Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), alias, null);

        List<String> lines = readEntries(auditLogFile, linesBefore, 2);
        LOG.info(lines);

        String line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
        assertNotNull("Contains event", line);
        assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT"));
        assertTrue("Contains worker id", line.contains("WORKER_ID: " + WORKERID_CRYPTOWORKER1));
        assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName));
        assertTrue("Contains key alias", line.contains("KEYALIAS: " + alias));
        assertTrue("Contains certificate",
                line.contains(new String(org.cesecore.util.CertTools
                        .getPemFromCertificateChain(Arrays.<Certificate>asList(cert, issuerCert)))
                                .replace("\r\n", "\n")));
    } finally {
        removeWorker(WORKERID_CRYPTOWORKER1);
        if (keystoreFile != null) {
            FileUtils.deleteQuietly(keystoreFile);
        }
    }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.jdbc.JdbcCrawler.java

/**
 * Populates the {@link #_groupingRanges}-{@link ArrayList} according to the configuration specified in the
 * {@link Grouping}-attribute of the {@link DataSourceConnectionConfig}. The SQL-statements needed for this are
 * executed via a local {@link Statement}-object, just as the data is retrieved via a local {@link ResultSet}-object.
 * //  w  w  w  .ja  v a  2s.  c o  m
 * @throws CrawlerCriticalException
 *           If any of the following conditions occur:
 *           <ul>
 *           <li>Any of the columns used for grouping has a data type which is not supported: !(Number||String)</li>
 *           <li>A SQLException is raised while retrieving the grouping data from the database</li>
 *           </ul>
 */
private void prepareGrouping() throws CrawlerCriticalException {
    final Grouping grouping = _process.getSelections().getGrouping();
    BigInteger stepping = BigInteger.ONE;
    ResultSet groupingResultSet = null;
    ResultSetMetaData groupingMetaData = null;
    if (grouping != null) {
        _groupingRanges = new ArrayList<GroupingRange>();
        final String groupingSQL = grouping.getSQL();
        stepping = grouping.getStepping();
        Statement groupingStatement = null;
        try {
            groupingStatement = _connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            _log.debug("Executing SQL for grouping preparation: [" + groupingSQL + "]");
            groupingResultSet = groupingStatement.executeQuery(groupingSQL);
            groupingMetaData = groupingResultSet.getMetaData();
            _log.debug("Retrieved groupingResultSet with [" + groupingMetaData.getColumnCount() + "] columns");
            for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {
                Class<?> columnClass = null;
                try {
                    columnClass = Class.forName(groupingMetaData.getColumnClassName(i));

                } catch (final ClassNotFoundException e) {
                    _log.error("This should never happen: the class[" + groupingMetaData.getColumnClassName(i)
                            + "] for the column " + i + " in the grouping result set could not be resolved");
                }
                if (Number.class.isAssignableFrom(columnClass)) {
                    _log.debug("RowNr " + i + " of the grouping result set is of type [" + columnClass.getName()
                            + "], which is derived from [Number]: fine for use in a grouping");
                    continue;
                } else if (String.class.equals(columnClass)) {
                    _log.debug("RowNr " + i
                            + " of the grouping result set is of type [String]: fine for use in a grouping");
                } else {
                    throw new CrawlerCriticalException("RowNr " + i + " of the grouping result set is of type ["
                            + columnClass.getName() + "]: NOT supported as a grouping field");
                }
            }
            int groupingRecords = 0;
            PreparedStatementTypedParameter[] startValues = null;
            PreparedStatementTypedParameter[] endValues = null;
            final PreparedStatementTypedParameter[] finalValues = new PreparedStatementTypedParameter[groupingMetaData
                    .getColumnCount()];

            while (groupingResultSet.next()) {

                if (groupingRecords == 0) {

                    startValues = new PreparedStatementTypedParameter[groupingMetaData.getColumnCount()];
                    for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {

                        startValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i),
                                (i * 2) - 1, groupingMetaData.getColumnType(i));
                    }

                }
                groupingRecords++;

                if (groupingRecords == stepping.intValue()) {
                    endValues = new PreparedStatementTypedParameter[groupingMetaData.getColumnCount()];
                    for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {
                        endValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i),
                                i * 2, groupingMetaData.getColumnType(i));
                    }
                    final GroupingRange groupingRange = new GroupingRange(startValues, endValues);
                    _groupingRanges.add(groupingRange);
                    if (_log.isTraceEnabled()) {
                        _log.trace(
                                "Added GroupingRange: [" + groupingRange.toString() + "] to _groupingRanges");
                    }
                    groupingRecords = 0;
                    continue;
                }

                for (int i = 1; i <= groupingMetaData.getColumnCount(); i++) {
                    finalValues[i - 1] = new PreparedStatementTypedParameter(groupingResultSet.getObject(i),
                            i * 2, groupingMetaData.getColumnType(i));

                }

            }
            if (groupingRecords != 0 && stepping.intValue() != 1) {
                final GroupingRange finalgroupingRange = new GroupingRange(startValues, finalValues);
                _groupingRanges.add(finalgroupingRange);
                _log.debug(
                        "Added final GroupingRange [" + finalgroupingRange.toString() + "] to _groupingRanges");
            }
        } catch (final SQLException e1) {
            throw new CrawlerCriticalException("Encountered SQLException while preparing Groupings");
        } finally {
            try {
                if (groupingStatement != null) {
                    groupingStatement.close();
                }
            } catch (final SQLException e) {
                _log.error("Could not closeGrouping statement");
            }
            try {
                groupingResultSet.close();
                _log.debug("Closed Grouping Resultset");
            } catch (final SQLException e) {
                _log.error("Could not close Resultset for Grouping statement");
            }
        }

    }
    // set current grouping to first grouping in list (if list is not empty)
    _groupingRangesIterator = _groupingRanges.iterator();
    if (_groupingRangesIterator.hasNext()) {
        _currentGroupingRange = _groupingRangesIterator.next();
    }

    _log.debug(String.format("Prepared %d grouping ranges based on specified stepping of %d",
            _groupingRanges.size(), stepping.intValue()));
}