Example usage for java.sql Types NUMERIC

List of usage examples for java.sql Types NUMERIC

Introduction

In this page you can find the example usage for java.sql Types NUMERIC.

Prototype

int NUMERIC

To view the source code for java.sql Types NUMERIC.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type NUMERIC.

Usage

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccMySql.CFAccMySqlAccountEntryTable.java

public void updateAccountEntry(CFAccAuthorization Authorization, CFAccAccountEntryBuff Buff) {
    final String S_ProcName = "updateAccountEntry";
    ResultSet resultSet = null;//from   ww w . j  av a2  s  . c o m
    try {
        long TenantId = Buff.getRequiredTenantId();
        long AccountId = Buff.getRequiredAccountId();
        UUID EntryId = Buff.getRequiredEntryId();
        UUID SplitEntryId = Buff.getOptionalSplitEntryId();
        Calendar EntryStamp = Buff.getRequiredEntryStamp();
        String Description = Buff.getRequiredDescription();
        Long TransferTenantId = Buff.getOptionalTransferTenantId();
        Long TransferAccountId = Buff.getOptionalTransferAccountId();
        Short DebitCurrencyId = Buff.getOptionalDebitCurrencyId();
        BigDecimal Debit = Buff.getOptionalDebit();
        Short CreditCurrencyId = Buff.getOptionalCreditCurrencyId();
        BigDecimal Credit = Buff.getOptionalCredit();
        short ConvertedCurrencyId = Buff.getRequiredConvertedCurrencyId();
        BigDecimal ConvertedAmount = Buff.getRequiredConvertedAmount();
        short BalanceCurrencyId = Buff.getRequiredBalanceCurrencyId();
        BigDecimal Balance = Buff.getRequiredBalance();
        int Revision = Buff.getRequiredRevision();
        Connection cnx = schema.getCnx();
        String sql = "call " + schema.getLowerSchemaDbName() + ".sp_update_ac_entry( ?, ?, ?, ?, ?, ?" + ", "
                + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "timestamp( ? )" + ", " + "?" + ", " + "?"
                + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?"
                + ", " + "?" + ", " + "?" + ", " + "?" + " )";
        if (stmtUpdateByPKey == null) {
            stmtUpdateByPKey = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
        stmtUpdateByPKey.setString(argIdx++, "ACNY");
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setLong(argIdx++, AccountId);
        stmtUpdateByPKey.setString(argIdx++, EntryId.toString());
        if (SplitEntryId != null) {
            stmtUpdateByPKey.setString(argIdx++, SplitEntryId.toString());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.VARCHAR);
        }
        stmtUpdateByPKey.setString(argIdx++, CFAccMySqlSchema.getTimestampString(EntryStamp));
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (TransferTenantId != null) {
            stmtUpdateByPKey.setLong(argIdx++, TransferTenantId.longValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.BIGINT);
        }
        if (TransferAccountId != null) {
            stmtUpdateByPKey.setLong(argIdx++, TransferAccountId.longValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.BIGINT);
        }
        if (DebitCurrencyId != null) {
            stmtUpdateByPKey.setShort(argIdx++, DebitCurrencyId.shortValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.SMALLINT);
        }
        if (Debit != null) {
            stmtUpdateByPKey.setBigDecimal(argIdx++, Debit);
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.NUMERIC);
        }
        if (CreditCurrencyId != null) {
            stmtUpdateByPKey.setShort(argIdx++, CreditCurrencyId.shortValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.SMALLINT);
        }
        if (Credit != null) {
            stmtUpdateByPKey.setBigDecimal(argIdx++, Credit);
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.NUMERIC);
        }
        stmtUpdateByPKey.setShort(argIdx++, ConvertedCurrencyId);
        stmtUpdateByPKey.setBigDecimal(argIdx++, ConvertedAmount);
        stmtUpdateByPKey.setShort(argIdx++, BalanceCurrencyId);
        stmtUpdateByPKey.setBigDecimal(argIdx++, Balance);
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        try {
            resultSet = stmtUpdateByPKey.executeQuery();
        } catch (SQLException e) {
            if (e.getErrorCode() != 1329) {
                throw e;
            }
            resultSet = null;
        }
        if ((resultSet != null) && resultSet.next()) {
            CFAccAccountEntryBuff updatedBuff = unpackAccountEntryResultSetToBuff(resultSet);
            if ((resultSet != null) && resultSet.next()) {
                resultSet.last();
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Did not expect multi-record response, " + resultSet.getRow() + " rows selected");
            }
            Buff.setOptionalSplitEntryId(updatedBuff.getOptionalSplitEntryId());
            Buff.setRequiredEntryStamp(updatedBuff.getRequiredEntryStamp());
            Buff.setRequiredDescription(updatedBuff.getRequiredDescription());
            Buff.setOptionalTransferTenantId(updatedBuff.getOptionalTransferTenantId());
            Buff.setOptionalTransferAccountId(updatedBuff.getOptionalTransferAccountId());
            Buff.setOptionalDebitCurrencyId(updatedBuff.getOptionalDebitCurrencyId());
            Buff.setOptionalDebit(updatedBuff.getOptionalDebit());
            Buff.setOptionalCreditCurrencyId(updatedBuff.getOptionalCreditCurrencyId());
            Buff.setOptionalCredit(updatedBuff.getOptionalCredit());
            Buff.setRequiredConvertedCurrencyId(updatedBuff.getRequiredConvertedCurrencyId());
            Buff.setRequiredConvertedAmount(updatedBuff.getRequiredConvertedAmount());
            Buff.setRequiredBalanceCurrencyId(updatedBuff.getRequiredBalanceCurrencyId());
            Buff.setRequiredBalance(updatedBuff.getRequiredBalance());
            Buff.setRequiredRevision(updatedBuff.getRequiredRevision());
        } else {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Expected a single-record response, " + resultSet.getRow() + " rows selected");
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
    }
}

From source file:com.redhat.rhn.manager.channel.ChannelManager.java

/**
 * For the specified server, make a best-guess effort at what its base-channel
 * SHOULD be//from  w  ww. j  av  a2 s.co  m
 * @param usr User asking the question
 * @param sid Server id of interest
 * @return Channel id
 */
