Example usage for java.sql Types SQLXML

List of usage examples for java.sql Types SQLXML

Introduction

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

Prototype

int SQLXML

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

Click Source Link

Document

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

Usage

From source file:com.siemens.scr.avt.ad.hibernate.StringXMLType.java

public int[] sqlTypes() {
    return new int[] { Types.SQLXML };
}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.tablemodel.TypeMapper.java

private static Class mapSQLType(final int t) {
    switch (t) {//from   w w w  .  j a v  a  2 s .  c  o  m
    case Types.ARRAY:
        return Object[].class;
    case Types.BIGINT:
        return Long.class;
    case Types.BINARY:
        return byteArrayClass;
    case Types.BIT:
        return Boolean.class;
    case Types.BLOB:
        return Blob.class;
    case Types.BOOLEAN: // Types.BOOLEAN was not part of JDK1.2.2
        return Boolean.class;
    case Types.CHAR:
        return String.class;
    case Types.CLOB:
        return Clob.class;
    case Types.DATALINK: // Types.DATALINK was not part of JDK 1.2.2
        return URL.class;
    case Types.DATE:
        return java.sql.Date.class;
    case Types.DECIMAL:
        return java.math.BigDecimal.class;
    case Types.DISTINCT:
        return Object.class;
    case Types.DOUBLE:
        return Double.class;
    case Types.FLOAT:
        return Double.class;
    case Types.INTEGER:
        return Integer.class;
    case Types.JAVA_OBJECT:
        return Object.class;
    case Types.LONGVARBINARY:
        return byteArrayClass;
    case Types.LONGVARCHAR:
        return String.class;
    case Types.NCLOB:
        return NClob.class;
    case Types.NULL:
        return Object.class;
    case Types.NUMERIC:
        return java.math.BigDecimal.class;
    case Types.NCHAR:
    case Types.NVARCHAR:
    case Types.LONGNVARCHAR:
        return String.class;
    case Types.OTHER:
        return Object.class;
    case Types.REAL:
        return Float.class;
    case Types.REF:
        return Ref.class;
    case Types.ROWID:
        return RowId.class;
    case Types.SMALLINT:
        return Short.class;
    case Types.STRUCT:
        return Struct.class;
    case Types.SQLXML:
        return SQLXML.class;
    case Types.TIME:
        return Time.class;
    case Types.TIMESTAMP:
        return Timestamp.class;
    case Types.TINYINT:
        return Byte.class;
    case Types.VARBINARY:
        return byteArrayClass;
    case Types.VARCHAR:
        return String.class;
    default:
        return Object.class;
    }
}

From source file:org.fao.geonet.arcgis.ArcSDEJdbcConnection.java

@Override
public Map<String, String> retrieveMetadata(AtomicBoolean cancelMonitor, String arcSDEVersion)
        throws Exception {
    Map<String, String> results = new HashMap<>();

    ArcSDEVersionFactory arcSDEVersionFactory = new ArcSDEVersionFactory();
    String metadataTable = arcSDEVersionFactory.getTableName(arcSDEVersion);
    String columnName = arcSDEVersionFactory.getMetadataColumnName(arcSDEVersion);

    String sqlQuery = "SELECT " + columnName + ", UUID FROM " + metadataTable;

    getJdbcTemplate().query(sqlQuery, new RowCallbackHandler() {
        @Override// www  .ja v  a2 s .c om
        public void processRow(ResultSet rs) throws SQLException {
            // Cancel processing
            if (cancelMonitor.get()) {
                Log.warning(ARCSDE_LOG_MODULE_NAME,
                        "Cancelling metadata retrieve using " + "ArcSDE connection (via JDBC)");
                rs.getStatement().cancel();
                results.clear();
            }

            String document = "";
            int colId = rs.findColumn(columnName);
            int colIdUuid = rs.findColumn("UUID");
            // very simple type check:
            if (rs.getObject(colId) != null) {
                if (rs.getMetaData().getColumnType(colId) == Types.BLOB) {
                    Blob blob = rs.getBlob(columnName);
                    byte[] bdata = blob.getBytes(1, (int) blob.length());
                    document = new String(bdata);

                } else if (rs.getMetaData().getColumnType(colId) == Types.LONGVARBINARY) {
                    byte[] byteData = rs.getBytes(colId);
                    document = new String(byteData);

                } else if (rs.getMetaData().getColumnType(colId) == Types.LONGNVARCHAR
                        || rs.getMetaData().getColumnType(colId) == Types.LONGVARCHAR
                        || rs.getMetaData().getColumnType(colId) == Types.VARCHAR
                        || rs.getMetaData().getColumnType(colId) == Types.SQLXML) {
                    document = rs.getString(colId);

                } else {
                    throw new SQLException("Trying to harvest from a column with an invalid datatype: "
                            + rs.getMetaData().getColumnTypeName(colId));
                }

                String uuid = rs.getString(colIdUuid);
                ;
                results.put(uuid, document);
            }

        }
    });

    Log.info(ARCSDE_LOG_MODULE_NAME,
            "Finished retrieving metadata, found: #" + results.size() + " metadata records");

    return results;
}