public static Long guessServerBase(User usr, Long sid) {
    // Figure out what this server's base OUGHT to be
    CallableMode sbm = ModeFactory.getCallableMode("Channel_queries", "guess_server_base");
    Map<String, Object> inParams = new HashMap<String, Object>();
    inParams.put("server_id", sid);
    Map<String, Integer> outParams = new HashMap<String, Integer>();
    outParams.put("result", new Integer(Types.NUMERIC));
    Map<String, Object> result = sbm.execute(inParams, outParams);

    return (Long) result.get(("result"));
}

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * Creates a group assignment//from   w ww. j av  a  2 s  .c om
 *
 * @param con                  a valid and open connection
 * @param sql                  an instance of StringBuilder
 * @param group                an instance of the FxGroupAssignment to be persisted
 * @param createSubAssignments if true calls createGroupAssignment is called recursively to create sub assignments
 * @return returns the assignmentId
 * @throws FxApplicationException on errors
 */
private long createGroupAssignment(Connection con, StringBuilder sql, FxGroupAssignmentEdit group,
        boolean createSubAssignments) throws FxApplicationException {
    if (!group.isNew())
        throw new FxInvalidParameterException("ex.structure.assignment.create.existing", group.getXPath());
    if (sql == null) {
        sql = new StringBuilder(1000);
    }
    PreparedStatement ps = null;
    long newAssignmentId;
    try {
        FxGroupAssignment thisGroupAssignment;
        String XPath;
        if (!group.getXPath().startsWith(group.getAssignedType().getName())) {
            if (group.getAlias() != null)
                XPath = XPathElement.buildXPath(false, group.getAssignedType().getName(),
                        XPathElement.stripType(group.getXPath()));
            else
                XPath = "/";
        } else
            XPath = group.getXPath();
        if (group.getAlias() != null) {
            sql.setLength(0);
            sql.append("INSERT INTO ").append(TBL_STRUCT_ASSIGNMENTS).
            //               1  2     3       4       5       6       7       8   9     10     11   12          13     14          15
                    append("(ID,ATYPE,ENABLED,TYPEDEF,MINMULT,MAXMULT,DEFMULT,POS,XPATH,XALIAS,BASE,PARENTGROUP,AGROUP,SYSINTERNAL,GROUPMODE)"
                            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            ps = con.prepareStatement(sql.toString());
            newAssignmentId = seq.getId(FxSystemSequencer.ASSIGNMENT);
            ps.setLong(1, newAssignmentId);
            ps.setInt(2, FxAssignment.TYPE_GROUP);
            ps.setBoolean(3, group.isEnabled());
            ps.setLong(4, group.getAssignedType().getId());
            ps.setInt(5, group.getMultiplicity().getMin());
            ps.setInt(6, group.getMultiplicity().getMax());
            ps.setInt(7, group.getDefaultMultiplicity());
            int position = getValidPosition(con, sql, group.getPosition(), group.getAssignedType().getId(),
                    group.getParentGroupAssignment());
            ps.setInt(8, position);
            ps.setString(9, XPath);
            ps.setString(10, group.getAlias());
            if (group.getBaseAssignmentId() == FxAssignment.NO_BASE)
                ps.setNull(11, java.sql.Types.NUMERIC);
            else
                ps.setLong(11, group.getBaseAssignmentId());
            ps.setLong(12, group.getParentGroupAssignment() == null ? FxAssignment.NO_PARENT
                    : group.getParentGroupAssignment().getId());
            ps.setLong(13, group.getGroup().getId());
            ps.setBoolean(14, group.isSystemInternal());
            ps.setInt(15, group.getMode().getId());
            ps.executeUpdate();
            ps.close();
            Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con,
                    TBL_STRUCT_ASSIGNMENTS, new String[] { "DESCRIPTION", "HINT" }, "ID", newAssignmentId);
            thisGroupAssignment = new FxGroupAssignment(newAssignmentId, true, group.getAssignedType(),
                    group.getAlias(), XPath, position, group.getMultiplicity(), group.getDefaultMultiplicity(),
                    group.getParentGroupAssignment(), group.getBaseAssignmentId(), group.getLabel(),
                    group.getHint(), group.getGroup(), group.getMode(), null);
            setAssignmentPosition(con, newAssignmentId, group.getPosition());
        } else {
            thisGroupAssignment = null;
            newAssignmentId = FxAssignment.NO_PARENT;
        }
        htracker.track(group.getAssignedType(), "history.assignment.createGroupAssignment", XPath,
                group.getAssignedType().getId(), group.getAssignedType().getName(), group.getGroup().getId(),
                group.getGroup().getName());

        // FxStructureOption inheritance
        boolean isInheritedAssignment = FxSharedUtils.checkAssignmentInherited(group);
        if (isInheritedAssignment) {
            // FxStructureOptions - retrieve only those with an activated "isInherited" flag
            final List<FxStructureOption> inheritedOpts = FxStructureOption.cloneOptions(group.getOptions(),
                    true);
            if (inheritedOpts.size() > 0) {
                storeOptions(con, TBL_STRUCT_GROUP_OPTIONS, "ID", group.getGroup().getId(), newAssignmentId,
                        inheritedOpts);
            }
        } else {
            storeOptions(con, TBL_STRUCT_GROUP_OPTIONS, "ID", group.getGroup().getId(), newAssignmentId,
                    group.getOptions());
        }

        if (group.getBaseAssignmentId() > 0 && createSubAssignments) {
            FxGroupAssignment baseGroup = (FxGroupAssignment) CacheAdmin.getEnvironment()
                    .getAssignment(group.getBaseAssignmentId());
            for (FxGroupAssignment ga : baseGroup.getAssignedGroups()) {
                FxGroupAssignmentEdit gae = new FxGroupAssignmentEdit(ga);
                gae.setEnabled(group.isEnabled());
                createGroupAssignment(con, sql, FxGroupAssignmentEdit.createNew(gae, group.getAssignedType(),
                        ga.getAlias(), XPath, thisGroupAssignment), createSubAssignments);
            }
            for (FxPropertyAssignment pa : baseGroup.getAssignedProperties()) {
                FxPropertyAssignmentEdit pae = new FxPropertyAssignmentEdit(pa);
                pae.setEnabled(group.isEnabled());
                createPropertyAssignment(con, sql, FxPropertyAssignmentEdit.createNew(pae,
                        group.getAssignedType(), pa.getAlias(), XPath, thisGroupAssignment));
            }
        }
        try {
            StructureLoader.reloadAssignments(FxContext.get().getDivisionId());
        } catch (FxApplicationException e) {
            EJBUtils.rollback(ctx);
            throw new FxCreateException(e, "ex.cache", e.getMessage());
        }
        if (group.getAssignedType().getId() != FxType.ROOT_ID)
            createInheritedAssignments(CacheAdmin.getEnvironment().getAssignment(newAssignmentId), con, sql,
                    group.getAssignedType().getDerivedTypes());
    } catch (SQLException e) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e);
        EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation)
            throw new FxEntryExistsException("ex.structure.assignment.group.exists", group.getAlias(),
                    group.getAssignedType().getName() + group.getXPath());
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } catch (FxNotFoundException e) {
        throw new FxCreateException(e);
    } finally {
        Database.closeObjects(AssignmentEngineBean.class, null, ps);
    }
    return newAssignmentId;
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import flat storages to the hierarchical storage
 *
 * @param con an open and valid connection to store imported data
 * @param zip zip file containing the data
 * @throws Exception on errors//from   w w  w.  j  a v a2 s. c om
 */
protected void importFlatStoragesHierarchical(Connection con, ZipFile zip) throws Exception {
    //mapping: storage->level->columnname->assignment id
    final Map<String, Map<Integer, Map<String, Long>>> flatAssignmentMapping = new HashMap<String, Map<Integer, Map<String, Long>>>(
            5);
    //mapping: assignment id->position index
    final Map<Long, Integer> assignmentPositions = new HashMap<Long, Integer>(100);
    //mapping: flatstorage->column sizes [string,bigint,double,select,text]
    final Map<String, Integer[]> flatstoragesColumns = new HashMap<String, Integer[]>(5);
    ZipEntry zeMeta = getZipEntry(zip, FILE_FLATSTORAGE_META);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(zip.getInputStream(zeMeta));
    XPath xPath = XPathFactory.newInstance().newXPath();

    //calculate column sizes
    NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document,
            XPathConstants.NODESET);
    Node currNode;
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue());
        int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue());
        int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue());
        int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue());
        int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue());
        String tableName = null;
        if (currNode.hasChildNodes()) {
            for (int j = 0; j < currNode.getChildNodes().getLength(); j++)
                if (currNode.getChildNodes().item(j).getNodeName().equals("name")) {
                    tableName = currNode.getChildNodes().item(j).getTextContent();
                }
        }
        if (tableName != null) {
            flatstoragesColumns.put(tableName, new Integer[] { cstring, cbigInt, cdouble, cselect, ctext });
        }
    }

    //parse mappings
    nodes = (NodeList) xPath.evaluate("/flatstorageMeta/mapping", document, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        long assignment = Long.valueOf(currNode.getAttributes().getNamedItem("assid").getNodeValue());
        int level = Integer.valueOf(currNode.getAttributes().getNamedItem("lvl").getNodeValue());
        String storage = null;
        String columnname = null;
        final NodeList childNodes = currNode.getChildNodes();
        for (int c = 0; c < childNodes.getLength(); c++) {
            Node child = childNodes.item(c);
            if ("tblname".equals(child.getNodeName()))
                storage = child.getTextContent();
            else if ("colname".equals(child.getNodeName()))
                columnname = child.getTextContent();
        }
        if (storage == null || columnname == null)
            throw new Exception("Invalid flatstorage export: could not read storage or column name!");
        if (!flatAssignmentMapping.containsKey(storage))
            flatAssignmentMapping.put(storage, new HashMap<Integer, Map<String, Long>>(20));
        Map<Integer, Map<String, Long>> levelMap = flatAssignmentMapping.get(storage);
        if (!levelMap.containsKey(level))
            levelMap.put(level, new HashMap<String, Long>(30));
        Map<String, Long> columnMap = levelMap.get(level);
        if (!columnMap.containsKey(columnname))
            columnMap.put(columnname, assignment);
        //calculate position
        assignmentPositions.put(assignment,
                getAssignmentPosition(flatstoragesColumns.get(storage), columnname));
    }
    if (flatAssignmentMapping.size() == 0) {
        LOG.warn("No flatstorage assignments found to process!");
        return;
    }
    ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT);

    final String xpathStorage = "flatstorages/storage";
    final String xpathData = "flatstorages/storage/data";

    final PreparedStatement psGetAssInfo = con.prepareStatement(
            "SELECT DISTINCT a.APROPERTY,a.XALIAS,p.DATATYPE FROM " + DatabaseConst.TBL_STRUCT_ASSIGNMENTS
                    + " a, " + DatabaseConst.TBL_STRUCT_PROPERTIES + " p WHERE a.ID=? AND p.ID=a.APROPERTY");
    final Map<Long, Object[]> assignmentPropAlias = new HashMap<Long, Object[]>(assignmentPositions.size());
    final String insert1 = "INSERT INTO " + DatabaseConst.TBL_CONTENT_DATA +
    //1  2   3   4    5     6      =1     =1    =1     =1          7         8          9
            "(ID,VER,POS,LANG,TPROP,ASSIGN,XDEPTH,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISMLDEF,";
    final String insert2 = "(?,?,?,?,1,?,?,1,1,1,?,?,?,";
    final PreparedStatement psString = con
            .prepareStatement(insert1 + "FTEXT1024,UFTEXT1024,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psText = con
            .prepareStatement(insert1 + "FCLOB,UFCLOB,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psDouble = con
            .prepareStatement(insert1 + "FDOUBLE,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psNumber = con
            .prepareStatement(insert1 + "FINT,FSELECT,FBIGINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psLargeNumber = con
            .prepareStatement(insert1 + "FBIGINT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psFloat = con
            .prepareStatement(insert1 + "FFLOAT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psBoolean = con
            .prepareStatement(insert1 + "FBOOL,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psReference = con
            .prepareStatement(insert1 + "FREF,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psSelectOne = con
            .prepareStatement(insert1 + "FSELECT,FINT)VALUES" + insert2 + "?,?)");
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private String currentStorage = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            int insertCount = 0;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
                currentStorage = null;
                insertCount = 0;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                LOG.info("Imported [" + insertCount + "] flatstorage entries into the hierarchical storage");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpathData)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else if (currPath.toString().equals(xpathStorage)) {
                    currentStorage = attributes.getValue("name");
                    LOG.info("Processing storage: " + currentStorage);
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            @SuppressWarnings({ "UnusedDeclaration" })
            private void pushPath(String qName, Attributes att) {
                path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpathData)) {
                    //                        LOG.info("Insert [" + xpathData + "]: [" + data + "]");
                    inTag = false;
                    processData();
                    /*try {
                    if (insertMode) {
                        if (executeInsertPhase) {
                            processColumnSet(insertColumns, psInsert);
                            counter += psInsert.executeUpdate();
                        }
                    } else {
                        if (executeUpdatePhase) {
                            if (processColumnSet(updateSetColumns, psUpdate)) {
                                processColumnSet(updateClauseColumns, psUpdate);
                                counter += psUpdate.executeUpdate();
                            }
                        }
                    }
                    } catch (SQLException e) {
                    throw new SAXException(e);
                    } catch (ParseException e) {
                    throw new SAXException(e);
                    }*/
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            void processData() {
                //                    System.out.println("processing " + currentStorage + " -> " + data);
                final String[] cols = { "string", "bigint", "double", "select", "text" };
                for (String column : data.keySet()) {
                    if (column.endsWith("_mld"))
                        continue;
                    for (String check : cols) {
                        if (column.startsWith(check)) {
                            if ("select".equals(check) && "0".equals(data.get(column)))
                                continue; //dont insert 0-referencing selects
                            try {
                                insertData(column);
                            } catch (SQLException e) {
                                //noinspection ThrowableInstanceNeverThrown
                                throw new FxDbException(e, "ex.db.sqlError", e.getMessage())
                                        .asRuntimeException();
                            }
                        }
                    }
                }
            }

            private void insertData(String column) throws SQLException {
                final int level = Integer.parseInt(data.get("lvl"));
                long assignment = flatAssignmentMapping.get(currentStorage).get(level)
                        .get(column.toUpperCase());
                int pos = FxArrayUtils.getIntElementAt(data.get("positions"), ',',
                        assignmentPositions.get(assignment));
                String _valueData = data.get("valuedata");
                Integer valueData = _valueData == null ? null
                        : FxArrayUtils.getHexIntElementAt(data.get("valuedata"), ',',
                                assignmentPositions.get(assignment));
                Object[] propXP = getPropertyXPathDataType(assignment);
                long prop = (Long) propXP[0];
                String xpath = (String) propXP[1];
                FxDataType dataType;
                try {
                    dataType = FxDataType.getById((Long) propXP[2]);
                } catch (FxNotFoundException e) {
                    throw e.asRuntimeException();
                }
                long id = Long.parseLong(data.get("id"));
                int ver = Integer.parseInt(data.get("ver"));
                long lang = Integer.parseInt(data.get("lang"));
                boolean isMaxVer = "1".equals(data.get("ismax_ver"));
                boolean isLiveVer = "1".equals(data.get("islive_ver"));
                boolean mlDef = "1".equals(data.get(column + "_mld"));
                PreparedStatement ps;
                int vdPos;
                switch (dataType) {
                case String1024:
                    ps = psString;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Text:
                case HTML:
                    ps = psText;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Number:
                    ps = psNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case LargeNumber:
                    ps = psLargeNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Reference:
                    ps = psReference;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Float:
                    ps = psFloat;
                    ps.setFloat(10, Float.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Double:
                    ps = psDouble;
                    ps.setDouble(10, Double.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Boolean:
                    ps = psBoolean;
                    ps.setBoolean(10, "1".equals(data.get(column)));
                    vdPos = 11;
                    break;
                case SelectOne:
                    ps = psSelectOne;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                default:
                    //noinspection ThrowableInstanceNeverThrown
                    throw new FxInvalidParameterException("assignment",
                            "ex.structure.flatstorage.datatype.unsupported", dataType.name())
                                    .asRuntimeException();
                }
                ps.setLong(1, id);
                ps.setInt(2, ver);
                ps.setInt(3, pos);
                ps.setLong(4, lang);
                ps.setLong(5, prop);
                ps.setLong(6, assignment);
                ps.setBoolean(7, isMaxVer);
                ps.setBoolean(8, isLiveVer);
                ps.setBoolean(9, mlDef);
                if (valueData == null)
                    ps.setNull(vdPos, java.sql.Types.NUMERIC);
                else
                    ps.setInt(vdPos, valueData);
                ps.executeUpdate();
                insertCount++;
            }

            /**
             * Get property id, xpath and data type for an assignment
             *
             * @param assignment assignment id
             * @return Object[] {propertyId, xpath, datatype}
             */
            private Object[] getPropertyXPathDataType(long assignment) {
                if (assignmentPropAlias.get(assignment) != null)
                    return assignmentPropAlias.get(assignment);
                try {
                    psGetAssInfo.setLong(1, assignment);
                    ResultSet rs = psGetAssInfo.executeQuery();
                    if (rs != null && rs.next()) {
                        Object[] data = new Object[] { rs.getLong(1), rs.getString(2), rs.getLong(3) };
                        assignmentPropAlias.put(assignment, data);
                        return data;
                    }
                } catch (SQLException e) {
                    throw new IllegalArgumentException(
                            "Could not load data for assignment " + assignment + ": " + e.getMessage());
                }
                throw new IllegalArgumentException("Could not load data for assignment " + assignment + "!");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        parser.parse(zip.getInputStream(zeData), handler);
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psGetAssInfo, psString, psBoolean, psDouble,
                psFloat, psLargeNumber, psNumber, psReference, psSelectOne, psText);
    }
}

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

/**
 * Set a properties data for inserts or updates
 *
 * @param insert          perform insert or update?
 * @param prop            current property
 * @param allData         all data of the instance (might be needed to buld references, etc.)
 * @param con             an open and valid connection
 * @param data            current property data
 * @param ps              prepared statement for the data table
 * @param ft              fulltext indexer
 * @param upperColumnPos  position of the uppercase column (if present, else <code>-1</code>)
 * @param includeFullText add fulltext entries? Will be skipped for position only changes
 * @throws SQLException        on errors
 * @throws FxUpdateException   on errors
 * @throws FxDbException       on errors
 * @throws FxNoAccessException for FxNoAccess values
 *///  w ww  . ja  v  a2s  .  c o m
private void setPropertyData(boolean insert, FxProperty prop, List<FxData> allData, Connection con,
        FxPropertyData data, PreparedStatement ps, FulltextIndexer ft, int upperColumnPos,
        boolean includeFullText) throws SQLException, FxUpdateException, FxDbException, FxNoAccessException {
    FxValue value = data.getValue();
    if (value instanceof FxNoAccess)
        throw new FxNoAccessException("ex.content.value.noaccess");
    if (value.isMultiLanguage() != ((FxPropertyAssignment) data.getAssignment()).isMultiLang()) {
        if (((FxPropertyAssignment) data.getAssignment()).isMultiLang())
            throw new FxUpdateException("ex.content.value.invalid.multilanguage.ass.multi",
                    data.getXPathFull());
        else
            throw new FxUpdateException("ex.content.value.invalid.multilanguage.ass.single",
                    data.getXPathFull());
    }
    int pos_lang = insert ? INSERT_LANG_POS : UPDATE_ID_POS + 2;
    int pos_isdef_lang = insert ? INSERT_ISDEF_LANG_POS : UPDATE_MLDEF_POS;
    final FxEnvironment env = CacheAdmin.getEnvironment();
    if (prop.getDataType().isSingleRowStorage()) {
        //Data types that just use one db row can be handled in a very similar way
        Object translatedValue;
        GregorianCalendar gc = null;
        final long[] translatedLanguages = value.getTranslatedLanguages();
        for (long translatedLanguage : translatedLanguages) {
            translatedValue = value.getTranslation(translatedLanguage);
            if (translatedValue == null) {
                LOG.warn("Translation for " + data.getXPath() + " is null!");
            }
            ps.setLong(pos_lang, translatedLanguage);
            if (!value.isMultiLanguage())
                ps.setBoolean(pos_isdef_lang, true);
            else
                ps.setBoolean(pos_isdef_lang, value.isDefaultLanguage(translatedLanguage));
            if (upperColumnPos != -1) {
                final Locale locale = value.isMultiLanguage() ? env.getLanguage(translatedLanguage).getLocale()
                        : Locale.getDefault();
                ps.setString(upperColumnPos, translatedValue.toString().toUpperCase(locale));
            }
            int[] pos = insert ? getColumnPosInsert(prop) : getColumnPosUpdate(prop);
            switch (prop.getDataType()) {
            case Double:
                checkDataType(FxDouble.class, value, data.getXPathFull());
                ps.setDouble(pos[0], (Double) translatedValue);
                break;
            case Float:
                checkDataType(FxFloat.class, value, data.getXPathFull());
                ps.setFloat(pos[0], (Float) translatedValue);
                break;
            case LargeNumber:
                checkDataType(FxLargeNumber.class, value, data.getXPathFull());
                ps.setLong(pos[0], (Long) translatedValue);
                break;
            case Number:
                checkDataType(FxNumber.class, value, data.getXPathFull());
                ps.setInt(pos[0], (Integer) translatedValue);
                break;
            case HTML:
                checkDataType(FxHTML.class, value, data.getXPathFull());
                boolean useTidy = ((FxHTML) value).isTidyHTML();
                ps.setBoolean(pos[1], useTidy);
                final String extractorInput = doTidy(data.getXPathFull(), (String) translatedValue);
                if (useTidy) {
                    translatedValue = extractorInput;
                }
                final HtmlExtractor result = new HtmlExtractor(extractorInput, true);
                setBigString(ps, pos[2], result.getText());
                setBigString(ps, pos[0], (String) translatedValue);
                break;
            case String1024:
            case Text:
                checkDataType(FxString.class, value, data.getXPathFull());
                setBigString(ps, pos[0], (String) translatedValue);
                break;
            case Boolean:
                checkDataType(FxBoolean.class, value, data.getXPathFull());
                ps.setBoolean(pos[0], (Boolean) translatedValue);
                break;
            case Date:
                checkDataType(FxDate.class, value, data.getXPathFull());
                if (gc == null)
                    gc = new GregorianCalendar();
                gc.setTime((Date) translatedValue);
                //strip all time information, this might not be necessary since ps.setDate() strips them
                //for most databases but won't hurt either ;)
                gc.set(GregorianCalendar.HOUR, 0);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);
                ps.setDate(pos[0], new java.sql.Date(gc.getTimeInMillis()));
                break;
            case DateTime:
                checkDataType(FxDateTime.class, value, data.getXPathFull());
                if (gc == null)
                    gc = new GregorianCalendar();
                gc.setTime((Date) translatedValue);
                ps.setTimestamp(pos[0], new Timestamp(gc.getTimeInMillis()));
                break;
            case DateRange:
                checkDataType(FxDateRange.class, value, data.getXPathFull());
                if (gc == null)
                    gc = new GregorianCalendar();
                gc.setTime(((DateRange) translatedValue).getLower());
                gc.set(GregorianCalendar.HOUR, 0);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);
                ps.setDate(pos[0], new java.sql.Date(gc.getTimeInMillis()));
                gc.setTime(((DateRange) translatedValue).getUpper());
                gc.set(GregorianCalendar.HOUR, 0);
                gc.set(GregorianCalendar.MINUTE, 0);
                gc.set(GregorianCalendar.SECOND, 0);
                gc.set(GregorianCalendar.MILLISECOND, 0);
                ps.setDate(pos[1], new java.sql.Date(gc.getTimeInMillis()));
                break;
            case DateTimeRange:
                checkDataType(FxDateTimeRange.class, value, data.getXPathFull());
                if (gc == null)
                    gc = new GregorianCalendar();
                gc.setTime(((DateRange) translatedValue).getLower());
                ps.setTimestamp(pos[0], new Timestamp(gc.getTimeInMillis()));
                gc.setTime(((DateRange) translatedValue).getUpper());
                ps.setTimestamp(pos[1], new Timestamp(gc.getTimeInMillis()));
                break;
            case Binary:
                checkDataType(FxBinary.class, value, data.getXPathFull());
                BinaryDescriptor binary = (BinaryDescriptor) translatedValue;
                if (!binary.isNewBinary()) {
                    ps.setLong(pos[0], binary.getId());
                } else {
                    try {
                        //transfer the binary from the transit table to the binary table
                        BinaryDescriptor created = binaryStorage.binaryTransit(con, binary);
                        ps.setLong(pos[0], created.getId());
                        //check all other properties if they contain the same handle
                        //and replace with the data of the new binary
                        for (FxData _curr : allData) {
                            if (_curr instanceof FxPropertyData && !_curr.isEmpty()
                                    && ((FxPropertyData) _curr).getValue() instanceof FxBinary) {
                                FxBinary _val = (FxBinary) ((FxPropertyData) _curr).getValue();
                                _val._replaceHandle(binary.getHandle(), created);
                            }
                        }
                    } catch (FxApplicationException e) {
                        throw new FxDbException(e);
                    }
                }
                break;
            case SelectOne:
                checkDataType(FxSelectOne.class, value, data.getXPathFull());
                ps.setLong(pos[0], ((FxSelectListItem) translatedValue).getId());
                break;
            case SelectMany:
                checkDataType(FxSelectMany.class, value, data.getXPathFull());
                SelectMany sm = (SelectMany) translatedValue;

                for (int i1 = 0; i1 < sm.getSelected().size(); i1++) {
                    FxSelectListItem item = sm.getSelected().get(i1);
                    if (i1 > 0) {
                        if (batchContentDataChanges())
                            ps.addBatch();
                        else
                            ps.executeUpdate();
                    }
                    ps.setLong(pos[0], item.getId());
                    ps.setString(pos[1], sm.getSelectedIdsList());
                    ps.setLong(pos[2], sm.getSelectedIds().size());
                }
                if (sm.getSelected().size() == 0)
                    ps.setLong(pos[0], 0); //write the virtual item as a marker to have a valid row
                break;
            case Reference:
                //reference integrity check is done prior to saving
                ps.setLong(pos[0], ((FxPK) translatedValue).getId());
                break;
            case InlineReference:
            default:
                throw new FxDbException(LOG, "ex.db.notImplemented.store", prop.getDataType().getName());
            }
            int valueDataPos = insert ? getValueDataInsertPos(prop.getDataType())
                    : getValueDataUpdatePos(prop.getDataType());
            if (value.hasValueData(translatedLanguage)) {
                ps.setInt(valueDataPos, value.getValueDataRaw(translatedLanguage));
            } else
                ps.setNull(valueDataPos, Types.NUMERIC);
            if (batchContentDataChanges())
                ps.addBatch();
            else {
                try {
                    ps.executeUpdate();
                } catch (SQLException e) {
                    LOG.error(prop.getName(), e);
                    throw e;
                }
            }
        }
    } else {
        switch (prop.getDataType()) {
        //TODO: implement datatype specific insert
        default:
            throw new FxDbException(LOG, "ex.db.notImplemented.store", prop.getDataType().getName());
        }

    }
    if (ft != null && prop.isFulltextIndexed() && includeFullText)
        ft.index(data);
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Create a new Node from a ResultSet./*from  w  ww. ja  v  a2 s  . com*/
 */
public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset)
        throws SQLException, IOException, ClassNotFoundException {
    HashMap propBuffer = new HashMap();
    String id = null;
    String name = null;
    String protoName = dbm.getTypeName();
    DbMapping dbmap = dbm;

    Node node = new Node();

    for (int i = 0; i < columns.length; i++) {
        // set prototype?
        if (columns[i].isPrototypeField()) {
            protoName = rs.getString(i + 1 + offset);

            if (protoName != null) {
                dbmap = getDbMapping(protoName);

                if (dbmap == null) {
                    // invalid prototype name!
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "createNode")
                            + "Invalid prototype name: " + protoName + " - using default");
                    dbmap = dbm;
                    protoName = dbmap.getTypeName();
                }
            }
        }

        // set id?
        if (columns[i].isIdField()) {
            id = rs.getString(i + 1 + offset);
            // if id == null, the object doesn't actually exist - return null
            if (id == null) {
                return null;
            }
        }

        // set name?
        if (columns[i].isNameField()) {
            name = rs.getString(i + 1 + offset);
        }

        Property newprop = new Property(node);

        switch (columns[i].getType()) {
        case Types.BIT:
            newprop.setBooleanValue(rs.getBoolean(i + 1 + offset));

            break;

        case Types.TINYINT:
        case Types.BIGINT:
        case Types.SMALLINT:
        case Types.INTEGER:
            newprop.setIntegerValue(rs.getLong(i + 1 + offset));

            break;

        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
            newprop.setFloatValue(rs.getDouble(i + 1 + offset));

            break;

        case Types.DECIMAL:
        case Types.NUMERIC:

            BigDecimal num = rs.getBigDecimal(i + 1 + offset);

            if (num == null) {
                break;
            }

            if (num.scale() > 0) {
                newprop.setFloatValue(num.doubleValue());
            } else {
                newprop.setIntegerValue(num.longValue());
            }

            break;

        case Types.VARBINARY:
        case Types.BINARY:
            //                    newprop.setStringValue(rs.getString(i+1+offset));
            newprop.setJavaObjectValue(rs.getBytes(i + 1 + offset));

            break;

        case Types.LONGVARBINARY: {
            InputStream in = rs.getBinaryStream(i + 1 + offset);
            if (in == null) {
                break;
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int read;
            while ((read = in.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
            }
            newprop.setJavaObjectValue(bout.toByteArray());
        }

            break;
        case Types.LONGVARCHAR:
            try {
                newprop.setStringValue(rs.getString(i + 1 + offset));
            } catch (SQLException x) {
                Reader in = rs.getCharacterStream(i + 1 + offset);
                char[] buffer = new char[2048];
                int read = 0;
                int r;

                while ((r = in.read(buffer, read, buffer.length - read)) > -1) {
                    read += r;

                    if (read == buffer.length) {
                        // grow input buffer
                        char[] newBuffer = new char[buffer.length * 2];

                        System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
                        buffer = newBuffer;
                    }
                }

                newprop.setStringValue(new String(buffer, 0, read));
            }

            break;

        case Types.CHAR:
        case Types.VARCHAR:
        case Types.OTHER:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            newprop.setDateValue(rs.getTimestamp(i + 1 + offset));

            break;

        case Types.NULL:
            newprop.setStringValue(null);

            break;

        case Types.CLOB:
            Clob cl = rs.getClob(i + 1 + offset);
            if (cl == null) {
                newprop.setStringValue(null);
                break;
            }
            char[] c = new char[(int) cl.length()];
            Reader isr = cl.getCharacterStream();
            isr.read(c);
            newprop.setStringValue(String.copyValueOf(c));
            break;

        default:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;
        }

        if (rs.wasNull()) {
            newprop.setStringValue(null);
        }

        propBuffer.put(columns[i].getName(), newprop);

        // mark property as clean, since it's fresh from the db
        newprop.dirty = false;
    }

    if (id == null) {
        return null;
    }

    Hashtable propMap = new Hashtable();
    DbColumn[] columns2 = dbmap.getColumns();
    for (int i = 0; i < columns2.length; i++) {
        Relation rel = columns2[i].getRelation();

        if (rel != null && (rel.reftype == Relation.PRIMITIVE || rel.reftype == Relation.REFERENCE)) {

            Property prop = (Property) propBuffer.get(columns2[i].getName());

            if (prop == null) {
                continue;
            }
            prop.setName(rel.propName);
            // if the property is a pointer to another node, change the property type to NODE
            if ((rel.reftype == Relation.REFERENCE) && rel.usesPrimaryKey()) {
                // FIXME: References to anything other than the primary key are not supported
                prop.convertToNodeReference(rel.otherType, this.app.getCurrentRequestEvaluator().getLayer());
            }
            propMap.put(rel.propName.toLowerCase(), prop);
        }
    }

    node.init(dbmap, id, name, protoName, propMap, safe);

    return node;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private Map<String, Integer> getTableSchema(SchemaAndTable schemaAndTable) throws SQLException {
    Map<String, Integer> columns = new HashMap<>();
    String query = "SELECT * FROM \"" + schemaAndTable.getSchema() + "\".\"" + schemaAndTable.getTable()
            + "\" WHERE 1 = 0";
    try (Statement schemaStatement = connection.createStatement();
            ResultSet rs = schemaStatement.executeQuery(query)) {
        ResultSetMetaData md = rs.getMetaData();
        int colCount = md.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            int colType = md.getColumnType(i);
            String colName = md.getColumnName(i);
            if (!configBean.baseConfigBean.caseSensitive) {
                colName = colName.toUpperCase();
            }/* w  w w.  ja va  2  s  .  co m*/
            if (colType == Types.DATE || colType == Types.TIME || colType == Types.TIMESTAMP) {
                dateTimeColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>());
                dateTimeColumns.get(schemaAndTable).put(colName, md.getColumnTypeName(i));
            }

            if (colType == Types.DECIMAL || colType == Types.NUMERIC) {
                decimalColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>());
                decimalColumns.get(schemaAndTable).put(colName,
                        new PrecisionAndScale(md.getPrecision(i), md.getScale(i)));
            }
            columns.put(md.getColumnName(i), md.getColumnType(i));
        }
    }
    return columns;
}

From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java

private void setNumericValue(int queryType, String value, String paramType, PreparedStatement sqlQuery, int i)
        throws SQLException {
    BigDecimal val = null;
    if (value != null) {
        val = new BigDecimal(value);
    }/*from ww  w .  j  a  v  a 2s. com*/
    if (QueryTypes.IN.equals(paramType)) {
        if (queryType == SQLQuery.DS_QUERY_TYPE_NORMAL) {
            if (value == null) {
                sqlQuery.setNull(i + 1, java.sql.Types.NUMERIC);
            } else {
                sqlQuery.setBigDecimal(i + 1, val);
            }
        } else {
            if (value == null) {
                ((CallableStatement) sqlQuery).setNull(i + 1, java.sql.Types.NUMERIC);
            } else {
                ((CallableStatement) sqlQuery).setBigDecimal(i + 1, val);
            }
        }
    } else if (QueryTypes.INOUT.equals(paramType)) {
        if (value == null) {
            ((CallableStatement) sqlQuery).setNull(i + 1, java.sql.Types.NUMERIC);
        } else {
            ((CallableStatement) sqlQuery).setBigDecimal(i + 1, val);
        }
        ((CallableStatement) sqlQuery).registerOutParameter(i + 1, java.sql.Types.NUMERIC);
    } else {
        ((CallableStatement) sqlQuery).registerOutParameter(i + 1, java.sql.Types.NUMERIC);
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccOracle.CFAccOracleAccountEntryTable.java

public void updateAccountEntry(CFAccAuthorization Authorization, CFAccAccountEntryBuff Buff) {
    final String S_ProcName = "updateAccountEntry";
    ResultSet resultSet = null;// ww  w .j  a  v a 2 s  .c o  m
    Connection cnx = schema.getCnx();
    CallableStatement stmtUpdateByPKey = null;
    List<CFAccAccountEntryBuff> buffList = new LinkedList<CFAccAccountEntryBuff>();
    try {
        long TenantId = Buff.getRequiredTenantId();
        long AccountId = Buff.getRequiredAccountId();
        UUID EntryId = Buff.getRequiredEntryId();
        UUID SplitEntryId = Buff.getOptionalSplitEntryId();
        Calendar EntryStamp = Buff.getRequiredEntryStamp();
        String Description = Buff.getRequiredDescription();
        Long TransferTenantId = Buff.getOptionalTransferTenantId();
        Long TransferAccountId = Buff.getOptionalTransferAccountId();
        Short DebitCurrencyId = Buff.getOptionalDebitCurrencyId();
        BigDecimal Debit = Buff.getOptionalDebit();
        Short CreditCurrencyId = Buff.getOptionalCreditCurrencyId();
        BigDecimal Credit = Buff.getOptionalCredit();
        short ConvertedCurrencyId = Buff.getRequiredConvertedCurrencyId();
        BigDecimal ConvertedAmount = Buff.getRequiredConvertedAmount();
        short BalanceCurrencyId = Buff.getRequiredBalanceCurrencyId();
        BigDecimal Balance = Buff.getRequiredBalance();
        int Revision = Buff.getRequiredRevision();
        stmtUpdateByPKey = cnx.prepareCall("begin " + schema.getLowerSchemaDbName()
                + ".upd_ac_entry( ?, ?, ?, ?, ?, ?, ?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?"
                + ", " + "to_timestamp( ?, 'YYYY-MM-DD HH24:MI:SS' )" + ", " + "?" + ", " + "?" + ", " + "?"
                + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?"
                + ", " + "?" + ", " + "? ); end;");
        int argIdx = 1;
        stmtUpdateByPKey.registerOutParameter(argIdx++, OracleTypes.CURSOR);
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
        stmtUpdateByPKey.setString(argIdx++, "ACNY");
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setLong(argIdx++, AccountId);
        stmtUpdateByPKey.setString(argIdx++, EntryId.toString());
        if (SplitEntryId != null) {
            stmtUpdateByPKey.setString(argIdx++, SplitEntryId.toString());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.VARCHAR);
        }
        stmtUpdateByPKey.setString(argIdx++, CFAccOracleSchema.getTimestampString(EntryStamp));
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (TransferTenantId != null) {
            stmtUpdateByPKey.setLong(argIdx++, TransferTenantId.longValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.BIGINT);
        }
        if (TransferAccountId != null) {
            stmtUpdateByPKey.setLong(argIdx++, TransferAccountId.longValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.BIGINT);
        }
        if (DebitCurrencyId != null) {
            stmtUpdateByPKey.setShort(argIdx++, DebitCurrencyId.shortValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.SMALLINT);
        }
        if (Debit != null) {
            stmtUpdateByPKey.setBigDecimal(argIdx++, Debit);
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.NUMERIC);
        }
        if (CreditCurrencyId != null) {
            stmtUpdateByPKey.setShort(argIdx++, CreditCurrencyId.shortValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.SMALLINT);
        }
        if (Credit != null) {
            stmtUpdateByPKey.setBigDecimal(argIdx++, Credit);
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.NUMERIC);
        }
        stmtUpdateByPKey.setShort(argIdx++, ConvertedCurrencyId);
        stmtUpdateByPKey.setBigDecimal(argIdx++, ConvertedAmount);
        stmtUpdateByPKey.setShort(argIdx++, BalanceCurrencyId);
        stmtUpdateByPKey.setBigDecimal(argIdx++, Balance);
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        stmtUpdateByPKey.execute();
        resultSet = (ResultSet) stmtUpdateByPKey.getObject(1);
        if (resultSet != null) {
            try {
                if (resultSet.next()) {
                    CFAccAccountEntryBuff updatedBuff = unpackAccountEntryResultSetToBuff(resultSet);
                    if (resultSet.next()) {
                        resultSet.last();
                        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                                "Did not expect multi-record response, " + resultSet.getRow()
                                        + " rows selected");
                    }
                    Buff.setOptionalSplitEntryId(updatedBuff.getOptionalSplitEntryId());
                    Buff.setRequiredEntryStamp(updatedBuff.getRequiredEntryStamp());
                    Buff.setRequiredDescription(updatedBuff.getRequiredDescription());
                    Buff.setOptionalTransferTenantId(updatedBuff.getOptionalTransferTenantId());
                    Buff.setOptionalTransferAccountId(updatedBuff.getOptionalTransferAccountId());
                    Buff.setOptionalDebitCurrencyId(updatedBuff.getOptionalDebitCurrencyId());
                    Buff.setOptionalDebit(updatedBuff.getOptionalDebit());
                    Buff.setOptionalCreditCurrencyId(updatedBuff.getOptionalCreditCurrencyId());
                    Buff.setOptionalCredit(updatedBuff.getOptionalCredit());
                    Buff.setRequiredConvertedCurrencyId(updatedBuff.getRequiredConvertedCurrencyId());
                    Buff.setRequiredConvertedAmount(updatedBuff.getRequiredConvertedAmount());
                    Buff.setRequiredBalanceCurrencyId(updatedBuff.getRequiredBalanceCurrencyId());
                    Buff.setRequiredBalance(updatedBuff.getRequiredBalance());
                    Buff.setRequiredRevision(updatedBuff.getRequiredRevision());
                } else {
                    throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                            "Expected a single-record response, " + resultSet.getRow() + " rows selected");
                }
            } catch (SQLException e) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "upd_ac_entry() did not return a valid result cursor");
            } finally {
                if (resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                    }
                    resultSet = null;
                }
            }
        } else {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "upd_ac_entry() did not return a result cursor");
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
        if (stmtUpdateByPKey != null) {
            try {
                stmtUpdateByPKey.close();
            } catch (SQLException e) {
            }
            stmtUpdateByPKey = null;
        }
    }
}

From source file:com.redhat.rhn.manager.system.SystemManager.java

/**
 * Tests whether or not a given server can be entitled with a specific entitlement
 * @param serverId The Id of the server in question
 * @param ent The entitlement to test/*from  w  w  w  . ja va2 s.c  om*/
 * @return Returns true or false depending on whether or not the server can be
 * entitled to the passed in entitlement.
 */
public static boolean canEntitleServer(Long serverId, Entitlement ent) {
    if (log.isDebugEnabled()) {
        log.debug("canEntitleServer.serverId: " + serverId + " ent: " + ent.getHumanReadableLabel());
    }
    Map<String, Object> in = new HashMap<String, Object>();
    in.put("sid", serverId);
    in.put("entitlement", ent.getLabel());

    Map<String, Integer> out = new HashMap<String, Integer>();
    out.put("retval", new Integer(Types.NUMERIC));

    CallableMode m = ModeFactory.getCallableMode("System_queries", "can_entitle_server");
    Map<String, Object> result = m.execute(in, out);
    boolean retval = BooleanUtils.toBoolean(((Long) result.get("retval")).intValue());
    log.debug("canEntitleServer.returning: " + retval);
    return retval;
}