From source file:org.executequery.gui.resultset.ResultSetTableModel.java

public void createTable(ResultSet resultSet) {

    if (!isOpenAndValid(resultSet)) {

        clearData();/*from   w w  w.j a  v  a  2  s .co  m*/
        return;
    }

    try {

        resetMetaData();
        ResultSetMetaData rsmd = resultSet.getMetaData();

        columnHeaders.clear();
        visibleColumnHeaders.clear();
        tableData.clear();

        int zeroBaseIndex = 0;
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {

            zeroBaseIndex = i - 1;

            columnHeaders.add(new ResultSetColumnHeader(zeroBaseIndex, rsmd.getColumnLabel(i),
                    rsmd.getColumnName(i), rsmd.getColumnType(i), rsmd.getColumnTypeName(i)));
        }

        int recordCount = 0;
        interrupted = false;

        if (holdMetaData) {

            setMetaDataVectors(rsmd);
        }

        List<RecordDataItem> rowData;
        long time = System.currentTimeMillis();
        while (resultSet.next()) {

            if (interrupted || Thread.interrupted()) {

                throw new InterruptedException();
            }

            recordCount++;
            rowData = new ArrayList<RecordDataItem>(count);

            for (int i = 1; i <= count; i++) {

                zeroBaseIndex = i - 1;

                ResultSetColumnHeader header = columnHeaders.get(zeroBaseIndex);
                RecordDataItem value = recordDataItemFactory.create(header);

                try {

                    int dataType = header.getDataType();
                    switch (dataType) {

                    // some drivers (informix for example)
                    // was noticed to return the hashcode from
                    // getObject for -1 data types (eg. longvarchar).
                    // force string for these - others stick with
                    // getObject() for default value formatting

                    case Types.CHAR:
                    case Types.VARCHAR:
                        value.setValue(resultSet.getString(i));
                        break;
                    case Types.DATE:
                        value.setValue(resultSet.getDate(i));
                        break;
                    case Types.TIME:
                        value.setValue(resultSet.getTime(i));
                        break;
                    case Types.TIMESTAMP:
                        value.setValue(resultSet.getTimestamp(i));
                        break;
                    case Types.LONGVARCHAR:
                    case Types.CLOB:
                        value.setValue(resultSet.getClob(i));
                        break;
                    case Types.LONGVARBINARY:
                    case Types.VARBINARY:
                    case Types.BINARY:
                        value.setValue(resultSet.getBytes(i));
                        break;
                    case Types.BLOB:
                        value.setValue(resultSet.getBlob(i));
                        break;
                    case Types.BIT:
                    case Types.TINYINT:
                    case Types.SMALLINT:
                    case Types.INTEGER:
                    case Types.BIGINT:
                    case Types.FLOAT:
                    case Types.REAL:
                    case Types.DOUBLE:
                    case Types.NUMERIC:
                    case Types.DECIMAL:
                    case Types.NULL:
                    case Types.OTHER:
                    case Types.JAVA_OBJECT:
                    case Types.DISTINCT:
                    case Types.STRUCT:
                    case Types.ARRAY:
                    case Types.REF:
                    case Types.DATALINK:
                    case Types.BOOLEAN:
                    case Types.ROWID:
                    case Types.NCHAR:
                    case Types.NVARCHAR:
                    case Types.LONGNVARCHAR:
                    case Types.NCLOB:
                    case Types.SQLXML:

                        // use getObject for all other known types

                        value.setValue(resultSet.getObject(i));
                        break;

                    default:

                        // otherwise try as string

                        asStringOrObject(value, resultSet, i);
                        break;
                    }

                } catch (Exception e) {

                    try {

                        // ... and on dump, resort to string
                        value.setValue(resultSet.getString(i));

                    } catch (SQLException sqlException) {

                        // catch-all SQLException - yes, this is hideous

                        // noticed with invalid date formatted values in mysql

                        value.setValue("<Error - " + sqlException.getMessage() + ">");
                    }
                }

                if (resultSet.wasNull()) {

                    value.setNull();
                }

                rowData.add(value);
            }

            tableData.add(rowData);

            if (recordCount == maxRecords) {

                break;
            }

        }

        if (Log.isTraceEnabled()) {

            Log.trace("Finished populating table model - " + recordCount + " rows - [ "
                    + MiscUtils.formatDuration(System.currentTimeMillis() - time) + "]");
        }

        fireTableStructureChanged();

    } catch (SQLException e) {

        System.err.println("SQL error populating table model at: " + e.getMessage());
        Log.debug("Table model error - " + e.getMessage(), e);

    } catch (Exception e) {

        if (e instanceof InterruptedException) {

            Log.debug("ResultSet generation interrupted.", e);

        } else {

            String message = e.getMessage();
            if (StringUtils.isBlank(message)) {

                System.err.println("Exception populating table model.");

            } else {

                System.err.println("Exception populating table model at: " + message);
            }

            Log.debug("Table model error - ", e);
        }

    } finally {

        if (resultSet != null) {

            try {

                resultSet.close();

                Statement statement = resultSet.getStatement();
                if (statement != null) {

                    statement.close();
                }

            } catch (SQLException e) {
            }

        }
    }

}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.StandardRowSetBuilder.java

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }//from   w w w  . j  av a  2  s  .c om
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    FieldFormatter[] fFormatters = buildFormatterArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

    boolean noKey = ((keyField == null) || keyField.isEmpty());

    //boolean isNull = false;
    Element data = null;
    Element row = null;
    Element col = null;
    Text text = null;
    String textVal = null;
    String precKey = null;
    String colKey = null;
    Map<String, String> keyAttr = new HashMap<String, String>();
    while (rs.next()) {
        if (rowCounter % 10 == 0) {
            ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger);
        }
        row = parser.createElement(doc, AbstractDBO.ROW_NAME);

        parser.setAttribute(row, AbstractDBO.ID_NAME, id);
        for (int j = 1; j <= metadata.getColumnCount(); j++) {
            FieldFormatter fF = fFormatters[j];

            //isNull = false;
            col = parser.createElement(doc, AbstractDBO.COL_NAME);
            switch (metadata.getColumnType(j)) {
            case Types.DATE: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DATE_TYPE);
                java.sql.Date dateVal = rs.getDate(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT);
            }
                break;
            case Types.TIME: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIME_TYPE);
                java.sql.Time dateVal = rs.getTime(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_TIME_FORMAT);
            }
                break;
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT);
            }
                break;
            case Types.DOUBLE: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                double numVal = rs.getDouble(j);
                textVal = processDouble(col, fF, numVal);
            }
                break;
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                textVal = processDouble(col, fF, numVal);
            }
                break;
            case Types.BIGINT: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BIGINT_TYPE);
                long numVal = rs.getLong(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.INTEGER: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.INTEGER_TYPE);
                int numVal = rs.getInt(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.SMALLINT:
            case Types.TINYINT: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.SMALLINT_TYPE);
                short numVal = rs.getShort(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.NUMERIC:
            case Types.DECIMAL: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                boolean isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.BOOLEAN: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BOOLEAN_TYPE);
                boolean bVal = rs.getBoolean(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(bVal);
            }
                break;
            case Types.SQLXML: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.XML_TYPE);
                SQLXML xml = rs.getSQLXML(j);
                boolean isNull = xml == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    textVal = xml.getString();
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                if (textVal == null) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                boolean isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                } else {
                    textVal = "";
                }
            }
                break;
            case Types.CLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE);
                Clob clob = rs.getClob(j);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                } else {
                    textVal = "";
                }
            }
                break;
            case Types.BLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE);
                Blob blob = rs.getBlob(j);
                boolean isNull = blob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    InputStream is = blob.getBinaryStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(is, baos);
                    is.close();
                    try {
                        byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                        textVal = Base64.getEncoder().encodeToString(buffer);
                    } catch (SQLFeatureNotSupportedException exc) {
                        textVal = Base64.getEncoder().encodeToString(baos.toByteArray());
                    }
                }
            }
                break;
            default: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE);
                textVal = rs.getString(j);
                boolean isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
            }
            if (textVal != null) {
                text = doc.createTextNode(textVal);
                col.appendChild(text);
            }
            if (!noKey && keyField.contains(new Integer(j))) {
                if (textVal != null) {
                    if (colKey == null) {
                        colKey = textVal;
                    } else {
                        colKey += "##" + textVal;
                    }
                    keyAttr.put("key_" + j, textVal);
                }
            } else {
                row.appendChild(col);
            }
        }
        if (noKey) {
            if (data == null) {
                data = parser.createElement(doc, AbstractDBO.DATA_NAME);
                parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            }
        } else if ((colKey != null) && !colKey.equals(precKey)) {
            if (data != null) {
                docRoot.appendChild(data);
            }
            data = parser.createElement(doc, AbstractDBO.DATA_NAME);
            parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            for (Entry<String, String> keyAttrEntry : keyAttr.entrySet()) {
                parser.setAttribute(data, keyAttrEntry.getKey(), keyAttrEntry.getValue());
            }
            keyAttr.clear();
            precKey = colKey;
        }
        colKey = null;
        data.appendChild(row);
        rowCounter++;
    }
    if (data != null) {
        docRoot.appendChild(data);
    }

    return rowCounter;
}

From source file:org.exist.xquery.modules.sql.ExecuteFunction.java

/**
 * evaluate the call to the XQuery execute() function, it is really the main entry point of this class.
 *
 * @param   args             arguments from the execute() function call
 * @param   contextSequence  the Context Sequence to operate on (not used here internally!)
 *
 * @return  A node representing the SQL result set
 *
 * @throws  XPathException  DOCUMENT ME!
 *
 * @see     org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 *///from w w w .  jav  a 2s  .c  o  m
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a connection and SQL statement specified?
    if (args[0].isEmpty() || args[1].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    // get the Connection
    long connectionUID = ((IntegerValue) args[0].itemAt(0)).getLong();
    Connection con = SQLModule.retrieveConnection(context, connectionUID);

    if (con == null) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    boolean preparedStmt = false;

    //setup the SQL statement
    String sql = null;
    Statement stmt = null;
    boolean executeResult = false;
    ResultSet rs = null;

    try {
        boolean makeNodeFromColumnName = false;
        MemTreeBuilder builder = context.getDocumentBuilder();
        int iRow = 0;

        //SQL or PreparedStatement?
        if (args.length == 3) {

            // get the SQL statement
            sql = args[1].getStringValue();
            stmt = con.createStatement();
            makeNodeFromColumnName = ((BooleanValue) args[2].itemAt(0)).effectiveBooleanValue();

            //execute the statement
            executeResult = stmt.execute(sql);

        } else if (args.length == 4) {

            preparedStmt = true;

            //get the prepared statement
            long statementUID = ((IntegerValue) args[1].itemAt(0)).getLong();
            PreparedStatementWithSQL stmtWithSQL = SQLModule.retrievePreparedStatement(context, statementUID);
            sql = stmtWithSQL.getSql();
            stmt = stmtWithSQL.getStmt();
            makeNodeFromColumnName = ((BooleanValue) args[3].itemAt(0)).effectiveBooleanValue();

            if (!args[2].isEmpty()) {
                setParametersOnPreparedStatement(stmt, (Element) args[2].itemAt(0));
            }

            //execute the prepared statement
            executeResult = ((PreparedStatement) stmt).execute();
        } else {
            //TODO throw exception
        }

        // DW: stmt can be null ?

        // execute the query statement
        if (executeResult) {
            /* SQL Query returned results */

            // iterate through the result set building an XML document
            rs = stmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            int iColumns = rsmd.getColumnCount();

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("count", null, null), String.valueOf(-1));

            while (rs.next()) {
                builder.startElement(new QName("row", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
                builder.addAttribute(new QName("index", null, null), String.valueOf(rs.getRow()));

                // get each tuple in the row
                for (int i = 0; i < iColumns; i++) {
                    String columnName = rsmd.getColumnLabel(i + 1);

                    if (columnName != null) {

                        String colElement = "field";

                        if (makeNodeFromColumnName && columnName.length() > 0) {
                            // use column names as the XML node

                            /**
                             * Spaces in column names are replaced with
                             * underscore's
                             */
                            colElement = SQLUtils.escapeXmlAttr(columnName.replace(' ', '_'));
                        }

                        builder.startElement(new QName(colElement, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                null);

                        if (!makeNodeFromColumnName || columnName.length() <= 0) {
                            String name;

                            if (columnName.length() > 0) {
                                name = SQLUtils.escapeXmlAttr(columnName);
                            } else {
                                name = "Column: " + String.valueOf(i + 1);
                            }

                            builder.addAttribute(new QName("name", null, null), name);
                        }

                        builder.addAttribute(
                                new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                rsmd.getColumnTypeName(i + 1));
                        builder.addAttribute(new QName(TYPE_ATTRIBUTE_NAME, Namespaces.SCHEMA_NS, "xs"),
                                Type.getTypeName(SQLUtils.sqlTypeToXMLType(rsmd.getColumnType(i + 1))));

                        //get the content
                        if (rsmd.getColumnType(i + 1) == Types.SQLXML) {
                            //parse sqlxml value
                            try {
                                final SQLXML sqlXml = rs.getSQLXML(i + 1);

                                if (rs.wasNull()) {
                                    // Add a null indicator attribute if the value was SQL Null
                                    builder.addAttribute(
                                            new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX),
                                            "true");
                                } else {

                                    SAXParserFactory factory = SAXParserFactory.newInstance();
                                    factory.setNamespaceAware(true);
                                    InputSource src = new InputSource(sqlXml.getCharacterStream());
                                    SAXParser parser = factory.newSAXParser();
                                    XMLReader xr = parser.getXMLReader();

                                    SAXAdapter adapter = new AppendingSAXAdapter(builder);
                                    xr.setContentHandler(adapter);
                                    xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
                                    xr.parse(src);
                                }
                            } catch (Exception e) {
                                throw new XPathException(
                                        "Could not parse column of type SQLXML: " + e.getMessage(), e);
                            }
                        } else {
                            //otherwise assume string value
                            final String colValue = rs.getString(i + 1);

                            if (rs.wasNull()) {
                                // Add a null indicator attribute if the value was SQL Null
                                builder.addAttribute(
                                        new QName("null", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), "true");
                            } else {
                                if (colValue != null) {
                                    builder.characters(SQLUtils.escapeXmlText(colValue));
                                }
                            }
                        }

                        builder.endElement();
                    }
                }

                builder.endElement();
                iRow++;
            }

            builder.endElement();
        } else {
            /* SQL Query performed updates */

            builder.startDocument();

            builder.startElement(new QName("result", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
            builder.addAttribute(new QName("updateCount", null, null), String.valueOf(stmt.getUpdateCount()));
            builder.endElement();
        }

        // Change the root element count attribute to have the correct value
        NodeValue node = (NodeValue) builder.getDocument().getDocumentElement();
        Node count = node.getNode().getAttributes().getNamedItem("count");

        if (count != null) {
            count.setNodeValue(String.valueOf(iRow));
        }

        builder.endDocument();

        // return the XML result set
        return (node);

    } catch (SQLException sqle) {
        LOG.error("sql:execute() Caught SQLException \"" + sqle.getMessage() + "\" for SQL: \"" + sql + "\"",
                sqle);

        //return details about the SQLException
        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("exception", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        boolean recoverable = false;

        if (sqle instanceof SQLRecoverableException) {
            recoverable = true;
        }
        builder.addAttribute(new QName("recoverable", null, null), String.valueOf(recoverable));

        builder.startElement(new QName("state", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(sqle.getSQLState());
        builder.endElement();

        builder.startElement(new QName("message", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

        String state = sqle.getMessage();

        if (state != null) {
            builder.characters(state);
        }

        builder.endElement();

        builder.startElement(new QName("stack-trace", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        ByteArrayOutputStream bufStackTrace = new ByteArrayOutputStream();
        sqle.printStackTrace(new PrintStream(bufStackTrace));
        builder.characters(new String(bufStackTrace.toByteArray()));
        builder.endElement();

        builder.startElement(new QName("sql", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.characters(SQLUtils.escapeXmlText(sql));
        builder.endElement();

        if (stmt instanceof PreparedStatement) {
            Element parametersElement = (Element) args[2].itemAt(0);

            if (parametersElement.getNamespaceURI().equals(SQLModule.NAMESPACE_URI)
                    && parametersElement.getLocalName().equals(PARAMETERS_ELEMENT_NAME)) {
                NodeList paramElements = parametersElement.getElementsByTagNameNS(SQLModule.NAMESPACE_URI,
                        PARAM_ELEMENT_NAME);

                builder.startElement(
                        new QName(PARAMETERS_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                for (int i = 0; i < paramElements.getLength(); i++) {
                    Element param = ((Element) paramElements.item(i));
                    String value = param.getFirstChild().getNodeValue();
                    String type = param.getAttributeNS(SQLModule.NAMESPACE_URI, TYPE_ATTRIBUTE_NAME);

                    builder.startElement(
                            new QName(PARAM_ELEMENT_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);

                    builder.addAttribute(
                            new QName(TYPE_ATTRIBUTE_NAME, SQLModule.NAMESPACE_URI, SQLModule.PREFIX), type);
                    builder.characters(SQLUtils.escapeXmlText(value));

                    builder.endElement();
                }

                builder.endElement();
            }
        }

        builder.startElement(new QName("xquery", SQLModule.NAMESPACE_URI, SQLModule.PREFIX), null);
        builder.addAttribute(new QName("line", null, null), String.valueOf(getLine()));
        builder.addAttribute(new QName("column", null, null), String.valueOf(getColumn()));
        builder.endElement();

        builder.endElement();
        builder.endDocument();

        return ((NodeValue) builder.getDocument().getDocumentElement());
    } finally {

        // close any record set or statement
        if (rs != null) {

            try {
                rs.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            rs = null;
        }

        if (!preparedStmt && stmt != null) {

            try {
                stmt.close();
            } catch (SQLException se) {
                LOG.warn("Unable to cleanup JDBC results", se);
            }
            stmt = null;
        }

    }
}

From source file:com.squid.core.domain.operators.ExtendedType.java

private String getTypeName(int SQLType) {
    switch (SQLType) {
    case Types.ARRAY:
        return "ARRAY";
    case Types.BIGINT:
        return "INTEGER";
    case Types.BINARY:
        return "BINARY";
    case Types.BIT:
        return "BIT";
    case Types.BLOB:
        return "BLOB";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.CHAR:
        return "CHAR";
    case Types.CLOB:
        return "CLOB";
    case Types.DATALINK:
        return "DATALINK";
    case Types.DATE:
        return "DATE";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.FLOAT:
        return "FLOAT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.NULL:
        return "UNDEFINED";//
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.OTHER:
        return "UNDEFINED";//
    case Types.REAL:
        return "REAL";
    case Types.REF:
        return "REF";
    case Types.ROWID:
        return "ROWID";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.SQLXML:
        return "SQLXML";
    case Types.STRUCT:
        return "STRUCT";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.TINYINT:
        return "TINYINT";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.VARCHAR:
        return "VARCHAR";
    default:/*from   w  w  w .j  ava  2s . co  m*/
        return "UNDEFINED";//
    }
}

From source file:org.fastcatsearch.datasource.reader.DBReader.java

private void fill() throws IRException {

    bulkCount = 0;/*from   w  ww .jav  a  2s  . co m*/
    try {
        ResultSetMetaData rsMeta = null;
        //? Tmp ??? .
        deleteTmpLob();

        try {
            rsMeta = r.getMetaData();
        } catch (SQLException e) {
            return;
        }
        while (r.next()) {

            Map<String, Object> keyValueMap = new HashMap<String, Object>();

            for (int i = 0; i < columnCount; i++) {
                int columnIdx = i + 1;
                int type = rsMeta.getColumnType(columnIdx);

                String str = "";

                String lobType = null;
                if (type == Types.BLOB || type == Types.BINARY || type == Types.LONGVARBINARY
                        || type == Types.VARBINARY || type == Types.JAVA_OBJECT) {
                    lobType = LOB_BINARY;
                } else if (type == Types.CLOB || type == Types.NCLOB || type == Types.SQLXML
                        || type == Types.LONGVARCHAR || type == Types.LONGNVARCHAR) {
                    lobType = LOB_STRING;
                }

                if (lobType == null) {
                    str = r.getString(columnIdx);

                    if (str != null) {
                        keyValueMap.put(columnName[i], str);
                    } else {
                        //    ? ? ? NULL ? 
                        keyValueMap.put(columnName[i], "");
                    }
                } else {
                    File file = null;

                    if (lobType == LOB_BINARY) {
                        // logger.debug("Column-"+columnIdx+" is BLOB!");
                        // BLOB?   .
                        ByteArrayOutputStream buffer = null;
                        try {
                            if (!useBlobFile) {
                                buffer = new ByteArrayOutputStream();
                            }
                            file = readTmpBlob(i, columnIdx, rsMeta, buffer);
                            if (useBlobFile) {
                                keyValueMap.put(columnName[i], file);
                            } else {
                                keyValueMap.put(columnName[i], buffer.toByteArray());
                            }
                        } finally {
                            if (buffer != null) {
                                try {
                                    buffer.close();
                                } catch (IOException ignore) {
                                }
                            }
                        }
                    } else if (lobType == LOB_STRING) {
                        StringBuilder sb = null;
                        if (!useBlobFile) {
                            sb = new StringBuilder();
                        }
                        file = readTmpClob(i, columnIdx, rsMeta, sb);
                        if (useBlobFile) {
                            keyValueMap.put(columnName[i], file);
                        } else {
                            keyValueMap.put(columnName[i], sb.toString());
                        }
                    }

                    //?   ?? .
                    if (file != null) {
                        tmpFile.add(file);
                    }
                }
            }

            dataSet[bulkCount] = keyValueMap;
            bulkCount++;
            totalCnt++;

            if (bulkCount >= BULK_SIZE) {
                break;
            }
        }

    } catch (Exception e) {

        logger.debug("", e);

        try {
            if (r != null) {
                r.close();
            }
        } catch (SQLException ignore) {
        }

        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException ignore) {
        }

        try {
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException ignore) {
        }

        throw new IRException(e);
    }
}

From source file:com.squid.core.domain.operators.ExtendedType.java

public static int FromTypeName(String SQLName) {
    if (SQLName.equals("ARRAY")) {
        return Types.ARRAY;
    }//  w  w w  .j a v  a 2  s. c  o m
    if (SQLName.equals("INTEGER")) {
        return Types.INTEGER;
    }
    if (SQLName.equals("BINARY")) {
        return Types.BINARY;
    }
    if (SQLName.equals("BIT")) {
        return Types.BIT;
    }
    if (SQLName.equals("BLOB")) {
        return Types.BLOB;
    }
    if (SQLName.equals("BOOLEAN")) {
        return Types.BOOLEAN;
    }
    if (SQLName.equals("CHAR")) {
        return Types.CHAR;
    }
    if (SQLName.equals("CLOB")) {
        return Types.CLOB;
    }
    if (SQLName.equals("DATALINK")) {
        return Types.DATALINK;
    }
    if (SQLName.equals("DATE")) {
        return Types.DATE;
    }
    if (SQLName.equals("DECIMAL")) {
        return Types.DECIMAL;
    }
    if (SQLName.equals("DOUBLE")) {
        return Types.DOUBLE;
    }
    if (SQLName.equals("FLOAT")) {
        return Types.FLOAT;
    }
    if (SQLName.equals("JAVA_OBJECT")) {
        return Types.JAVA_OBJECT;
    }
    if (SQLName.equals("LONGNVARCHAR")) {
        return Types.LONGNVARCHAR;
    }
    if (SQLName.equals("LONGVARBINARY")) {
        return Types.LONGVARBINARY;
    }
    if (SQLName.equals("NCHAR")) {
        return Types.NCHAR;
    }
    if (SQLName.equals("NCLOB")) {
        return Types.NCLOB;
    }
    if (SQLName.equals("UNDEFINED")) {
        return Types.OTHER;
    }
    if (SQLName.equals("NUMERIC")) {
        return Types.NUMERIC;
    }
    if (SQLName.equals("NVARCHAR")) {
        return Types.NVARCHAR;
    }
    if (SQLName.equals("REAL")) {
        return Types.REAL;
    }
    if (SQLName.equals("REF")) {
        return Types.REF;
    }
    if (SQLName.equals("ROWID")) {
        return Types.ROWID;
    }
    if (SQLName.equals("SMALLINT")) {
        return Types.SMALLINT;
    }
    if (SQLName.equals("SQLXML")) {
        return Types.SQLXML;
    }
    if (SQLName.equals("STRUCT")) {
        return Types.STRUCT;
    }
    if (SQLName.equals("TIME")) {
        return Types.TIME;
    }
    if (SQLName.equals("TIMESTAMP")) {
        return Types.TIMESTAMP;
    }
    if (SQLName.equals("TINYINT")) {
        return Types.TINYINT;
    }
    if (SQLName.equals("VARCHAR")) {
        return Types.VARCHAR;
    }
    if (SQLName.equals("VARBINARY")) {
        return Types.VARBINARY;
    }
    return Types.OTHER;
}

From source file:org.apache.oozie.command.SchemaCheckXCommand.java

private String getSQLTypeFromInt(int t) {
    switch (t) {/*from  w ww  . j  a va2 s  . c  om*/
    case Types.BIT:
        return "BIT";
    case Types.TINYINT:
        return "TINYINT";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.BIGINT:
        return "BIGINT";
    case Types.FLOAT:
        return "FLOAT";
    case Types.REAL:
        return "REAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.CHAR:
        return "CHAR";
    case Types.VARCHAR:
        return "VARCHAR";
    case Types.LONGVARCHAR:
        return "LONGVARCHAR";
    case Types.DATE:
        return "DATE";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.BINARY:
        return "BINARY";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NULL:
        return "NULL";
    case Types.OTHER:
        return "OTHER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.DISTINCT:
        return "DISTINCT";
    case Types.STRUCT:
        return "STRUCT";
    case Types.ARRAY:
        return "ARRAY";
    case Types.BLOB:
        return "BLOB";
    case Types.CLOB:
        return "CLOB";
    case Types.REF:
        return "REF";
    case Types.DATALINK:
        return "DATALINK";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.ROWID:
        return "ROWID";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.SQLXML:
        return "SQLXML";
    default:
        return "unknown";
    }
}