From c7d0fa93d5958f24b47ab0f745140d6c392236aa Mon Sep 17 00:00:00 2001 From: Vitaliy Filippov Date: Wed, 9 Dec 2015 18:18:29 +0300 Subject: [PATCH] Fix \r --- .../databasebc/JDBCClusterManager.java | 2 +- .../openesb/databasebc/JDBCDenormalizer.java | 2552 +++++----- .../openesb/databasebc/JDBCNormalizer.java | 3292 ++++++------ .../databasebc/OutboundMessageProcessor.java | 4522 ++++++++--------- 4 files changed, 5184 insertions(+), 5184 deletions(-) diff --git a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCClusterManager.java b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCClusterManager.java index 4f00535c8..ea4381eaf 100644 --- a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCClusterManager.java +++ b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCClusterManager.java @@ -509,7 +509,7 @@ public class JDBCClusterManager { int rowsUpdated = ps.executeUpdate(); recordInserted = true; } catch (final Exception e) { - mLogger.log(Level.WARNING, e.getLocalizedMessage()); + mLogger.log(Level.WARNING, e.getLocalizedMessage()); mLogger.log(Level.INFO, mMessages.getString("DBBC-R10903.JCM_RECORD_LOCKED", new Object[]{getInstanceName()})); recordInserted = false; }finally{ diff --git a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCDenormalizer.java b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCDenormalizer.java index af693ddf7..382931a72 100644 --- a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCDenormalizer.java +++ b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCDenormalizer.java @@ -1,1276 +1,1276 @@ -/* - * BEGIN_HEADER - DO NOT EDIT - * - * The contents of this file are subject to the terms - * of the Common Development and Distribution License - * (the "License"). You may not use this file except - * in compliance with the License. - * - * You can obtain a copy of the license at - * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. - * See the License for the specific language governing - * permissions and limitations under the License. - * - * When distributing Covered Code, include this CDDL - * HEADER in each file and include the License file at - * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. - * If applicable add the following below this CDDL HEADER, - * with the fields enclosed by brackets "[]" replaced with - * your own identifying information: Portions Copyright - * [year] [name of copyright owner] - */ - -/* - * @(#)JDBCDenormalizer.java - * - * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. - * - * END_HEADER - DO NOT EDIT - */ -package org.glassfish.openesb.databasebc; - -import java.io.StringWriter; -import java.sql.CallableStatement; -import java.sql.DatabaseMetaData; -import java.sql.ParameterMetaData; -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -import org.glassfish.openesb.databasebc.model.metadata.DBMetaData; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.jbi.messaging.MessagingException; -import javax.jbi.messaging.NormalizedMessage; -import javax.wsdl.Input; -import javax.wsdl.Message; -import javax.wsdl.Operation; -import javax.wsdl.Part; -import javax.xml.namespace.QName; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMResult; -import javax.xml.transform.stream.StreamResult; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import com.ibm.wsdl.util.xml.DOMUtils; -import com.sun.jbi.internationalization.Messages; -import org.glassfish.openesb.databasebc.extensions.JDBCOperationInput; -import com.sun.jbi.nms.wsdl11wrapper.HelperFactory; -import com.sun.jbi.nms.wsdl11wrapper.WrapperParser; -import java.io.InputStream; -import java.io.Reader; -import java.util.Scanner; -import javax.xml.transform.stream.StreamSource; -import org.glassfish.openesb.databasebc.extensions.SPOperationInput; -import org.glassfish.openesb.databasebc.util.CachedQueryParameter; -import org.glassfish.openesb.databasebc.util.ParamMetadataCache; - -/** - * - * JDBCDenormalizer - * - */ -public class JDBCDenormalizer { - - private static final Messages mMessages = Messages.getMessages( - JDBCDenormalizer.class); - private static final Logger mLogger = Messages.getLogger( - JDBCDenormalizer.class); - private String dbName = null; - private String catalog = null; - private ArrayList outParamIndex = new ArrayList(); - private HashMap outParamTypes = - new HashMap(); - private HashMap outParamNames = - new HashMap(); - private HashMap mColNamesTypes = - new HashMap(); - private String mRecordPrefix = null; //113494 - private String driverName_; - - /** - * - * @param normalizedMessage - * @param opMetaData - * @param ps - * @throws MessagingException - */ - protected void denormalizeOutbound(final NormalizedMessage normalizedMessage, - String dbName, final OperationMetaData opMetaData, final PreparedStatement ps) - throws MessagingException { - if (opMetaData != null) { - final JDBCOperationInput mJdbcOperationInput = opMetaData. - getJDBCOperationInput(); - final String operationType = mJdbcOperationInput.getOperationType(); - mColNamesTypes = mJdbcOperationInput.getColNamesTypes(); - //if (JDBCUtil.opList.contains(operationType)) { - try { - Element element = - transformMessage(normalizedMessage, opMetaData); - if (element != null) - populatePreparedStatement(element, dbName, opMetaData, ps); - } catch (final SQLException ex) { - final String msg = - JDBCDenormalizer.mMessages.getString( - "DBBC_E00709.JDBCDN_FailedPopulate_PS") + - "Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. - getSQLState() + " ErrorCode:" + ex.getErrorCode(); - throw new MessagingException(msg, ex); - } catch (final Exception ex) { - final String msg = JDBCDenormalizer.mMessages.getString( - "DBBC_E00709.JDBCDN_FailedPopulate_PS") + - "Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } - //} - } - } - - /** - * - * @param normalizedMessage - * @param opMetaData - * @param dbmeta - * @param cs - * @throws MessagingException - */ - protected void denormalizeOutboundProc(final NormalizedMessage normalizedMessage, - final OperationMetaData opMetaData, final DatabaseMetaData dbmeta, final CallableStatement cs) - throws MessagingException { - if (opMetaData != null) { - final SPOperationInput mJdbcOperationInput = opMetaData. - getJDBCSPOperationInput(); - final String operationType = mJdbcOperationInput.getOperationType(); - - try { - Element element = - transformMessage(normalizedMessage, opMetaData); - if (element != null) - populateProcedure(element, opMetaData, dbmeta, cs); - } catch (final SQLException ex) { - final String msg = - JDBCDenormalizer.mMessages.getString( - "DBBC_E00711.DN_FailedPopulate_Proc") + - "Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. - getSQLState() + " ErrorCode:" + ex.getErrorCode(); - throw new MessagingException(msg, ex); - } catch (final Throwable th) { - final String msg = JDBCDenormalizer.mMessages.getString( - "DBBC_E00712.DN_Failed_Proc") + "Reason: " + th. - getLocalizedMessage(); - throw new MessagingException(msg, th); - } - } - } - - /** - * - * @param tableElem - * @param opMetaData - * @param cs - * @throws SQLException - * @throws MessagingException - * @throws Exception - */ - @SuppressWarnings("empty-statement") - private void populateProcedure(final Element tableElem, - final OperationMetaData opMetaData, final DatabaseMetaData dbmeta, CallableStatement cs) - throws SQLException, MessagingException, Exception { - final SPOperationInput jdbcSql = opMetaData.getJDBCSPOperationInput(); - driverName_ = dbmeta.getDriverName(); - String sqltext = jdbcSql.getExecutionString(); - String procName = getProcName(sqltext); - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - String pcatalog = null; - String pschema = null; - if (dbName != null) - pschema = dbName; - if (catalog != null) - pcatalog = catalog; - ResultSet rs = null; - if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.INFO, JDBCDenormalizer.mMessages.getString( - "DBBC_R00716.JDBCDN_StartPopulateProc")); - if (jdbcSql != null) { - final String dbURL = dbmeta.getURL(); - ParamMetadataCache paramsCache = ParamMetadataCache.instance(); - ArrayList params = paramsCache.getMetadata( - dbURL, opMetaData); - - if (params == null) { - try { - final String dbms = dbmeta.getDatabaseProductName(). - toLowerCase(); - final String colNamePattern = - ((dbms.contains("sql server") || dbms.contains( - "adaptive server")) && sqltext.contains("=")) ? null : "%"; - - rs = dbmeta.getProcedureColumns(pcatalog, pschema, procName, - colNamePattern); - } catch (final SQLException ex) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.SEVERE, JDBCDenormalizer.mMessages.getString( - "DBBC_R00721.JDBCDN_UnableToProcessMedataData"), - ex); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.SEVERE, JDBCDenormalizer.mMessages.getString( - "DBBC_R00721.JDBCDN_UnableToProcessMedataData")); - } - - if (rs != null) - params = cacheQueryParameters(rs); - else { - final String msg = JDBCDenormalizer.mMessages.getString( - "DBBC_R00721.JDBCDN_UnableToProcessMedataData"); - MessagingException me = new MessagingException(msg); - mLogger.log(Level.SEVERE, msg); - throw me; - } - - try { - rs.close(); - } catch (SQLException e) { - mLogger.log(Level.WARNING, - JDBCDenormalizer.mMessages.getString( - "DBBC_R00727.JDBCDN_CursorLeak") + procName); - } - paramsCache.storeMetadata(dbURL, opMetaData, params); - } - - - for (int i = 0; i < params.size(); ++i) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - JDBCDenormalizer.mMessages.getString( - "DBBC_R00719.JDBCDN_ProcessColumn")); - CachedQueryParameter param = params.get(i); - String columnName = param.getName(); - // strip off "@" in front of columnName - // In case if it is function, for RETURN parameter coulumnName will be null. - if (columnName != null && columnName.charAt(0) == '@') - columnName = columnName.substring(1); - - int targetSqlType = param.getType(); - int colType = param.getDirection(); - String type_Name = param.getTypeName(); - short numericScale = param.getPrecision(); - - final int columnNumber = i + 1; - if (colType == DatabaseMetaData.procedureColumnIn) { - if ((targetSqlType == 1111) && (type_Name.equals( - "PL/SQL TABLE"))) - targetSqlType = -14; - - if ((targetSqlType == 1111) && (type_Name.equals( - "PL/SQL RECORD"))) - targetSqlType = -14; - - if ((targetSqlType == 1111) && (type_Name.equals("CLOB"))) - targetSqlType = 2005; - - if ((targetSqlType == 1111) && (type_Name.equals("NVARCHAR2"))) - targetSqlType = 12; - final Element columnElem = findMatchingColumnElement( - columnName, - tableElem, mRecordPrefix); //113494 - - if (columnElem != null) { - final String value = DOMUtils.getChildCharacterData( - columnElem); - String isNull = ""; - try { - isNull = columnElem.getAttribute("isNull"); - } catch (Exception e) { - mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( - "DBBC_R00722.JDBCDN_IsNullNotSet")); - } - if (((value != null) && !value.trim().equals("")) || (!isNull. - equalsIgnoreCase("true"))) - if (dbmeta.getDriverName().toLowerCase().contains( - "oracle") && targetSqlType == java.sql.Types.BLOB) - cs.setBinaryStream(columnNumber, - (java.io.ByteArrayInputStream) JDBCUtil.convert(value, - targetSqlType, cs.getConnection()), value.length()); - else if (dbmeta.getDriverName().toLowerCase(). - contains("oracle") && targetSqlType == java.sql.Types.CLOB) - cs.setCharacterStream(columnNumber, - (java.io.StringReader) JDBCUtil.convert( - value, targetSqlType, cs.getConnection()), - value.length()); - else - cs.setObject(columnNumber, - JDBCUtil.convert(value, targetSqlType, - cs.getConnection()), targetSqlType); - else - cs.setNull(columnNumber, targetSqlType); - }//end of if - }//end of if - - if (colType == DatabaseMetaData.procedureColumnInOut || colType == DatabaseMetaData.procedureColumnOut) - try { - // if the parameter is a cursor type, add its index to the arraylist - if ((targetSqlType == 1111) && (type_Name.equals( - "REF CURSOR"))) { - targetSqlType = -10; - cs.registerOutParameter(columnNumber, targetSqlType); - } else if ((targetSqlType == 1111) && (type_Name.equals("CLOB"))) { - targetSqlType = 2005; - cs.registerOutParameter(columnNumber, targetSqlType, - type_Name); - } else if (dbmeta.getDatabaseProductName(). - toLowerCase().contains("oracle")) - cs.registerOutParameter(columnNumber, targetSqlType); - else - cs.registerOutParameter(columnNumber, targetSqlType, - type_Name); - outParamIndex.add(Integer.valueOf(Double.valueOf( - columnNumber).intValue())); - outParamTypes.put(columnNumber, type_Name); - outParamNames.put(columnNumber, columnName); - } catch (SQLException e) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.WARNING, e.getLocalizedMessage(), - e); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, e.getLocalizedMessage()); - throw e; - } - - // check if the parameter is RETURN type (i.e. it is a function) - if (colType == DatabaseMetaData.procedureColumnReturn) - try { - // if the parameter is a cursor type, add its index to the arraylist - if ((targetSqlType == 1111) && (type_Name.equals( - "REF CURSOR"))) { - targetSqlType = -10; - cs.registerOutParameter(columnNumber, targetSqlType); - } else if ((dbmeta.getDatabaseProductName(). - toLowerCase().contains("sql server") || - dbmeta.getDatabaseProductName(). - toLowerCase().contains("adaptive server")) && - columnName.equals("RETURN_VALUE")) - cs.registerOutParameter(columnNumber, targetSqlType, - type_Name); - else - cs.registerOutParameter(columnNumber, targetSqlType, - numericScale); - - outParamIndex.add(Integer.valueOf(Double.valueOf( - columnNumber).intValue())); - outParamTypes.put(columnNumber, type_Name); - //columnName will be null for RETURN type. However DB BC wizard puts it as param1. - //So hardcoding it so that normalizes return value. - if (columnName == null) - columnName = "param1"; - outParamNames.put(columnNumber, columnName); - } catch (SQLException e) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.WARNING, e.getLocalizedMessage(), - e); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, e.getLocalizedMessage()); - throw e; - } - - //i++; - if (mLogger.isLoggable(Level.FINEST)) { - mLogger.log(Level.FINEST, - JDBCDenormalizer.mMessages.getString( - "DBBC_R00717.JDBCDN_ColumnName") + " == " + columnName); - mLogger.log(Level.FINEST, - JDBCDenormalizer.mMessages.getString( - "DBBC_R00718.JDBCDN_ColumnType") + " == " + type_Name); - } - - }//end of While - } - } - - /** - * - * @param tableElem - * @param opMetaData - * @param ps - * @throws SQLException - * @throws MessagingException - * @throws Exception - */ - private void populatePreparedStatement(final Element tableElem, String dbName, - final OperationMetaData opMetaData, final PreparedStatement ps) - throws SQLException, MessagingException, Exception { - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - DatabaseMetaData dbMeta = ps.getConnection().getMetaData(); - - final JDBCOperationInput jdbcSql = opMetaData.getJDBCSql(); - - /** - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - * - * When generatedKey is specified, parameterMetaData's count includes the generatedKey's parameter also. - * So we need to reduce the param count value by 1 so that it matches the number of columns specified in paramOrder. - * This is applicable only for Oracle. - */ - String generatedKey = jdbcSql.getGeneratedKey(); - boolean isOracle = dbMeta.getDriverName().toLowerCase().contains( - "oracle"); - boolean reduceParamCountFromParamMetaData = false; - if (generatedKey != null && !generatedKey.equals("") && isOracle) - reduceParamCountFromParamMetaData = true; - /* Logicoy - changes ends here */ - - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( - "DBBC_R00720.JDBCDN_StartPopulatePS")); - - if (jdbcSql != null) { - - //113494 start - mRecordPrefix = opMetaData.getJDBCSql().getTableName(); - // see if the table name is null (SQL SE) - // then take the query name as the prefix - if (mRecordPrefix == null) { - mRecordPrefix = opMetaData.getJDBCOperationOutput().getName(); - mRecordPrefix = mRecordPrefix.substring(0, - mRecordPrefix.indexOf("Response")); - } - -//113494 end - ArrayList paramsList = - ParamMetadataCache.instance().getMetadata(dbMeta.getURL(), - opMetaData); - if (paramsList == null) { - ParameterMetaData paramMetaData = null; - try { - paramMetaData = ps.getParameterMetaData(); - } catch (final SQLException ex) { - mLogger.log(Level.WARNING, ex.getLocalizedMessage()); - } - - if (paramMetaData != null) { - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - /** - * Modified by Logicoy. - * When generatedKey is specified, parameterMetaData's count includes the generatedKey's parameter also. - * So we need to reduce the param count value by 1 so that it matches the number of columns specified in paramOrder. - * This is applicable only for Oracle. - */ - int parameters = paramMetaData.getParameterCount(); - - if (reduceParamCountFromParamMetaData) - parameters = parameters - 1; - - - if (parameters > 0) {// If there are no parameter we do not need to set anything /* Logicoy - changes ends here */ - // on Prepared statement - String paramOrder = jdbcSql.getParamOrder(); - - // changed for SQLSE since the user cannot enter param - // ordering in sqlprojects. - // we should generate a default param ordering. - if (paramOrder == null || paramOrder.trim().equals("")) - paramOrder = getDefaultParameterOrderString( - parameters); - - final List columns = extractColumns(paramOrder); - - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - JDBCDenormalizer.mMessages.getString( - "DBBC_R00722.JDBCDN_TotalColumns") + columns.size()); - - paramsList = - cacheQueryParameters(columns, paramMetaData, - reduceParamCountFromParamMetaData); - - } else - paramsList = cacheEmptyQueryParams(); - - ParamMetadataCache.instance().storeMetadata(dbMeta.getURL(), - opMetaData, paramsList); - } - } - if (paramsList != null) - for (int i = 0; i < paramsList.size(); i++) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( - "DBBC_R00724.JDBCDN_ProcessParam")); - - CachedQueryParameter param = paramsList.get(i); - final String columnName = param.getName(); - final int columnNumber = i + 1; - final Element columnElement = findMatchingColumnElement( - columnName, tableElem, mRecordPrefix); //113494 Issue - - if (columnElement != null) { - final String value = DOMUtils.getChildCharacterData( - columnElement); - String isNull = ""; - String isDefaultColumn = ""; - try { - isNull = columnElement.getAttribute("isNull"); - } catch (Exception e) { - mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( - "DBBC_R00722.JDBCDN_IsNullNotSet")); - } - - try { - isDefaultColumn = columnElement.getAttribute( - "isDefaultColumn"); - } catch (Exception e) { - mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( - "DBBC_R00723.JDBCDN_IsDefaultNotSet")); - } - /* - * Modified by Logicoy Inc., - * Open ESB Bug No: 107 - Throws error during insert when any of the parameter has empty value - * The below condition checks if value is not empty, not isNull and not isDefault. Changed the OR condition (BUG) to AND condition - * - */ - if ((((value != null) && !value.trim().equals("")) && (!isNull.equalsIgnoreCase("true"))) && - (((value != null) && !value.trim().equals("")) && (!isDefaultColumn.equalsIgnoreCase("true")))) { - /* - * Logiocy Inc., - * Bug 107 - changes ends here - */ - int columnType = param.getType(); - if (ps.getConnection().getMetaData().getDriverName(). - toLowerCase().contains("oracle") && columnType == java.sql.Types.BLOB) - ps.setBinaryStream(columnNumber, - (java.io.ByteArrayInputStream) JDBCUtil.convert(value, - columnType, ps.getConnection()), value.length()); - else if (ps.getConnection().getMetaData(). - getDriverName().toLowerCase().contains( - "oracle") && columnType == java.sql.Types.CLOB) - ps.setCharacterStream(columnNumber, - (java.io.StringReader) JDBCUtil.convert( - value, columnType, ps.getConnection()), - value.length()); - else - ps.setObject(columnNumber, JDBCUtil.convert( - value, columnType, ps.getConnection()), - columnType); - - if (mLogger.isLoggable(Level.FINEST)) { - mLogger.log(Level.FINEST, - mMessages.getString( - "DBBC_R00717.JDBCDN_ColumnName") + " == " + columnName); - mLogger.log(Level.FINEST, - mMessages.getString( - "DBBC_R00726.JDBCDN_ColumnType") + " == " + columnType); - } - - } else { - int columnType = param.getType(); - - if ((!isNull.equalsIgnoreCase("true")) && (isDefaultColumn != null && isDefaultColumn. - equalsIgnoreCase("true"))) { - if (!param.defaultSet()) { - ResultSet rs = ps.getConnection(). - getMetaData().getColumns(null, null, - jdbcSql.getTableName(), "%"); - while (rs.next()) - if (columnName.equalsIgnoreCase(rs.getString("COLUMN_NAME")) && rs. - getString("COLUMN_DEF") != null) - //ps.setObject(columnNumber, JDBCUtil.convert(rs.getString("COLUMN_DEF"), columnType, ps.getConnection()), columnType); - param.setDefault(rs.getString( - "COLUMN_DEF")); - param.setDefault(null); - } - - if (param.hasDefault()) - ps.setObject(columnNumber, JDBCUtil.convert( - param.getDefault(), columnType, ps.getConnection()), - columnType); - else - ps.setNull(columnNumber, columnType); - - } else - ps.setNull(columnNumber, columnType); - - } - - - } - } - else { - final String msg = mMessages.getString( - "DBBC_E00714.JDBCDN_Failed_PS_Param"); - throw new MessagingException(msg); - } - - } - } - - /** - * - * @param dbColumnName - * @param tableElem - * @return - */ - private Element findMatchingColumnElement(final String dbColumnName, - final Element tableElem, String recordPrefix) { // 113494 Issue - Element columnElem = null; - NodeList childNodes = tableElem.getChildNodes(); - - for (int i = 0; i < childNodes.getLength(); i++) { - final Node child = childNodes.item(i); - if ((child instanceof Element) && - child.getLocalName().equalsIgnoreCase( - recordPrefix + "_Record")) { // 113494 Issue - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.FINEST, recordPrefix + "_Record"); - columnElem = (Element) child; - childNodes = columnElem.getChildNodes(); - } - } - for (int i = 0; i < childNodes.getLength(); i++) { - final Node child = childNodes.item(i); - if ((child instanceof Element) && - child.getLocalName().equalsIgnoreCase(dbColumnName)) { - columnElem = (Element) child; - break; - - } - } - - if (null == columnElem) { - //throw new MessagingException(String.format(JDBCDenormalizer.mMessages.getString("DBBC_E00727.JDBCDN_FailedFindColumnElem"), dbColumnName)); - columnElem = - tableElem.getOwnerDocument().createElement(dbColumnName); - columnElem.setAttribute("isNull", "true"); - } - - return columnElem; - } - - /** - * - * @param paramOrder - * @return - */ - private List extractColumns(final String paramOrder) { - final List columnList = new ArrayList(); - - if (paramOrder != null) { - final Scanner tok = new Scanner(paramOrder).useDelimiter( - "\\s*" + "," + "\\s*"); - - while (tok.hasNext()) { - final String column = tok.next(); - columnList.add(column.trim()); - } - - } - - return columnList; - } - - /** - * - * @param parent - * @param msgQName - * @return - */ - private Element findChildElement(final Element parent, - final QName msgQName) { - final String ns = msgQName.getNamespaceURI(); - final String localName = msgQName.getLocalPart(); - NodeList nl = null; - - if ((ns != null) && !ns.trim().equals("")) - nl = parent.getElementsByTagNameNS(ns, localName); - else - nl = parent.getElementsByTagName(localName); - - if ((nl != null) && (nl.getLength() > 0)) { - if (JDBCDenormalizer.mLogger.isLoggable(Level.INFO)) - JDBCDenormalizer.mLogger.log(Level.INFO, "found element"); - - if (JDBCDenormalizer.mLogger.isLoggable(Level.FINEST)) - JDBCDenormalizer.mLogger.log(Level.FINEST, - "found element with name, " + localName); - - final Element e2 = (Element) nl.item(0); - - return e2; - } - - return null; - } - - /** - * - * @param root - * @param elemName - * @return - */ - private Element findPart(final Element root, - final String elemName) { - // parts wrappers never have namespace - final NodeList nl = root.getElementsByTagName(elemName); - - if ((nl != null) && (nl.getLength() > 0)) { - if (JDBCDenormalizer.mLogger.isLoggable(Level.INFO)) - JDBCDenormalizer.mLogger.log(Level.INFO, - "found element with name, " + elemName); - - final Element e2 = (Element) nl.item(0); - - return e2; - } - - return null; - } - - /** - ** Used by SQLSE to get the default parameter ordering. - * @param pmeta - * @return - */ - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - /** - * Modified by Logicoy - * Refactored this method to pass the parameterMetaData's count instead of passing the ParameterMetaDataObject itself - * since we only need the count value. - */ - private String getDefaultParameterOrderString(int numParams) { - String parameterOrderString = null; - //int numParams = 0; - - //if (pmeta != null) { - /*try { - numParams = pmeta.getParameterCount(); - } catch (final SQLException sqle) { - JDBCDenormalizer.mLogger.log(Level.WARNING, - JDBCDenormalizer.mMessages.getString("JDBCDN_Failed_ParamCount")); - - return null; - }*/ - - if (numParams > 0) - for (int i = 1; i <= - numParams; i++) { - final String paramname = "param" + String.valueOf(i); - parameterOrderString = - (parameterOrderString == null) - ? paramname : (parameterOrderString + "," + paramname); - } - //} - - return parameterOrderString; - } -//register out parameters - - private void registerOutParameters(CallableStatement cstmt, final DatabaseMetaData dbmeta) - throws SQLException, NullPointerException { - String errMsg = ""; - int colCount = 0; - boolean isFunction = false; - boolean hasParameters = true; - // indicates if the procedure is within a package or standalone - boolean isPackaged = true; - ArrayList paramIndices = new ArrayList(); - ArrayList result = new ArrayList(); - int paramIndex = 0; - try { - ParameterMetaData pmeta = cstmt.getParameterMetaData(); - if (pmeta != null) { - int numParams = pmeta.getParameterCount(); - if (numParams > 0) - // get info for each parameter - for (int i = 1; i <= - numParams; i++) { - // try to get the sql type info - default to VARCHAR - String sqlType = "VARCHAR"; - try { - sqlType = DBMetaData.getSQLTypeDescription(pmeta.getParameterType( - i)); - } catch (SQLException e) { - mLogger.log(Level.WARNING, - "Could not get SQL Type Description from DBMetadata", - e.getLocalizedMessage()); - } - -// try to get the java type info - default to String - /** - * Changing it to not use metadata class name and instead use the HashMap SQLTOJAVATYPES. - * Without the change the parameter datatypes java.lang.Double and WSDLGenerator look up list - * exepects native type double, float, short etc. - **/ - String javaType = "java.lang.String"; - javaType = - DBMetaData.getJavaFromSQLTypeDescription(sqlType); - -// added abey for Procedure ResultSet - try { - if ((pmeta.getParameterType(i) == java.sql.Types.OTHER) && (pmeta. - getParameterTypeName(i).equalsIgnoreCase( - "REF CURSOR"))) { - sqlType = "RESULTSET"; - javaType = - "java.sql.ResultSet"; - } - - } catch (SQLException e) { - mLogger.log(Level.WARNING, - "Could not get Java type information from DBMetadata", - e.getLocalizedMessage()); - } - -// try to get the param type, default to IN -// always default it since getParameterMode() in data direct 3.3 throws exception -// and 3.4 return UNKNOWN type - String paramType = "IN"; - - try { - paramType = DBMetaData.getPrepStmtParamTypeDescription(pmeta. - getParameterMode((i))); - } catch (SQLException e) { - mLogger.log(Level.WARNING, - "Could not get PreparedStatement Parameter Description", - e.getLocalizedMessage()); - } - -// set defalut type - int sqlTypeCode = java.sql.Types.VARCHAR; - if (paramType.equalsIgnoreCase("INOUT") || paramType. - equalsIgnoreCase("OUT")) - try { - - // if the parameter is a cursor type, add its index to the arraylist - if ((pmeta.getParameterType(i) == 1111) && (paramType.equals( - "OTHER"))) - sqlTypeCode = java.sql.Types.OTHER; - - } catch (SQLException e) { - mLogger.log(Level.WARNING, - "Driver Does not support getting the Datatypes", - e.getLocalizedMessage()); - } - if (paramType.equals("RETURN")) - try { - // if the parameter is a cursor type, add its index to the arraylist - if ((pmeta.getParameterType(i) == 1111) && (paramType.equals( - "OTHER"))) { - //sqlTypeCode = java.sql.Types.OTHER; - } - - } catch (SQLException e) { - mLogger.log(Level.WARNING, - "Driver Does not support getting the Datatypes", - e.getLocalizedMessage()); - } - cstmt.registerOutParameter(paramIndex, sqlTypeCode); - outParamIndex.add(Integer.valueOf(Double.valueOf( - paramIndex).intValue())); - - - } - } - - - - - - } catch (SQLException e) { - mLogger.log(Level.WARNING, "Could not get Parameter MetaData", e); - } - - } - - /* - private String getProcName(String sqlText) { - String proc_name = ""; - String schema = ""; - final Scanner tok = new Scanner(sqlText).useDelimiter("\\s*" + " " + "\\s*"); - - while (tok.hasNext()) { - String column = tok.next(); - int cnt = 0; - column=column.toLowerCase(); - if(column.endsWith("call")){ - cnt++; - proc_name=tok.next(); - if(proc_name.contains(".")){ - final Scanner tok1 = new Scanner(proc_name).useDelimiter("\\s*" + "." + "\\s*"); - schema=tok1.next(); - proc_name=tok1.next(); - } - if(proc_name.contains("(")){ - int i = proc_name.indexOf("("); - proc_name=proc_name.substring(0, i); - } - if(proc_name.contains("}")){ - int i = proc_name.indexOf("}"); - proc_name=proc_name.substring(0, i); - } - } - if(cnt>0) - break; - } - return proc_name; - } - */ - public String getProcName( - String sqlText) { - String proc_name = ""; - String schema = ""; - final StringTokenizer tok = new StringTokenizer(sqlText, " "); - - while (tok.hasMoreElements()) { - String column = (String) tok.nextElement(); - int cnt = 0; - column = - column.toLowerCase(); - if (column.endsWith("call")) { - cnt++; - proc_name = - (String) tok.nextElement(); - if (proc_name.contains(".")) { - //final StringTokenizer tok1 = new StringTokenizer(proc_name, "."); - //catalog = tok1.nextToken(); - //final String beforeDot1 = tok1.nextToken(); - //proc_name = tok1.nextToken(); - String[] procData = proc_name.split("\\."); - final int len = procData.length; - proc_name = - procData[len - 1]; - String catName = null; - String schemaName = null; - if (len == 3) { - catName = procData[0]; - schemaName = - procData[1]; - } else - schemaName = procData[0]; - - if (driverName_.toLowerCase().contains("oracle")) { - catalog = schemaName; - dbName = - catName; - } else { - catalog = catName; - dbName = - schemaName; - } - - } - if (proc_name.contains("(")) { - int i = proc_name.indexOf("("); - proc_name = - proc_name.substring(0, i); - } - - if (proc_name.contains("}")) { - int i = proc_name.indexOf("}"); - proc_name = - proc_name.substring(0, i); - } - - } - if (cnt > 0) - break; - - } - return proc_name; - } - - private final Element transformMessage(final NormalizedMessage normalizedMessage, - final OperationMetaData opMetaData) throws MessagingException { - Element element = null; - try { - final TransformerFactory tFactory = TransformerFactory.newInstance(); - final Transformer trans = tFactory.newTransformer(); - final Source source = normalizedMessage.getContent(); - final DOMResult result = new DOMResult(); - trans.transform(source, result); - - if (source instanceof StreamSource) { - StreamSource stream = (StreamSource) source; - InputStream inputStream = stream.getInputStream(); - if (inputStream != null) - inputStream.reset(); - - Reader reader = stream.getReader(); - if (reader != null) - reader.reset(); - - } - - final Node node = result.getNode(); - final StringWriter strWriter = new StringWriter(); - final StreamResult sResult = new StreamResult(strWriter); - trans.transform(source, sResult); - - if (source instanceof StreamSource) { - StreamSource stream = (StreamSource) source; - InputStream inputStream = stream.getInputStream(); - if (inputStream != null) - inputStream.reset(); - - Reader reader = stream.getReader(); - if (reader != null) - reader.reset(); - - } - if (node != null) { - Document normalDoc = null; - - if (node instanceof Document) - normalDoc = (Document) node; - else - normalDoc = ((Element) node).getOwnerDocument(); - - final Element normalRoot = normalDoc.getDocumentElement(); - //final BindingOperation bindingOperation = opMetaData.getBindingOperation(); - final Operation operation = opMetaData.getOperation(); - final Input input = operation.getInput(); - final Message inputMessage = input.getMessage(); - - if (HelperFactory.WRAPPER_ENABLED) { - final WrapperParser wrapperParser = HelperFactory.createParser(); - wrapperParser.parse(normalDoc, inputMessage); - - final Map parts = inputMessage.getParts(); - final Iterator it = parts.values().iterator(); - - while (it.hasNext()) { - final Part part = (Part) it.next(); - - if (wrapperParser.hasPart(part.getName())) { - final QName elementQName = part.getElementName(); - - if (elementQName == null) { - final String msgEx = JDBCDenormalizer.mMessages.getString( - "DBBC_E00706.DN_Failed_Denormalize") + - part.getName() + - "should have element attribute defined."; - throw new MessagingException(msgEx); - } - -//Element element = null; - final NodeList unwrappedList = wrapperParser.getPartNodes(part. - getName()); - - for (int j = 0; - j < unwrappedList.getLength(); - j++) { - final Node unwrapped = unwrappedList.item(j); - - if ((unwrapped.getNodeType() == Node.ELEMENT_NODE) && - (unwrapped.getLocalName() != null) && - unwrapped.getLocalName().equals(elementQName. - getLocalPart())) { - element = (Element) unwrapped; - - break; - } - } - - /*if (element != null) { - populateProcedure(element, opMetaData, - dbmeta,cs); - //registerOutParameters(cs); - } else { - final String msgEx = JDBCDenormalizer.mMessages.getString( - "JDBCDN_Failed_Finding_Node") + - elementQName.getLocalPart() + - ", in the part wrapper"; - JDBCDenormalizer.mLogger.log(Level.WARNING, msgEx); - throw new MessagingException(msgEx); - }*/ - } - } - } else { - final Element messageElement = normalRoot; - - if (messageElement != null) { - final Map parts = inputMessage.getParts(); - final Iterator it = parts.values().iterator(); - - while (it.hasNext()) { - final Part part = (Part) it.next(); - - final Element partElement = findPart(messageElement, - part.getName()); - - if (partElement != null) { - final QName elementQName = part.getElementName(); - - if (elementQName != null) - element = findChildElement(partElement, - elementQName); - } - } - } - } - } - } catch (final TransformerConfigurationException ex) { - final String msg = JDBCDenormalizer.mMessages.getString( - "DBBC_E00708.DN_Failed_Convert_NM"); - throw new MessagingException(msg, ex); - } catch (final TransformerException ex) { - final String msg = JDBCDenormalizer.mMessages.getString( - "DBBC_E00708.DN_Failed_Convert_NM"); - throw new MessagingException(msg, ex); - } catch (final Throwable th) { - final String msg = JDBCDenormalizer.mMessages.getString( - "DBBC_E00712.DN_Failed_Proc"); - throw new MessagingException(msg, th); - } - return element; - } - - protected void setDatabaseName(String databaseName) { - dbName = databaseName; - } - - protected ArrayList getOutParamIndex() { - return outParamIndex; - } - - protected HashMap getOutParamTypes() { - return outParamTypes; - } - - protected HashMap getOutParamNames() { - return outParamNames; - } - - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - /* - * Modified by Logicoy - * Added reduceParamCountFromParamMetaData - */ - protected ArrayList cacheQueryParameters(List paramNames, ParameterMetaData paramMeta, boolean reduceParamCountFromParamMetaData) throws SQLException { - int size = paramNames.size(); - int paramCount = paramMeta.getParameterCount(); - if (reduceParamCountFromParamMetaData) - paramCount = paramCount - 1; - if (size != paramCount) - return null; - - ArrayList params = - new ArrayList(size); - for (int i = 0; i < size; ++i) { - final int metaIdx = i + 1; - String name = paramNames.get(i); - int type = -1; - try { //Oracle doesn't support this feature. Shame on them! - type = paramMeta.getParameterType(metaIdx); - } catch (SQLException e) { - type = (int) JDBCUtil.builtInTypes.get(mColNamesTypes.get(name)); - } - /*String typeName = null; - try{ // ... and this - typeName = paramMeta.getParameterTypeName(metaIdx); - } - catch(SQLException e){ - } - int direction = paramMeta.getParameterMode(metaIdx); - short precision = (short) paramMeta.getPrecision(metaIdx);*/ - CachedQueryParameter cp = new CachedQueryParameter(name, type); - params.add(cp); - } - - return params; - } - - protected ArrayList cacheEmptyQueryParams() { - return new ArrayList(0); - } - - protected ArrayList cacheQueryParameters(ResultSet paramsInfo) throws SQLException { - if (paramsInfo == null) - return null; - - ArrayList params = - new ArrayList(); - while (paramsInfo.next()) { - String name = paramsInfo.getString("COLUMN_NAME"); - int type = (int) java.sql.Types.VARCHAR; - try { - type = paramsInfo.getInt("DATA_TYPE"); - - } catch (final SQLException e) { - type = (int) JDBCUtil.builtInTypes.get(mColNamesTypes.get(name)); - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. - getLocalizedMessage()); - - } - String typeName = "VARCHAR"; - try { - typeName = paramsInfo.getString("TYPE_NAME"); - } catch (final SQLException e) { - //typeName = JDBCUtil.builtInTypes.get(mColNamesTypes.get(name)); - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. - getLocalizedMessage()); - - } - int direction = Integer.valueOf(ParameterMetaData.parameterModeIn); - try { - direction = paramsInfo.getInt("COLUMN_TYPE"); - } catch (final SQLException e) { - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. - getLocalizedMessage()); - - } - short precision = 0; - try { - precision = paramsInfo.getShort("SCALE"); - } catch (final SQLException e) { - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. - getLocalizedMessage()); - - } - CachedQueryParameter cp = new CachedQueryParameter(name, type, - typeName, direction, precision); - params.add(cp); - } - - return params; - } -} +/* + * BEGIN_HEADER - DO NOT EDIT + * + * The contents of this file are subject to the terms + * of the Common Development and Distribution License + * (the "License"). You may not use this file except + * in compliance with the License. + * + * You can obtain a copy of the license at + * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. + * See the License for the specific language governing + * permissions and limitations under the License. + * + * When distributing Covered Code, include this CDDL + * HEADER in each file and include the License file at + * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. + * If applicable add the following below this CDDL HEADER, + * with the fields enclosed by brackets "[]" replaced with + * your own identifying information: Portions Copyright + * [year] [name of copyright owner] + */ + +/* + * @(#)JDBCDenormalizer.java + * + * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. + * + * END_HEADER - DO NOT EDIT + */ +package org.glassfish.openesb.databasebc; + +import java.io.StringWriter; +import java.sql.CallableStatement; +import java.sql.DatabaseMetaData; +import java.sql.ParameterMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +import org.glassfish.openesb.databasebc.model.metadata.DBMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.jbi.messaging.MessagingException; +import javax.jbi.messaging.NormalizedMessage; +import javax.wsdl.Input; +import javax.wsdl.Message; +import javax.wsdl.Operation; +import javax.wsdl.Part; +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.stream.StreamResult; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import com.ibm.wsdl.util.xml.DOMUtils; +import com.sun.jbi.internationalization.Messages; +import org.glassfish.openesb.databasebc.extensions.JDBCOperationInput; +import com.sun.jbi.nms.wsdl11wrapper.HelperFactory; +import com.sun.jbi.nms.wsdl11wrapper.WrapperParser; +import java.io.InputStream; +import java.io.Reader; +import java.util.Scanner; +import javax.xml.transform.stream.StreamSource; +import org.glassfish.openesb.databasebc.extensions.SPOperationInput; +import org.glassfish.openesb.databasebc.util.CachedQueryParameter; +import org.glassfish.openesb.databasebc.util.ParamMetadataCache; + +/** + * + * JDBCDenormalizer + * + */ +public class JDBCDenormalizer { + + private static final Messages mMessages = Messages.getMessages( + JDBCDenormalizer.class); + private static final Logger mLogger = Messages.getLogger( + JDBCDenormalizer.class); + private String dbName = null; + private String catalog = null; + private ArrayList outParamIndex = new ArrayList(); + private HashMap outParamTypes = + new HashMap(); + private HashMap outParamNames = + new HashMap(); + private HashMap mColNamesTypes = + new HashMap(); + private String mRecordPrefix = null; //113494 + private String driverName_; + + /** + * + * @param normalizedMessage + * @param opMetaData + * @param ps + * @throws MessagingException + */ + protected void denormalizeOutbound(final NormalizedMessage normalizedMessage, + String dbName, final OperationMetaData opMetaData, final PreparedStatement ps) + throws MessagingException { + if (opMetaData != null) { + final JDBCOperationInput mJdbcOperationInput = opMetaData. + getJDBCOperationInput(); + final String operationType = mJdbcOperationInput.getOperationType(); + mColNamesTypes = mJdbcOperationInput.getColNamesTypes(); + //if (JDBCUtil.opList.contains(operationType)) { + try { + Element element = + transformMessage(normalizedMessage, opMetaData); + if (element != null) + populatePreparedStatement(element, dbName, opMetaData, ps); + } catch (final SQLException ex) { + final String msg = + JDBCDenormalizer.mMessages.getString( + "DBBC_E00709.JDBCDN_FailedPopulate_PS") + + "Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. + getSQLState() + " ErrorCode:" + ex.getErrorCode(); + throw new MessagingException(msg, ex); + } catch (final Exception ex) { + final String msg = JDBCDenormalizer.mMessages.getString( + "DBBC_E00709.JDBCDN_FailedPopulate_PS") + + "Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } + //} + } + } + + /** + * + * @param normalizedMessage + * @param opMetaData + * @param dbmeta + * @param cs + * @throws MessagingException + */ + protected void denormalizeOutboundProc(final NormalizedMessage normalizedMessage, + final OperationMetaData opMetaData, final DatabaseMetaData dbmeta, final CallableStatement cs) + throws MessagingException { + if (opMetaData != null) { + final SPOperationInput mJdbcOperationInput = opMetaData. + getJDBCSPOperationInput(); + final String operationType = mJdbcOperationInput.getOperationType(); + + try { + Element element = + transformMessage(normalizedMessage, opMetaData); + if (element != null) + populateProcedure(element, opMetaData, dbmeta, cs); + } catch (final SQLException ex) { + final String msg = + JDBCDenormalizer.mMessages.getString( + "DBBC_E00711.DN_FailedPopulate_Proc") + + "Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. + getSQLState() + " ErrorCode:" + ex.getErrorCode(); + throw new MessagingException(msg, ex); + } catch (final Throwable th) { + final String msg = JDBCDenormalizer.mMessages.getString( + "DBBC_E00712.DN_Failed_Proc") + "Reason: " + th. + getLocalizedMessage(); + throw new MessagingException(msg, th); + } + } + } + + /** + * + * @param tableElem + * @param opMetaData + * @param cs + * @throws SQLException + * @throws MessagingException + * @throws Exception + */ + @SuppressWarnings("empty-statement") + private void populateProcedure(final Element tableElem, + final OperationMetaData opMetaData, final DatabaseMetaData dbmeta, CallableStatement cs) + throws SQLException, MessagingException, Exception { + final SPOperationInput jdbcSql = opMetaData.getJDBCSPOperationInput(); + driverName_ = dbmeta.getDriverName(); + String sqltext = jdbcSql.getExecutionString(); + String procName = getProcName(sqltext); + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + String pcatalog = null; + String pschema = null; + if (dbName != null) + pschema = dbName; + if (catalog != null) + pcatalog = catalog; + ResultSet rs = null; + if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.INFO, JDBCDenormalizer.mMessages.getString( + "DBBC_R00716.JDBCDN_StartPopulateProc")); + if (jdbcSql != null) { + final String dbURL = dbmeta.getURL(); + ParamMetadataCache paramsCache = ParamMetadataCache.instance(); + ArrayList params = paramsCache.getMetadata( + dbURL, opMetaData); + + if (params == null) { + try { + final String dbms = dbmeta.getDatabaseProductName(). + toLowerCase(); + final String colNamePattern = + ((dbms.contains("sql server") || dbms.contains( + "adaptive server")) && sqltext.contains("=")) ? null : "%"; + + rs = dbmeta.getProcedureColumns(pcatalog, pschema, procName, + colNamePattern); + } catch (final SQLException ex) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.SEVERE, JDBCDenormalizer.mMessages.getString( + "DBBC_R00721.JDBCDN_UnableToProcessMedataData"), + ex); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.SEVERE, JDBCDenormalizer.mMessages.getString( + "DBBC_R00721.JDBCDN_UnableToProcessMedataData")); + } + + if (rs != null) + params = cacheQueryParameters(rs); + else { + final String msg = JDBCDenormalizer.mMessages.getString( + "DBBC_R00721.JDBCDN_UnableToProcessMedataData"); + MessagingException me = new MessagingException(msg); + mLogger.log(Level.SEVERE, msg); + throw me; + } + + try { + rs.close(); + } catch (SQLException e) { + mLogger.log(Level.WARNING, + JDBCDenormalizer.mMessages.getString( + "DBBC_R00727.JDBCDN_CursorLeak") + procName); + } + paramsCache.storeMetadata(dbURL, opMetaData, params); + } + + + for (int i = 0; i < params.size(); ++i) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + JDBCDenormalizer.mMessages.getString( + "DBBC_R00719.JDBCDN_ProcessColumn")); + CachedQueryParameter param = params.get(i); + String columnName = param.getName(); + // strip off "@" in front of columnName + // In case if it is function, for RETURN parameter coulumnName will be null. + if (columnName != null && columnName.charAt(0) == '@') + columnName = columnName.substring(1); + + int targetSqlType = param.getType(); + int colType = param.getDirection(); + String type_Name = param.getTypeName(); + short numericScale = param.getPrecision(); + + final int columnNumber = i + 1; + if (colType == DatabaseMetaData.procedureColumnIn) { + if ((targetSqlType == 1111) && (type_Name.equals( + "PL/SQL TABLE"))) + targetSqlType = -14; + + if ((targetSqlType == 1111) && (type_Name.equals( + "PL/SQL RECORD"))) + targetSqlType = -14; + + if ((targetSqlType == 1111) && (type_Name.equals("CLOB"))) + targetSqlType = 2005; + + if ((targetSqlType == 1111) && (type_Name.equals("NVARCHAR2"))) + targetSqlType = 12; + final Element columnElem = findMatchingColumnElement( + columnName, + tableElem, mRecordPrefix); //113494 + + if (columnElem != null) { + final String value = DOMUtils.getChildCharacterData( + columnElem); + String isNull = ""; + try { + isNull = columnElem.getAttribute("isNull"); + } catch (Exception e) { + mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( + "DBBC_R00722.JDBCDN_IsNullNotSet")); + } + if (((value != null) && !value.trim().equals("")) || (!isNull. + equalsIgnoreCase("true"))) + if (dbmeta.getDriverName().toLowerCase().contains( + "oracle") && targetSqlType == java.sql.Types.BLOB) + cs.setBinaryStream(columnNumber, + (java.io.ByteArrayInputStream) JDBCUtil.convert(value, + targetSqlType, cs.getConnection()), value.length()); + else if (dbmeta.getDriverName().toLowerCase(). + contains("oracle") && targetSqlType == java.sql.Types.CLOB) + cs.setCharacterStream(columnNumber, + (java.io.StringReader) JDBCUtil.convert( + value, targetSqlType, cs.getConnection()), + value.length()); + else + cs.setObject(columnNumber, + JDBCUtil.convert(value, targetSqlType, + cs.getConnection()), targetSqlType); + else + cs.setNull(columnNumber, targetSqlType); + }//end of if + }//end of if + + if (colType == DatabaseMetaData.procedureColumnInOut || colType == DatabaseMetaData.procedureColumnOut) + try { + // if the parameter is a cursor type, add its index to the arraylist + if ((targetSqlType == 1111) && (type_Name.equals( + "REF CURSOR"))) { + targetSqlType = -10; + cs.registerOutParameter(columnNumber, targetSqlType); + } else if ((targetSqlType == 1111) && (type_Name.equals("CLOB"))) { + targetSqlType = 2005; + cs.registerOutParameter(columnNumber, targetSqlType, + type_Name); + } else if (dbmeta.getDatabaseProductName(). + toLowerCase().contains("oracle")) + cs.registerOutParameter(columnNumber, targetSqlType); + else + cs.registerOutParameter(columnNumber, targetSqlType, + type_Name); + outParamIndex.add(Integer.valueOf(Double.valueOf( + columnNumber).intValue())); + outParamTypes.put(columnNumber, type_Name); + outParamNames.put(columnNumber, columnName); + } catch (SQLException e) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.WARNING, e.getLocalizedMessage(), + e); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, e.getLocalizedMessage()); + throw e; + } + + // check if the parameter is RETURN type (i.e. it is a function) + if (colType == DatabaseMetaData.procedureColumnReturn) + try { + // if the parameter is a cursor type, add its index to the arraylist + if ((targetSqlType == 1111) && (type_Name.equals( + "REF CURSOR"))) { + targetSqlType = -10; + cs.registerOutParameter(columnNumber, targetSqlType); + } else if ((dbmeta.getDatabaseProductName(). + toLowerCase().contains("sql server") || + dbmeta.getDatabaseProductName(). + toLowerCase().contains("adaptive server")) && + columnName.equals("RETURN_VALUE")) + cs.registerOutParameter(columnNumber, targetSqlType, + type_Name); + else + cs.registerOutParameter(columnNumber, targetSqlType, + numericScale); + + outParamIndex.add(Integer.valueOf(Double.valueOf( + columnNumber).intValue())); + outParamTypes.put(columnNumber, type_Name); + //columnName will be null for RETURN type. However DB BC wizard puts it as param1. + //So hardcoding it so that normalizes return value. + if (columnName == null) + columnName = "param1"; + outParamNames.put(columnNumber, columnName); + } catch (SQLException e) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.WARNING, e.getLocalizedMessage(), + e); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, e.getLocalizedMessage()); + throw e; + } + + //i++; + if (mLogger.isLoggable(Level.FINEST)) { + mLogger.log(Level.FINEST, + JDBCDenormalizer.mMessages.getString( + "DBBC_R00717.JDBCDN_ColumnName") + " == " + columnName); + mLogger.log(Level.FINEST, + JDBCDenormalizer.mMessages.getString( + "DBBC_R00718.JDBCDN_ColumnType") + " == " + type_Name); + } + + }//end of While + } + } + + /** + * + * @param tableElem + * @param opMetaData + * @param ps + * @throws SQLException + * @throws MessagingException + * @throws Exception + */ + private void populatePreparedStatement(final Element tableElem, String dbName, + final OperationMetaData opMetaData, final PreparedStatement ps) + throws SQLException, MessagingException, Exception { + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + DatabaseMetaData dbMeta = ps.getConnection().getMetaData(); + + final JDBCOperationInput jdbcSql = opMetaData.getJDBCSql(); + + /** + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + * + * When generatedKey is specified, parameterMetaData's count includes the generatedKey's parameter also. + * So we need to reduce the param count value by 1 so that it matches the number of columns specified in paramOrder. + * This is applicable only for Oracle. + */ + String generatedKey = jdbcSql.getGeneratedKey(); + boolean isOracle = dbMeta.getDriverName().toLowerCase().contains( + "oracle"); + boolean reduceParamCountFromParamMetaData = false; + if (generatedKey != null && !generatedKey.equals("") && isOracle) + reduceParamCountFromParamMetaData = true; + /* Logicoy - changes ends here */ + + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( + "DBBC_R00720.JDBCDN_StartPopulatePS")); + + if (jdbcSql != null) { + + //113494 start + mRecordPrefix = opMetaData.getJDBCSql().getTableName(); + // see if the table name is null (SQL SE) + // then take the query name as the prefix + if (mRecordPrefix == null) { + mRecordPrefix = opMetaData.getJDBCOperationOutput().getName(); + mRecordPrefix = mRecordPrefix.substring(0, + mRecordPrefix.indexOf("Response")); + } + +//113494 end + ArrayList paramsList = + ParamMetadataCache.instance().getMetadata(dbMeta.getURL(), + opMetaData); + if (paramsList == null) { + ParameterMetaData paramMetaData = null; + try { + paramMetaData = ps.getParameterMetaData(); + } catch (final SQLException ex) { + mLogger.log(Level.WARNING, ex.getLocalizedMessage()); + } + + if (paramMetaData != null) { + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + /** + * Modified by Logicoy. + * When generatedKey is specified, parameterMetaData's count includes the generatedKey's parameter also. + * So we need to reduce the param count value by 1 so that it matches the number of columns specified in paramOrder. + * This is applicable only for Oracle. + */ + int parameters = paramMetaData.getParameterCount(); + + if (reduceParamCountFromParamMetaData) + parameters = parameters - 1; + + + if (parameters > 0) {// If there are no parameter we do not need to set anything /* Logicoy - changes ends here */ + // on Prepared statement + String paramOrder = jdbcSql.getParamOrder(); + + // changed for SQLSE since the user cannot enter param + // ordering in sqlprojects. + // we should generate a default param ordering. + if (paramOrder == null || paramOrder.trim().equals("")) + paramOrder = getDefaultParameterOrderString( + parameters); + + final List columns = extractColumns(paramOrder); + + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + JDBCDenormalizer.mMessages.getString( + "DBBC_R00722.JDBCDN_TotalColumns") + columns.size()); + + paramsList = + cacheQueryParameters(columns, paramMetaData, + reduceParamCountFromParamMetaData); + + } else + paramsList = cacheEmptyQueryParams(); + + ParamMetadataCache.instance().storeMetadata(dbMeta.getURL(), + opMetaData, paramsList); + } + } + if (paramsList != null) + for (int i = 0; i < paramsList.size(); i++) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( + "DBBC_R00724.JDBCDN_ProcessParam")); + + CachedQueryParameter param = paramsList.get(i); + final String columnName = param.getName(); + final int columnNumber = i + 1; + final Element columnElement = findMatchingColumnElement( + columnName, tableElem, mRecordPrefix); //113494 Issue + + if (columnElement != null) { + final String value = DOMUtils.getChildCharacterData( + columnElement); + String isNull = ""; + String isDefaultColumn = ""; + try { + isNull = columnElement.getAttribute("isNull"); + } catch (Exception e) { + mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( + "DBBC_R00722.JDBCDN_IsNullNotSet")); + } + + try { + isDefaultColumn = columnElement.getAttribute( + "isDefaultColumn"); + } catch (Exception e) { + mLogger.log(Level.FINE, JDBCDenormalizer.mMessages.getString( + "DBBC_R00723.JDBCDN_IsDefaultNotSet")); + } + /* + * Modified by Logicoy Inc., + * Open ESB Bug No: 107 - Throws error during insert when any of the parameter has empty value + * The below condition checks if value is not empty, not isNull and not isDefault. Changed the OR condition (BUG) to AND condition + * + */ + if ((((value != null) && !value.trim().equals("")) && (!isNull.equalsIgnoreCase("true"))) && + (((value != null) && !value.trim().equals("")) && (!isDefaultColumn.equalsIgnoreCase("true")))) { + /* + * Logiocy Inc., + * Bug 107 - changes ends here + */ + int columnType = param.getType(); + if (ps.getConnection().getMetaData().getDriverName(). + toLowerCase().contains("oracle") && columnType == java.sql.Types.BLOB) + ps.setBinaryStream(columnNumber, + (java.io.ByteArrayInputStream) JDBCUtil.convert(value, + columnType, ps.getConnection()), value.length()); + else if (ps.getConnection().getMetaData(). + getDriverName().toLowerCase().contains( + "oracle") && columnType == java.sql.Types.CLOB) + ps.setCharacterStream(columnNumber, + (java.io.StringReader) JDBCUtil.convert( + value, columnType, ps.getConnection()), + value.length()); + else + ps.setObject(columnNumber, JDBCUtil.convert( + value, columnType, ps.getConnection()), + columnType); + + if (mLogger.isLoggable(Level.FINEST)) { + mLogger.log(Level.FINEST, + mMessages.getString( + "DBBC_R00717.JDBCDN_ColumnName") + " == " + columnName); + mLogger.log(Level.FINEST, + mMessages.getString( + "DBBC_R00726.JDBCDN_ColumnType") + " == " + columnType); + } + + } else { + int columnType = param.getType(); + + if ((!isNull.equalsIgnoreCase("true")) && (isDefaultColumn != null && isDefaultColumn. + equalsIgnoreCase("true"))) { + if (!param.defaultSet()) { + ResultSet rs = ps.getConnection(). + getMetaData().getColumns(null, null, + jdbcSql.getTableName(), "%"); + while (rs.next()) + if (columnName.equalsIgnoreCase(rs.getString("COLUMN_NAME")) && rs. + getString("COLUMN_DEF") != null) + //ps.setObject(columnNumber, JDBCUtil.convert(rs.getString("COLUMN_DEF"), columnType, ps.getConnection()), columnType); + param.setDefault(rs.getString( + "COLUMN_DEF")); + param.setDefault(null); + } + + if (param.hasDefault()) + ps.setObject(columnNumber, JDBCUtil.convert( + param.getDefault(), columnType, ps.getConnection()), + columnType); + else + ps.setNull(columnNumber, columnType); + + } else + ps.setNull(columnNumber, columnType); + + } + + + } + } + else { + final String msg = mMessages.getString( + "DBBC_E00714.JDBCDN_Failed_PS_Param"); + throw new MessagingException(msg); + } + + } + } + + /** + * + * @param dbColumnName + * @param tableElem + * @return + */ + private Element findMatchingColumnElement(final String dbColumnName, + final Element tableElem, String recordPrefix) { // 113494 Issue + Element columnElem = null; + NodeList childNodes = tableElem.getChildNodes(); + + for (int i = 0; i < childNodes.getLength(); i++) { + final Node child = childNodes.item(i); + if ((child instanceof Element) && + child.getLocalName().equalsIgnoreCase( + recordPrefix + "_Record")) { // 113494 Issue + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.FINEST, recordPrefix + "_Record"); + columnElem = (Element) child; + childNodes = columnElem.getChildNodes(); + } + } + for (int i = 0; i < childNodes.getLength(); i++) { + final Node child = childNodes.item(i); + if ((child instanceof Element) && + child.getLocalName().equalsIgnoreCase(dbColumnName)) { + columnElem = (Element) child; + break; + + } + } + + if (null == columnElem) { + //throw new MessagingException(String.format(JDBCDenormalizer.mMessages.getString("DBBC_E00727.JDBCDN_FailedFindColumnElem"), dbColumnName)); + columnElem = + tableElem.getOwnerDocument().createElement(dbColumnName); + columnElem.setAttribute("isNull", "true"); + } + + return columnElem; + } + + /** + * + * @param paramOrder + * @return + */ + private List extractColumns(final String paramOrder) { + final List columnList = new ArrayList(); + + if (paramOrder != null) { + final Scanner tok = new Scanner(paramOrder).useDelimiter( + "\\s*" + "," + "\\s*"); + + while (tok.hasNext()) { + final String column = tok.next(); + columnList.add(column.trim()); + } + + } + + return columnList; + } + + /** + * + * @param parent + * @param msgQName + * @return + */ + private Element findChildElement(final Element parent, + final QName msgQName) { + final String ns = msgQName.getNamespaceURI(); + final String localName = msgQName.getLocalPart(); + NodeList nl = null; + + if ((ns != null) && !ns.trim().equals("")) + nl = parent.getElementsByTagNameNS(ns, localName); + else + nl = parent.getElementsByTagName(localName); + + if ((nl != null) && (nl.getLength() > 0)) { + if (JDBCDenormalizer.mLogger.isLoggable(Level.INFO)) + JDBCDenormalizer.mLogger.log(Level.INFO, "found element"); + + if (JDBCDenormalizer.mLogger.isLoggable(Level.FINEST)) + JDBCDenormalizer.mLogger.log(Level.FINEST, + "found element with name, " + localName); + + final Element e2 = (Element) nl.item(0); + + return e2; + } + + return null; + } + + /** + * + * @param root + * @param elemName + * @return + */ + private Element findPart(final Element root, + final String elemName) { + // parts wrappers never have namespace + final NodeList nl = root.getElementsByTagName(elemName); + + if ((nl != null) && (nl.getLength() > 0)) { + if (JDBCDenormalizer.mLogger.isLoggable(Level.INFO)) + JDBCDenormalizer.mLogger.log(Level.INFO, + "found element with name, " + elemName); + + final Element e2 = (Element) nl.item(0); + + return e2; + } + + return null; + } + + /** + ** Used by SQLSE to get the default parameter ordering. + * @param pmeta + * @return + */ + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + /** + * Modified by Logicoy + * Refactored this method to pass the parameterMetaData's count instead of passing the ParameterMetaDataObject itself + * since we only need the count value. + */ + private String getDefaultParameterOrderString(int numParams) { + String parameterOrderString = null; + //int numParams = 0; + + //if (pmeta != null) { + /*try { + numParams = pmeta.getParameterCount(); + } catch (final SQLException sqle) { + JDBCDenormalizer.mLogger.log(Level.WARNING, + JDBCDenormalizer.mMessages.getString("JDBCDN_Failed_ParamCount")); + + return null; + }*/ + + if (numParams > 0) + for (int i = 1; i <= + numParams; i++) { + final String paramname = "param" + String.valueOf(i); + parameterOrderString = + (parameterOrderString == null) + ? paramname : (parameterOrderString + "," + paramname); + } + //} + + return parameterOrderString; + } +//register out parameters + + private void registerOutParameters(CallableStatement cstmt, final DatabaseMetaData dbmeta) + throws SQLException, NullPointerException { + String errMsg = ""; + int colCount = 0; + boolean isFunction = false; + boolean hasParameters = true; + // indicates if the procedure is within a package or standalone + boolean isPackaged = true; + ArrayList paramIndices = new ArrayList(); + ArrayList result = new ArrayList(); + int paramIndex = 0; + try { + ParameterMetaData pmeta = cstmt.getParameterMetaData(); + if (pmeta != null) { + int numParams = pmeta.getParameterCount(); + if (numParams > 0) + // get info for each parameter + for (int i = 1; i <= + numParams; i++) { + // try to get the sql type info - default to VARCHAR + String sqlType = "VARCHAR"; + try { + sqlType = DBMetaData.getSQLTypeDescription(pmeta.getParameterType( + i)); + } catch (SQLException e) { + mLogger.log(Level.WARNING, + "Could not get SQL Type Description from DBMetadata", + e.getLocalizedMessage()); + } + +// try to get the java type info - default to String + /** + * Changing it to not use metadata class name and instead use the HashMap SQLTOJAVATYPES. + * Without the change the parameter datatypes java.lang.Double and WSDLGenerator look up list + * exepects native type double, float, short etc. + **/ + String javaType = "java.lang.String"; + javaType = + DBMetaData.getJavaFromSQLTypeDescription(sqlType); + +// added abey for Procedure ResultSet + try { + if ((pmeta.getParameterType(i) == java.sql.Types.OTHER) && (pmeta. + getParameterTypeName(i).equalsIgnoreCase( + "REF CURSOR"))) { + sqlType = "RESULTSET"; + javaType = + "java.sql.ResultSet"; + } + + } catch (SQLException e) { + mLogger.log(Level.WARNING, + "Could not get Java type information from DBMetadata", + e.getLocalizedMessage()); + } + +// try to get the param type, default to IN +// always default it since getParameterMode() in data direct 3.3 throws exception +// and 3.4 return UNKNOWN type + String paramType = "IN"; + + try { + paramType = DBMetaData.getPrepStmtParamTypeDescription(pmeta. + getParameterMode((i))); + } catch (SQLException e) { + mLogger.log(Level.WARNING, + "Could not get PreparedStatement Parameter Description", + e.getLocalizedMessage()); + } + +// set defalut type + int sqlTypeCode = java.sql.Types.VARCHAR; + if (paramType.equalsIgnoreCase("INOUT") || paramType. + equalsIgnoreCase("OUT")) + try { + + // if the parameter is a cursor type, add its index to the arraylist + if ((pmeta.getParameterType(i) == 1111) && (paramType.equals( + "OTHER"))) + sqlTypeCode = java.sql.Types.OTHER; + + } catch (SQLException e) { + mLogger.log(Level.WARNING, + "Driver Does not support getting the Datatypes", + e.getLocalizedMessage()); + } + if (paramType.equals("RETURN")) + try { + // if the parameter is a cursor type, add its index to the arraylist + if ((pmeta.getParameterType(i) == 1111) && (paramType.equals( + "OTHER"))) { + //sqlTypeCode = java.sql.Types.OTHER; + } + + } catch (SQLException e) { + mLogger.log(Level.WARNING, + "Driver Does not support getting the Datatypes", + e.getLocalizedMessage()); + } + cstmt.registerOutParameter(paramIndex, sqlTypeCode); + outParamIndex.add(Integer.valueOf(Double.valueOf( + paramIndex).intValue())); + + + } + } + + + + + + } catch (SQLException e) { + mLogger.log(Level.WARNING, "Could not get Parameter MetaData", e); + } + + } + + /* + private String getProcName(String sqlText) { + String proc_name = ""; + String schema = ""; + final Scanner tok = new Scanner(sqlText).useDelimiter("\\s*" + " " + "\\s*"); + + while (tok.hasNext()) { + String column = tok.next(); + int cnt = 0; + column=column.toLowerCase(); + if(column.endsWith("call")){ + cnt++; + proc_name=tok.next(); + if(proc_name.contains(".")){ + final Scanner tok1 = new Scanner(proc_name).useDelimiter("\\s*" + "." + "\\s*"); + schema=tok1.next(); + proc_name=tok1.next(); + } + if(proc_name.contains("(")){ + int i = proc_name.indexOf("("); + proc_name=proc_name.substring(0, i); + } + if(proc_name.contains("}")){ + int i = proc_name.indexOf("}"); + proc_name=proc_name.substring(0, i); + } + } + if(cnt>0) + break; + } + return proc_name; + } + */ + public String getProcName( + String sqlText) { + String proc_name = ""; + String schema = ""; + final StringTokenizer tok = new StringTokenizer(sqlText, " "); + + while (tok.hasMoreElements()) { + String column = (String) tok.nextElement(); + int cnt = 0; + column = + column.toLowerCase(); + if (column.endsWith("call")) { + cnt++; + proc_name = + (String) tok.nextElement(); + if (proc_name.contains(".")) { + //final StringTokenizer tok1 = new StringTokenizer(proc_name, "."); + //catalog = tok1.nextToken(); + //final String beforeDot1 = tok1.nextToken(); + //proc_name = tok1.nextToken(); + String[] procData = proc_name.split("\\."); + final int len = procData.length; + proc_name = + procData[len - 1]; + String catName = null; + String schemaName = null; + if (len == 3) { + catName = procData[0]; + schemaName = + procData[1]; + } else + schemaName = procData[0]; + + if (driverName_.toLowerCase().contains("oracle")) { + catalog = schemaName; + dbName = + catName; + } else { + catalog = catName; + dbName = + schemaName; + } + + } + if (proc_name.contains("(")) { + int i = proc_name.indexOf("("); + proc_name = + proc_name.substring(0, i); + } + + if (proc_name.contains("}")) { + int i = proc_name.indexOf("}"); + proc_name = + proc_name.substring(0, i); + } + + } + if (cnt > 0) + break; + + } + return proc_name; + } + + private final Element transformMessage(final NormalizedMessage normalizedMessage, + final OperationMetaData opMetaData) throws MessagingException { + Element element = null; + try { + final TransformerFactory tFactory = TransformerFactory.newInstance(); + final Transformer trans = tFactory.newTransformer(); + final Source source = normalizedMessage.getContent(); + final DOMResult result = new DOMResult(); + trans.transform(source, result); + + if (source instanceof StreamSource) { + StreamSource stream = (StreamSource) source; + InputStream inputStream = stream.getInputStream(); + if (inputStream != null) + inputStream.reset(); + + Reader reader = stream.getReader(); + if (reader != null) + reader.reset(); + + } + + final Node node = result.getNode(); + final StringWriter strWriter = new StringWriter(); + final StreamResult sResult = new StreamResult(strWriter); + trans.transform(source, sResult); + + if (source instanceof StreamSource) { + StreamSource stream = (StreamSource) source; + InputStream inputStream = stream.getInputStream(); + if (inputStream != null) + inputStream.reset(); + + Reader reader = stream.getReader(); + if (reader != null) + reader.reset(); + + } + if (node != null) { + Document normalDoc = null; + + if (node instanceof Document) + normalDoc = (Document) node; + else + normalDoc = ((Element) node).getOwnerDocument(); + + final Element normalRoot = normalDoc.getDocumentElement(); + //final BindingOperation bindingOperation = opMetaData.getBindingOperation(); + final Operation operation = opMetaData.getOperation(); + final Input input = operation.getInput(); + final Message inputMessage = input.getMessage(); + + if (HelperFactory.WRAPPER_ENABLED) { + final WrapperParser wrapperParser = HelperFactory.createParser(); + wrapperParser.parse(normalDoc, inputMessage); + + final Map parts = inputMessage.getParts(); + final Iterator it = parts.values().iterator(); + + while (it.hasNext()) { + final Part part = (Part) it.next(); + + if (wrapperParser.hasPart(part.getName())) { + final QName elementQName = part.getElementName(); + + if (elementQName == null) { + final String msgEx = JDBCDenormalizer.mMessages.getString( + "DBBC_E00706.DN_Failed_Denormalize") + + part.getName() + + "should have element attribute defined."; + throw new MessagingException(msgEx); + } + +//Element element = null; + final NodeList unwrappedList = wrapperParser.getPartNodes(part. + getName()); + + for (int j = 0; + j < unwrappedList.getLength(); + j++) { + final Node unwrapped = unwrappedList.item(j); + + if ((unwrapped.getNodeType() == Node.ELEMENT_NODE) && + (unwrapped.getLocalName() != null) && + unwrapped.getLocalName().equals(elementQName. + getLocalPart())) { + element = (Element) unwrapped; + + break; + } + } + + /*if (element != null) { + populateProcedure(element, opMetaData, + dbmeta,cs); + //registerOutParameters(cs); + } else { + final String msgEx = JDBCDenormalizer.mMessages.getString( + "JDBCDN_Failed_Finding_Node") + + elementQName.getLocalPart() + + ", in the part wrapper"; + JDBCDenormalizer.mLogger.log(Level.WARNING, msgEx); + throw new MessagingException(msgEx); + }*/ + } + } + } else { + final Element messageElement = normalRoot; + + if (messageElement != null) { + final Map parts = inputMessage.getParts(); + final Iterator it = parts.values().iterator(); + + while (it.hasNext()) { + final Part part = (Part) it.next(); + + final Element partElement = findPart(messageElement, + part.getName()); + + if (partElement != null) { + final QName elementQName = part.getElementName(); + + if (elementQName != null) + element = findChildElement(partElement, + elementQName); + } + } + } + } + } + } catch (final TransformerConfigurationException ex) { + final String msg = JDBCDenormalizer.mMessages.getString( + "DBBC_E00708.DN_Failed_Convert_NM"); + throw new MessagingException(msg, ex); + } catch (final TransformerException ex) { + final String msg = JDBCDenormalizer.mMessages.getString( + "DBBC_E00708.DN_Failed_Convert_NM"); + throw new MessagingException(msg, ex); + } catch (final Throwable th) { + final String msg = JDBCDenormalizer.mMessages.getString( + "DBBC_E00712.DN_Failed_Proc"); + throw new MessagingException(msg, th); + } + return element; + } + + protected void setDatabaseName(String databaseName) { + dbName = databaseName; + } + + protected ArrayList getOutParamIndex() { + return outParamIndex; + } + + protected HashMap getOutParamTypes() { + return outParamTypes; + } + + protected HashMap getOutParamNames() { + return outParamNames; + } + + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + /* + * Modified by Logicoy + * Added reduceParamCountFromParamMetaData + */ + protected ArrayList cacheQueryParameters(List paramNames, ParameterMetaData paramMeta, boolean reduceParamCountFromParamMetaData) throws SQLException { + int size = paramNames.size(); + int paramCount = paramMeta.getParameterCount(); + if (reduceParamCountFromParamMetaData) + paramCount = paramCount - 1; + if (size != paramCount) + return null; + + ArrayList params = + new ArrayList(size); + for (int i = 0; i < size; ++i) { + final int metaIdx = i + 1; + String name = paramNames.get(i); + int type = -1; + try { //Oracle doesn't support this feature. Shame on them! + type = paramMeta.getParameterType(metaIdx); + } catch (SQLException e) { + type = (int) JDBCUtil.builtInTypes.get(mColNamesTypes.get(name)); + } + /*String typeName = null; + try{ // ... and this + typeName = paramMeta.getParameterTypeName(metaIdx); + } + catch(SQLException e){ + } + int direction = paramMeta.getParameterMode(metaIdx); + short precision = (short) paramMeta.getPrecision(metaIdx);*/ + CachedQueryParameter cp = new CachedQueryParameter(name, type); + params.add(cp); + } + + return params; + } + + protected ArrayList cacheEmptyQueryParams() { + return new ArrayList(0); + } + + protected ArrayList cacheQueryParameters(ResultSet paramsInfo) throws SQLException { + if (paramsInfo == null) + return null; + + ArrayList params = + new ArrayList(); + while (paramsInfo.next()) { + String name = paramsInfo.getString("COLUMN_NAME"); + int type = (int) java.sql.Types.VARCHAR; + try { + type = paramsInfo.getInt("DATA_TYPE"); + + } catch (final SQLException e) { + type = (int) JDBCUtil.builtInTypes.get(mColNamesTypes.get(name)); + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. + getLocalizedMessage()); + + } + String typeName = "VARCHAR"; + try { + typeName = paramsInfo.getString("TYPE_NAME"); + } catch (final SQLException e) { + //typeName = JDBCUtil.builtInTypes.get(mColNamesTypes.get(name)); + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. + getLocalizedMessage()); + + } + int direction = Integer.valueOf(ParameterMetaData.parameterModeIn); + try { + direction = paramsInfo.getInt("COLUMN_TYPE"); + } catch (final SQLException e) { + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. + getLocalizedMessage()); + + } + short precision = 0; + try { + precision = paramsInfo.getShort("SCALE"); + } catch (final SQLException e) { + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_R00723.JDBCDN_DriverNoSupportForMetaData", e. + getLocalizedMessage()); + + } + CachedQueryParameter cp = new CachedQueryParameter(name, type, + typeName, direction, precision); + params.add(cp); + } + + return params; + } +} diff --git a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCNormalizer.java b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCNormalizer.java index 7015cdc9c..d34887c15 100644 --- a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCNormalizer.java +++ b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/JDBCNormalizer.java @@ -1,1663 +1,1663 @@ -/* - * BEGIN_HEADER - DO NOT EDIT - * - * The contents of this file are subject to the terms - * of the Common Development and Distribution License - * (the "License"). You may not use this file except - * in compliance with the License. - * - * You can obtain a copy of the license at - * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. - * See the License for the specific language governing - * permissions and limitations under the License. - * - * When distributing Covered Code, include this CDDL - * HEADER in each file and include the License file at - * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. - * If applicable add the following below this CDDL HEADER, - * with the fields enclosed by brackets "[]" replaced with - * your own identifying information: Portions Copyright - * [year] [name of copyright owner] - */ - -/* - * @(#)JDBCNormalizer.java - * - * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. - * - * END_HEADER - DO NOT EDIT - */ -package org.glassfish.openesb.databasebc; - -import java.io.IOException; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.ParameterMetaData; -import java.sql.CallableStatement; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Connection; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.jbi.messaging.MessageExchange; -import javax.jbi.messaging.MessagingException; -import javax.jbi.messaging.NormalizedMessage; -import javax.wsdl.Input; -import javax.wsdl.Message; -import javax.wsdl.Output; -import javax.wsdl.Part; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.*; -import javax.xml.transform.dom.DOMSource; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Text; -import com.sun.jbi.internationalization.Messages; -import org.glassfish.openesb.databasebc.extensions.JDBCConstants; -import org.glassfish.openesb.databasebc.extensions.JDBCOperationInput; -import org.glassfish.openesb.databasebc.extensions.JDBCOperationOutput; -import com.sun.jbi.nms.wsdl11wrapper.HelperFactory; -import com.sun.jbi.nms.wsdl11wrapper.WrapperBuilder; -import com.sun.jbi.nms.wsdl11wrapper.WrapperProcessingException; -import org.glassfish.openesb.databasebc.extensions.SPOperationOutput; -import org.glassfish.openesb.databasebc.util.XMLCharUtil; -import org.glassfish.openesb.databasebc.util.DebugLog; - -/** - * - * To change the template for this generated type comment go to - * Window - Preferences - Java - Code Generation - Code and Comments - */ -public class JDBCNormalizer { - - private static final Messages mMessages = Messages.getMessages( - JDBCNormalizer.class); - private static final Logger mLogger = Messages.getLogger( - JDBCNormalizer.class); - private static DocumentBuilder mBuilder = null; - private WrapperBuilder wrapperBuilder; - private ArrayList outParamIndex = new ArrayList(); - private HashMap outParamTypes = - new HashMap(); - private HashMap outParamNames = - new HashMap(); - private String mRecordPrefix = null; //113494 - private boolean status; - private Connection connection = null; - private String insertQuery = null; - public ArrayList mProcessedList = new ArrayList(); - public Map mInboundExchangeProcessRecordsMap = new HashMap(); +/* + * BEGIN_HEADER - DO NOT EDIT + * + * The contents of this file are subject to the terms + * of the Common Development and Distribution License + * (the "License"). You may not use this file except + * in compliance with the License. + * + * You can obtain a copy of the license at + * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. + * See the License for the specific language governing + * permissions and limitations under the License. + * + * When distributing Covered Code, include this CDDL + * HEADER in each file and include the License file at + * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. + * If applicable add the following below this CDDL HEADER, + * with the fields enclosed by brackets "[]" replaced with + * your own identifying information: Portions Copyright + * [year] [name of copyright owner] + */ + +/* + * @(#)JDBCNormalizer.java + * + * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. + * + * END_HEADER - DO NOT EDIT + */ +package org.glassfish.openesb.databasebc; + +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.ParameterMetaData; +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.jbi.messaging.MessageExchange; +import javax.jbi.messaging.MessagingException; +import javax.jbi.messaging.NormalizedMessage; +import javax.wsdl.Input; +import javax.wsdl.Message; +import javax.wsdl.Output; +import javax.wsdl.Part; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Text; +import com.sun.jbi.internationalization.Messages; +import org.glassfish.openesb.databasebc.extensions.JDBCConstants; +import org.glassfish.openesb.databasebc.extensions.JDBCOperationInput; +import org.glassfish.openesb.databasebc.extensions.JDBCOperationOutput; +import com.sun.jbi.nms.wsdl11wrapper.HelperFactory; +import com.sun.jbi.nms.wsdl11wrapper.WrapperBuilder; +import com.sun.jbi.nms.wsdl11wrapper.WrapperProcessingException; +import org.glassfish.openesb.databasebc.extensions.SPOperationOutput; +import org.glassfish.openesb.databasebc.util.XMLCharUtil; +import org.glassfish.openesb.databasebc.util.DebugLog; + +/** + * + * To change the template for this generated type comment go to + * Window - Preferences - Java - Code Generation - Code and Comments + */ +public class JDBCNormalizer { + + private static final Messages mMessages = Messages.getMessages( + JDBCNormalizer.class); + private static final Logger mLogger = Messages.getLogger( + JDBCNormalizer.class); + private static DocumentBuilder mBuilder = null; + private WrapperBuilder wrapperBuilder; + private ArrayList outParamIndex = new ArrayList(); + private HashMap outParamTypes = + new HashMap(); + private HashMap outParamNames = + new HashMap(); + private String mRecordPrefix = null; //113494 + private boolean status; + private Connection connection = null; + private String insertQuery = null; + public ArrayList mProcessedList = new ArrayList(); + public Map mInboundExchangeProcessRecordsMap = new HashMap(); public int mRowCount = 0; - private JDBCClusterManager mJDBCClusterManager; - - /** Creates a new instance of SoapNormalizer - * @throws javax.jbi.messaging.MessagingException - */ - public JDBCNormalizer() throws MessagingException { - try { - wrapperBuilder = HelperFactory.createBuilder(); - } catch (final WrapperProcessingException ex) { - throw new MessagingException(JDBCNormalizer.mMessages.getString( - "DBBC_E00701.JDBCN_Failed_Create") + ex.getMessage(), ex); - } - } - - /** - * - * @param rowsUpdated - * @param exchange - * @param meta - * @return - * @throws MessagingException - */ - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - public NormalizedMessage normalize(final String outputValue, - final MessageExchange exchange, final OperationMetaData meta) - throws MessagingException { - final NormalizedMessage normalMsg = exchange.createMessage(); + private JDBCClusterManager mJDBCClusterManager; + + /** Creates a new instance of SoapNormalizer + * @throws javax.jbi.messaging.MessagingException + */ + public JDBCNormalizer() throws MessagingException { + try { + wrapperBuilder = HelperFactory.createBuilder(); + } catch (final WrapperProcessingException ex) { + throw new MessagingException(JDBCNormalizer.mMessages.getString( + "DBBC_E00701.JDBCN_Failed_Create") + ex.getMessage(), ex); + } + } + + /** + * + * @param rowsUpdated + * @param exchange + * @param meta + * @return + * @throws MessagingException + */ + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + public NormalizedMessage normalize(final String outputValue, + final MessageExchange exchange, final OperationMetaData meta) + throws MessagingException { + final NormalizedMessage normalMsg = exchange.createMessage(); mRowCount = 0; - - try { - Document normalDoc = JDBCNormalizer.newDocument(); - String returnPartName = null; - final JDBCOperationOutput jdbcOpOutput = - meta.getJDBCOperationOutput(); - - if (jdbcOpOutput != null) { - returnPartName = jdbcOpOutput.getReturnPartName(); - - if (returnPartName == null) { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + - "missing " + JDBCOperationOutput.ATTR_RETURN_PART_NAME + - " attribute in " + - JDBCConstants.QNAME_OPERATION_OUTPUT; - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + - "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; - throw new MessagingException(msgEx); - } - - if (HelperFactory.WRAPPER_ENABLED) { - String operationOutputName = null; - Message msg = null; - final Output output = meta.getOperation().getOutput(); - - if (output != null) { - operationOutputName = output.getName(); - msg = output.getMessage(); - - if (msg != null) { - wrapperBuilder.initialize(normalDoc, msg, - operationOutputName); - - final Part part = msg.getPart(returnPartName); - - if (part != null) { - final Element returnPartElement = normalDoc.createElement( - returnPartName); - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - final Text text = normalDoc.createTextNode("" + - outputValue); - - final QName type = part.getTypeName(); - { - if (type != null) { - returnPartElement.appendChild(text); - wrapperBuilder.addPart(part.getName(), - returnPartElement); - } else { - final QName element = part.getElementName(); - final Element elementRoot = normalDoc.createElementNS(element. - getNamespaceURI(), element.getLocalPart()); - returnPartElement.appendChild(elementRoot); - - elementRoot.appendChild(text); - wrapperBuilder.addPart(part.getName(), - elementRoot); - } - normalDoc = wrapperBuilder.getResult(); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00703.JDBCN_Failed_NM_Part") + returnPartName + - "in message " + msg.getQName(); - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing message in its "; - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing "; - throw new MessagingException(msgEx); - } - } else { - final String operationName = - meta.getBindingOperation().getName(); - final Element normalRoot = - normalDoc.createElement(operationName); - normalDoc.appendChild(normalRoot); - - if (returnPartName != null) { - final Element returnElement = normalDoc.createElement( - returnPartName); - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - final Text text = normalDoc.createTextNode("" + outputValue); - returnElement.appendChild(text); - normalRoot.appendChild(returnElement); - } - } - - if (JDBCNormalizer.mLogger.isLoggable(Level.INFO)) - JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", - normalDoc); - - normalMsg.setContent(new DOMSource(normalDoc)); - } catch (final ParserConfigurationException tex) { - final String msg = JDBCNormalizer.mMessages.getString( - "DBBC_E00705.JDBCN_Failed_NM_DOM"); - throw new MessagingException(msg, tex); - } catch (final WrapperProcessingException ex) { - final String exMsg = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + ex.getMessage(); - throw new MessagingException(exMsg, ex); - } - - return normalMsg; - } - - /** - * - * @param rs - * @param exchange - * @param meta - * @param epb - * @param pkName - * @return - * @throws MessagingException - * @throws SQLException - * @throws ParserConfigurationException - * @throws TransformerConfigurationException - * @throws TransformerException - */ - public NormalizedMessage normalizeSelectInbound(final ResultSet rs, - final MessageExchange exchange, final OperationMetaData meta, final EndpointBean epb, - final String pkName, final String dbName) - throws MessagingException, SQLException, ParserConfigurationException, - TransformerConfigurationException, TransformerException { - final NormalizedMessage normalMsg = exchange.createMessage(); - - //113494 start - mRecordPrefix = meta.getJDBCSql().getTableName(); - // see if the table name is null (SQL SE) - // then take the query name as the prefix - if (mRecordPrefix == null) { - mRecordPrefix = meta.getJDBCOperationOutput().getName(); - mRecordPrefix = mRecordPrefix.substring(0, mRecordPrefix.indexOf( - "Response")); - } - //113494 end - - try { - Document normalDoc = JDBCNormalizer.newDocument(); - String returnPartName = null; - String NS = ""; - int numberOfRecords = meta.getJDBCOperationInput(). - getNumberOfRecords(); - - - QName elementQName = null; - final JDBCOperationInput jdbcOpInput = meta.getJDBCOperationInput(); - - if (jdbcOpInput == null) { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + - "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; - throw new MessagingException(msgEx); - } - - if (HelperFactory.WRAPPER_ENABLED) { - String operationInputName = null; - Message msg = null; - final Input input = meta.getOperation().getInput(); - - if (input != null) { - operationInputName = input.getName(); - msg = input.getMessage(); - - /* Adding for inbound */ - final Map parts = msg.getParts(); - final Iterator it = parts.values().iterator(); - - while (it.hasNext()) { - final Part part = (Part) it.next(); - elementQName = part.getElementName(); - - if (elementQName == null) { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00703.JDBCN_Failed_NM_Part") + part.getName() + - "should have element attribute defined."; - throw new MessagingException(msgEx); - } - - // } //while - returnPartName = elementQName.getLocalPart(); - - if (returnPartName == null) { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + "missing "// + - // JDBCOperationInput.ATTR_RETURN_PART_NAME - // + " attribute in " - + JDBCConstants.QNAME_OPERATION_INPUT; - throw new MessagingException(msgEx); - } - - /* End of inbound */ - if (msg != null) { - wrapperBuilder.initialize(normalDoc, msg, - operationInputName); - - // Part part = msg.getPart(returnPartName); - if (part != null) { - final Element returnPartElement = normalDoc.createElement( - returnPartName); - final QName type = part.getTypeName(); - { - if (type != null) { - // get resultset metadata rsmd and add it to the element - final ResultSetMetaData rsmd = rs.getMetaData(); - if (numberOfRecords == -1) - while (rs.next()) { + + try { + Document normalDoc = JDBCNormalizer.newDocument(); + String returnPartName = null; + final JDBCOperationOutput jdbcOpOutput = + meta.getJDBCOperationOutput(); + + if (jdbcOpOutput != null) { + returnPartName = jdbcOpOutput.getReturnPartName(); + + if (returnPartName == null) { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + + "missing " + JDBCOperationOutput.ATTR_RETURN_PART_NAME + + " attribute in " + + JDBCConstants.QNAME_OPERATION_OUTPUT; + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + + "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; + throw new MessagingException(msgEx); + } + + if (HelperFactory.WRAPPER_ENABLED) { + String operationOutputName = null; + Message msg = null; + final Output output = meta.getOperation().getOutput(); + + if (output != null) { + operationOutputName = output.getName(); + msg = output.getMessage(); + + if (msg != null) { + wrapperBuilder.initialize(normalDoc, msg, + operationOutputName); + + final Part part = msg.getPart(returnPartName); + + if (part != null) { + final Element returnPartElement = normalDoc.createElement( + returnPartName); + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + final Text text = normalDoc.createTextNode("" + + outputValue); + + final QName type = part.getTypeName(); + { + if (type != null) { + returnPartElement.appendChild(text); + wrapperBuilder.addPart(part.getName(), + returnPartElement); + } else { + final QName element = part.getElementName(); + final Element elementRoot = normalDoc.createElementNS(element. + getNamespaceURI(), element.getLocalPart()); + returnPartElement.appendChild(elementRoot); + + elementRoot.appendChild(text); + wrapperBuilder.addPart(part.getName(), + elementRoot); + } + normalDoc = wrapperBuilder.getResult(); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00703.JDBCN_Failed_NM_Part") + returnPartName + + "in message " + msg.getQName(); + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing message in its "; + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing "; + throw new MessagingException(msgEx); + } + } else { + final String operationName = + meta.getBindingOperation().getName(); + final Element normalRoot = + normalDoc.createElement(operationName); + normalDoc.appendChild(normalRoot); + + if (returnPartName != null) { + final Element returnElement = normalDoc.createElement( + returnPartName); + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + final Text text = normalDoc.createTextNode("" + outputValue); + returnElement.appendChild(text); + normalRoot.appendChild(returnElement); + } + } + + if (JDBCNormalizer.mLogger.isLoggable(Level.INFO)) + JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", + normalDoc); + + normalMsg.setContent(new DOMSource(normalDoc)); + } catch (final ParserConfigurationException tex) { + final String msg = JDBCNormalizer.mMessages.getString( + "DBBC_E00705.JDBCN_Failed_NM_DOM"); + throw new MessagingException(msg, tex); + } catch (final WrapperProcessingException ex) { + final String exMsg = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + ex.getMessage(); + throw new MessagingException(exMsg, ex); + } + + return normalMsg; + } + + /** + * + * @param rs + * @param exchange + * @param meta + * @param epb + * @param pkName + * @return + * @throws MessagingException + * @throws SQLException + * @throws ParserConfigurationException + * @throws TransformerConfigurationException + * @throws TransformerException + */ + public NormalizedMessage normalizeSelectInbound(final ResultSet rs, + final MessageExchange exchange, final OperationMetaData meta, final EndpointBean epb, + final String pkName, final String dbName) + throws MessagingException, SQLException, ParserConfigurationException, + TransformerConfigurationException, TransformerException { + final NormalizedMessage normalMsg = exchange.createMessage(); + + //113494 start + mRecordPrefix = meta.getJDBCSql().getTableName(); + // see if the table name is null (SQL SE) + // then take the query name as the prefix + if (mRecordPrefix == null) { + mRecordPrefix = meta.getJDBCOperationOutput().getName(); + mRecordPrefix = mRecordPrefix.substring(0, mRecordPrefix.indexOf( + "Response")); + } + //113494 end + + try { + Document normalDoc = JDBCNormalizer.newDocument(); + String returnPartName = null; + String NS = ""; + int numberOfRecords = meta.getJDBCOperationInput(). + getNumberOfRecords(); + + + QName elementQName = null; + final JDBCOperationInput jdbcOpInput = meta.getJDBCOperationInput(); + + if (jdbcOpInput == null) { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + + "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; + throw new MessagingException(msgEx); + } + + if (HelperFactory.WRAPPER_ENABLED) { + String operationInputName = null; + Message msg = null; + final Input input = meta.getOperation().getInput(); + + if (input != null) { + operationInputName = input.getName(); + msg = input.getMessage(); + + /* Adding for inbound */ + final Map parts = msg.getParts(); + final Iterator it = parts.values().iterator(); + + while (it.hasNext()) { + final Part part = (Part) it.next(); + elementQName = part.getElementName(); + + if (elementQName == null) { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00703.JDBCN_Failed_NM_Part") + part.getName() + + "should have element attribute defined."; + throw new MessagingException(msgEx); + } + + // } //while + returnPartName = elementQName.getLocalPart(); + + if (returnPartName == null) { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + "missing "// + + // JDBCOperationInput.ATTR_RETURN_PART_NAME + // + " attribute in " + + JDBCConstants.QNAME_OPERATION_INPUT; + throw new MessagingException(msgEx); + } + + /* End of inbound */ + if (msg != null) { + wrapperBuilder.initialize(normalDoc, msg, + operationInputName); + + // Part part = msg.getPart(returnPartName); + if (part != null) { + final Element returnPartElement = normalDoc.createElement( + returnPartName); + final QName type = part.getTypeName(); + { + if (type != null) { + // get resultset metadata rsmd and add it to the element + final ResultSetMetaData rsmd = rs.getMetaData(); + if (numberOfRecords == -1) + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable( - Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = - normalDoc.createElement( - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = rsmd.getColumnName(j); - String colValue = JDBCUtil.convertToString(j, - rs, rsmd, dbName); - - final Element e = normalDoc.createElement( - XMLCharUtil.makeValidNCName( - colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode( - colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - returnPartElement.appendChild( - record); - } - else - while (rs.next() && (numberOfRecords > 0)) { + if (mLogger.isLoggable( + Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = + normalDoc.createElement( + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = rsmd.getColumnName(j); + String colValue = JDBCUtil.convertToString(j, + rs, rsmd, dbName); + + final Element e = normalDoc.createElement( + XMLCharUtil.makeValidNCName( + colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode( + colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + returnPartElement.appendChild( + record); + } + else + while (rs.next() && (numberOfRecords > 0)) { mRowCount++; - if (mLogger.isLoggable( - Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = - normalDoc.createElement( - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = rsmd.getColumnName(j); - String colValue = JDBCUtil.convertToString(j, - rs, rsmd, dbName); - - final Element e = normalDoc.createElement( - XMLCharUtil.makeValidNCName( - colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode( - colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - returnPartElement.appendChild( - record); - numberOfRecords--; - } - wrapperBuilder.addPart(part.getName(), - returnPartElement); - } else { - final QName element = part.getElementName(); - NS = element.getNamespaceURI(); - - final Element elementRoot = normalDoc.createElementNS(NS, - element.getLocalPart()); - - // returnPartElement.appendChild(elementRoot); - // get resultset metadata rsmd and add it to the element - final ResultSetMetaData rsmd = rs.getMetaData(); - final List pKeyList = - new ArrayList(); - - if (numberOfRecords == -1) - while (rs.next()) { + if (mLogger.isLoggable( + Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = + normalDoc.createElement( + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = rsmd.getColumnName(j); + String colValue = JDBCUtil.convertToString(j, + rs, rsmd, dbName); + + final Element e = normalDoc.createElement( + XMLCharUtil.makeValidNCName( + colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode( + colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + returnPartElement.appendChild( + record); + numberOfRecords--; + } + wrapperBuilder.addPart(part.getName(), + returnPartElement); + } else { + final QName element = part.getElementName(); + NS = element.getNamespaceURI(); + + final Element elementRoot = normalDoc.createElementNS(NS, + element.getLocalPart()); + + // returnPartElement.appendChild(elementRoot); + // get resultset metadata rsmd and add it to the element + final ResultSetMetaData rsmd = rs.getMetaData(); + final List pKeyList = + new ArrayList(); + + if (numberOfRecords == -1) + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable( - Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - Element record = - normalDoc.createElementNS(NS, - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = rsmd.getColumnName(j); - String colValue = JDBCUtil.convertToString(j, - rs, rsmd, dbName); - - if (colName.equalsIgnoreCase( - pkName) || ("\"" + colName + "\""). - equalsIgnoreCase( - pkName)) - if (epb.isClustered()) { - boolean inserted = - false; - mJDBCClusterManager.setPKValue( - colValue); - //boolean inserted = isRecordInserted(epb, connection, pkName, colValue); - inserted = - mJDBCClusterManager. - isRecordInsertedByCurrentInstance(); - if (!inserted) - record = null; - else - pKeyList.add( - colValue); - } else { - boolean processed = - isRecordProcessed( - colValue); - if (!processed) - pKeyList.add( - colValue); - else - record = null; - } - if (record != null) { - final Element e = - normalDoc.createElementNS( - NS, XMLCharUtil.makeValidNCName( - colName)); - - if (rs.wasNull()) { - colValue = ""; - e.setAttribute( - "isNull", - "true"); - } else - e.setAttribute( - "isNull", - "false"); - e.appendChild(normalDoc.createTextNode( - colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log( - Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } else - break; - } - if (record != null) - elementRoot.appendChild( - record); - } - else - while (rs.next() && (numberOfRecords > 0)) { + if (mLogger.isLoggable( + Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + Element record = + normalDoc.createElementNS(NS, + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = rsmd.getColumnName(j); + String colValue = JDBCUtil.convertToString(j, + rs, rsmd, dbName); + + if (colName.equalsIgnoreCase( + pkName) || ("\"" + colName + "\""). + equalsIgnoreCase( + pkName)) + if (epb.isClustered()) { + boolean inserted = + false; + mJDBCClusterManager.setPKValue( + colValue); + //boolean inserted = isRecordInserted(epb, connection, pkName, colValue); + inserted = + mJDBCClusterManager. + isRecordInsertedByCurrentInstance(); + if (!inserted) + record = null; + else + pKeyList.add( + colValue); + } else { + boolean processed = + isRecordProcessed( + colValue); + if (!processed) + pKeyList.add( + colValue); + else + record = null; + } + if (record != null) { + final Element e = + normalDoc.createElementNS( + NS, XMLCharUtil.makeValidNCName( + colName)); + + if (rs.wasNull()) { + colValue = ""; + e.setAttribute( + "isNull", + "true"); + } else + e.setAttribute( + "isNull", + "false"); + e.appendChild(normalDoc.createTextNode( + colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log( + Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } else + break; + } + if (record != null) + elementRoot.appendChild( + record); + } + else + while (rs.next() && (numberOfRecords > 0)) { mRowCount++; - if (mLogger.isLoggable( - Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - Element record = - normalDoc.createElementNS(NS, - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = rsmd.getColumnName(j); - String colValue = JDBCUtil.convertToString(j, - rs, rsmd, dbName); - - if (colName.equalsIgnoreCase( - pkName) || ("\"" + colName + "\""). - equalsIgnoreCase( - pkName)) - if (epb.isClustered()) { - boolean inserted = - false; - mJDBCClusterManager.setPKValue( - colValue); - /*List pkDangListValues = mJDBCClusterManager.getDanglingInstancePKList(); - if(!pkDangListValues.isEmpty()){ - // check the pk values is exsits in the list - //if(pkDangListValues.contains(colValue)){ - // It means , the current instance took the owner ship of this records and need to process. - // the PK records are already present in the result so make the inserted is true.and need to remove the pk value - //from the the list to avoid duplicate process. - // if pkDangListValues > numberOfRecords, don't remove them from the list and process in the next poll. - // inserted = true; - // pkDangListValues.remove(colValue); - // }else{ - // inserted = mJDBCClusterManager.isRecordInsertedByCurrentInstance(); - // } - else{*/ - inserted = - mJDBCClusterManager. - isRecordInsertedByCurrentInstance(); - //} - //boolean inserted = isRecordInserted(epb, connection, pkName, colValue); - if (!inserted)// inserted true means, this records is inserted by this instance and need to process.means add it to the pKeyList - record = null; - else - pKeyList.add( - colValue); - } else { - boolean processed = - isRecordProcessed( - colValue); - if (!processed) - pKeyList.add( - colValue); - else - record = null; - } - if (record != null) { - final Element e = - normalDoc.createElementNS( - NS, XMLCharUtil.makeValidNCName( - colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute( - "isNull", - "true"); - } else - e.setAttribute( - "isNull", - "false"); - e.appendChild(normalDoc.createTextNode( - colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log( - Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } else - break; - } - if (record != null) { - elementRoot.appendChild( - record); - numberOfRecords--; - } - } //else - epb.setProcessList(pKeyList); - if (pKeyList.size() != 0) - mInboundExchangeProcessRecordsMap.put(exchange. - getExchangeId(), - pKeyList); - wrapperBuilder.addPart(part.getName(), - elementRoot); - } - normalDoc = wrapperBuilder.getResult(); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00703.JDBCN_Failed_NM_Part") + - returnPartName + "in message " + - msg.getQName(); - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing message in its "; - throw new MessagingException(msgEx); - } - } // while - } // if(input) - else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing "; - throw new MessagingException(msgEx); - } - } else { - final String operationName = - meta.getBindingOperation().getName(); - final Element normalRoot = - normalDoc.createElement(operationName); - normalDoc.appendChild(normalRoot); - - if (returnPartName != null) { - final Element returnElement = normalDoc.createElement( - returnPartName); - - // get resultset metadata rsmd and add it to the element - final ResultSetMetaData rsmd = rs.getMetaData(); - if (numberOfRecords == -1) - while (rs.next()) { + if (mLogger.isLoggable( + Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + Element record = + normalDoc.createElementNS(NS, + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = rsmd.getColumnName(j); + String colValue = JDBCUtil.convertToString(j, + rs, rsmd, dbName); + + if (colName.equalsIgnoreCase( + pkName) || ("\"" + colName + "\""). + equalsIgnoreCase( + pkName)) + if (epb.isClustered()) { + boolean inserted = + false; + mJDBCClusterManager.setPKValue( + colValue); + /*List pkDangListValues = mJDBCClusterManager.getDanglingInstancePKList(); + if(!pkDangListValues.isEmpty()){ + // check the pk values is exsits in the list + //if(pkDangListValues.contains(colValue)){ + // It means , the current instance took the owner ship of this records and need to process. + // the PK records are already present in the result so make the inserted is true.and need to remove the pk value + //from the the list to avoid duplicate process. + // if pkDangListValues > numberOfRecords, don't remove them from the list and process in the next poll. + // inserted = true; + // pkDangListValues.remove(colValue); + // }else{ + // inserted = mJDBCClusterManager.isRecordInsertedByCurrentInstance(); + // } + else{*/ + inserted = + mJDBCClusterManager. + isRecordInsertedByCurrentInstance(); + //} + //boolean inserted = isRecordInserted(epb, connection, pkName, colValue); + if (!inserted)// inserted true means, this records is inserted by this instance and need to process.means add it to the pKeyList + record = null; + else + pKeyList.add( + colValue); + } else { + boolean processed = + isRecordProcessed( + colValue); + if (!processed) + pKeyList.add( + colValue); + else + record = null; + } + if (record != null) { + final Element e = + normalDoc.createElementNS( + NS, XMLCharUtil.makeValidNCName( + colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute( + "isNull", + "true"); + } else + e.setAttribute( + "isNull", + "false"); + e.appendChild(normalDoc.createTextNode( + colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log( + Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } else + break; + } + if (record != null) { + elementRoot.appendChild( + record); + numberOfRecords--; + } + } //else + epb.setProcessList(pKeyList); + if (pKeyList.size() != 0) + mInboundExchangeProcessRecordsMap.put(exchange. + getExchangeId(), + pKeyList); + wrapperBuilder.addPart(part.getName(), + elementRoot); + } + normalDoc = wrapperBuilder.getResult(); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00703.JDBCN_Failed_NM_Part") + + returnPartName + "in message " + + msg.getQName(); + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing message in its "; + throw new MessagingException(msgEx); + } + } // while + } // if(input) + else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing "; + throw new MessagingException(msgEx); + } + } else { + final String operationName = + meta.getBindingOperation().getName(); + final Element normalRoot = + normalDoc.createElement(operationName); + normalDoc.appendChild(normalRoot); + + if (returnPartName != null) { + final Element returnElement = normalDoc.createElement( + returnPartName); + + // get resultset metadata rsmd and add it to the element + final ResultSetMetaData rsmd = rs.getMetaData(); + if (numberOfRecords == -1) + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElement( - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = rsmd.getColumnName(j); - String colValue = - JDBCUtil.convertToString(j, rs, rsmd, - dbName); - - final Element e = normalDoc.createElement( - XMLCharUtil.makeValidNCName(colName)); - - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", "true"); - } else - e.setAttribute("isNull", "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - returnElement.appendChild(record); - } - else - while (rs.next() && (numberOfRecords > 0)) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElement( + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = rsmd.getColumnName(j); + String colValue = + JDBCUtil.convertToString(j, rs, rsmd, + dbName); + + final Element e = normalDoc.createElement( + XMLCharUtil.makeValidNCName(colName)); + + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", "true"); + } else + e.setAttribute("isNull", "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + returnElement.appendChild(record); + } + else + while (rs.next() && (numberOfRecords > 0)) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElement( - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = rsmd.getColumnName(j); - String colValue = - JDBCUtil.convertToString(j, rs, rsmd, - dbName); - final Element e = normalDoc.createElement( - XMLCharUtil.makeValidNCName(colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", "true"); - } else - e.setAttribute("isNull", "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - returnElement.appendChild(record); - numberOfRecords--; - } - normalRoot.appendChild(returnElement); - } - } - - JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", - normalDoc); - if (JDBCNormalizer.mLogger.isLoggable(Level.FINE)) - DebugLog.debugLog(mLogger, Level.INFO, - "***normalizeSelectInbound***", normalDoc); - normalMsg.setContent(new DOMSource(normalDoc)); - } catch (final ParserConfigurationException tex) { - final String msg = JDBCNormalizer.mMessages.getString( - "DBBC_E00705.JDBCN_Failed_NM_DOM"); - throw new MessagingException(msg, tex); - } catch (final WrapperProcessingException ex) { - final String exMsg = JDBCNormalizer.mMessages.getString( - "DBBC_E00703.JDBCN_Failed_NM_Part") + ex.getMessage(); - throw new MessagingException(exMsg, ex); - } catch (final IOException ex) { - final String exMsg = JDBCNormalizer.mMessages.getString( - "DBBC_R00707.JDBCN_Failed_Base64_Encode"); - throw new MessagingException(exMsg, ex); - } - - return normalMsg; - } - - /** - * - * @param rs - * @param exchange - * @param meta - * @return - * @throws MessagingException - * @throws SQLException - * @throws ParserConfigurationException - * @throws TransformerConfigurationException - * @throws TransformerException - */ - public NormalizedMessage normalizeSelect(final ResultSet rs, - final MessageExchange exchange, final OperationMetaData meta, String driverName) - throws MessagingException, SQLException, ParserConfigurationException, - TransformerConfigurationException, TransformerException { - final NormalizedMessage normalMsg = exchange.createMessage(); - - try { - Document normalDoc = JDBCNormalizer.newDocument(); - String returnPartName = null; - String NS = ""; - int numberOfRecords = meta.getJDBCOperationInput(). - getNumberOfRecords(); - final JDBCOperationOutput jdbcOpOutput = - meta.getJDBCOperationOutput(); - //113494 start - mRecordPrefix = meta.getJDBCSql().getTableName(); - // see if the table name is null (SQL SE) - // then take the query name as the prefix - if (mRecordPrefix == null) { - mRecordPrefix = meta.getJDBCOperationOutput().getName(); - mRecordPrefix = mRecordPrefix.substring(0, - mRecordPrefix.indexOf("Response")); - } - //113494 end - - if (jdbcOpOutput != null) { - returnPartName = jdbcOpOutput.getReturnPartName(); - - if (returnPartName == null) { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + - "missing " + JDBCOperationOutput.ATTR_RETURN_PART_NAME + - " attribute in " + - JDBCConstants.QNAME_OPERATION_OUTPUT; - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + - "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; - throw new MessagingException(msgEx); - } - - if (HelperFactory.WRAPPER_ENABLED) { - String operationOutputName = null; - Message msg = null; - final Output output = meta.getOperation().getOutput(); - - if (output != null) { - operationOutputName = output.getName(); - msg = output.getMessage(); - - if (msg != null) { - wrapperBuilder.initialize(normalDoc, msg, - operationOutputName); - - final Part part = msg.getPart(returnPartName); - - if (part != null) { - final Element returnPartElement = normalDoc.createElement( - returnPartName); - final QName type = part.getTypeName(); - { - if (type != null) { - // get resultset metadata rsmd and add it to the - // element - final ResultSetMetaData rsmd = rs.getMetaData(); - String[] validColNames = new String[rsmd.getColumnCount()]; - validColNames = validateColumnNames(rsmd, - validColNames); - - if (numberOfRecords == -1) - while (rs.next()) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElement( + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = rsmd.getColumnName(j); + String colValue = + JDBCUtil.convertToString(j, rs, rsmd, + dbName); + final Element e = normalDoc.createElement( + XMLCharUtil.makeValidNCName(colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", "true"); + } else + e.setAttribute("isNull", "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + returnElement.appendChild(record); + numberOfRecords--; + } + normalRoot.appendChild(returnElement); + } + } + + JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", + normalDoc); + if (JDBCNormalizer.mLogger.isLoggable(Level.FINE)) + DebugLog.debugLog(mLogger, Level.INFO, + "***normalizeSelectInbound***", normalDoc); + normalMsg.setContent(new DOMSource(normalDoc)); + } catch (final ParserConfigurationException tex) { + final String msg = JDBCNormalizer.mMessages.getString( + "DBBC_E00705.JDBCN_Failed_NM_DOM"); + throw new MessagingException(msg, tex); + } catch (final WrapperProcessingException ex) { + final String exMsg = JDBCNormalizer.mMessages.getString( + "DBBC_E00703.JDBCN_Failed_NM_Part") + ex.getMessage(); + throw new MessagingException(exMsg, ex); + } catch (final IOException ex) { + final String exMsg = JDBCNormalizer.mMessages.getString( + "DBBC_R00707.JDBCN_Failed_Base64_Encode"); + throw new MessagingException(exMsg, ex); + } + + return normalMsg; + } + + /** + * + * @param rs + * @param exchange + * @param meta + * @return + * @throws MessagingException + * @throws SQLException + * @throws ParserConfigurationException + * @throws TransformerConfigurationException + * @throws TransformerException + */ + public NormalizedMessage normalizeSelect(final ResultSet rs, + final MessageExchange exchange, final OperationMetaData meta, String driverName) + throws MessagingException, SQLException, ParserConfigurationException, + TransformerConfigurationException, TransformerException { + final NormalizedMessage normalMsg = exchange.createMessage(); + + try { + Document normalDoc = JDBCNormalizer.newDocument(); + String returnPartName = null; + String NS = ""; + int numberOfRecords = meta.getJDBCOperationInput(). + getNumberOfRecords(); + final JDBCOperationOutput jdbcOpOutput = + meta.getJDBCOperationOutput(); + //113494 start + mRecordPrefix = meta.getJDBCSql().getTableName(); + // see if the table name is null (SQL SE) + // then take the query name as the prefix + if (mRecordPrefix == null) { + mRecordPrefix = meta.getJDBCOperationOutput().getName(); + mRecordPrefix = mRecordPrefix.substring(0, + mRecordPrefix.indexOf("Response")); + } + //113494 end + + if (jdbcOpOutput != null) { + returnPartName = jdbcOpOutput.getReturnPartName(); + + if (returnPartName == null) { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + + "missing " + JDBCOperationOutput.ATTR_RETURN_PART_NAME + + " attribute in " + + JDBCConstants.QNAME_OPERATION_OUTPUT; + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + + "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; + throw new MessagingException(msgEx); + } + + if (HelperFactory.WRAPPER_ENABLED) { + String operationOutputName = null; + Message msg = null; + final Output output = meta.getOperation().getOutput(); + + if (output != null) { + operationOutputName = output.getName(); + msg = output.getMessage(); + + if (msg != null) { + wrapperBuilder.initialize(normalDoc, msg, + operationOutputName); + + final Part part = msg.getPart(returnPartName); + + if (part != null) { + final Element returnPartElement = normalDoc.createElement( + returnPartName); + final QName type = part.getTypeName(); + { + if (type != null) { + // get resultset metadata rsmd and add it to the + // element + final ResultSetMetaData rsmd = rs.getMetaData(); + String[] validColNames = new String[rsmd.getColumnCount()]; + validColNames = validateColumnNames(rsmd, + validColNames); + + if (numberOfRecords == -1) + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElement( - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = - validColNames[j - 1]; - String colValue = JDBCUtil.convertToString(j, rs, - rsmd, driverName); - final Element e = - normalDoc.createElement(XMLCharUtil. - makeValidNCName(colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - returnPartElement.appendChild(record); - } - else - while (rs.next() && (numberOfRecords > 0)) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElement( + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = + validColNames[j - 1]; + String colValue = JDBCUtil.convertToString(j, rs, + rsmd, driverName); + final Element e = + normalDoc.createElement(XMLCharUtil. + makeValidNCName(colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + returnPartElement.appendChild(record); + } + else + while (rs.next() && (numberOfRecords > 0)) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElement( - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = - validColNames[j - 1]; - String colValue = JDBCUtil.convertToString(j, rs, - rsmd, driverName); - final Element e = - normalDoc.createElement(XMLCharUtil. - makeValidNCName(colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - returnPartElement.appendChild(record); - numberOfRecords--; - } - - wrapperBuilder.addPart(part.getName(), - returnPartElement); - } else { - final QName element = part.getElementName(); - NS = element.getNamespaceURI(); - - final Element elementRoot = normalDoc.createElementNS(NS, - element.getLocalPart()); - - // returnPartElement.appendChild(elementRoot); - // get resultset metadata rsmd and add it to the element - final ResultSetMetaData rsmd = rs.getMetaData(); - String[] validColNames = new String[rsmd.getColumnCount()]; - validColNames = validateColumnNames(rsmd, - validColNames); - - if (numberOfRecords == -1) - while (rs.next()) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElement( + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = + validColNames[j - 1]; + String colValue = JDBCUtil.convertToString(j, rs, + rsmd, driverName); + final Element e = + normalDoc.createElement(XMLCharUtil. + makeValidNCName(colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + returnPartElement.appendChild(record); + numberOfRecords--; + } + + wrapperBuilder.addPart(part.getName(), + returnPartElement); + } else { + final QName element = part.getElementName(); + NS = element.getNamespaceURI(); + + final Element elementRoot = normalDoc.createElementNS(NS, + element.getLocalPart()); + + // returnPartElement.appendChild(elementRoot); + // get resultset metadata rsmd and add it to the element + final ResultSetMetaData rsmd = rs.getMetaData(); + String[] validColNames = new String[rsmd.getColumnCount()]; + validColNames = validateColumnNames(rsmd, + validColNames); + + if (numberOfRecords == -1) + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElementNS(NS, - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = - validColNames[j - 1]; - String colValue = JDBCUtil.convertToString(j, rs, - rsmd, driverName); - - - final Element e = - normalDoc.createElementNS(NS, - XMLCharUtil.makeValidNCName(colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - elementRoot.appendChild(record); - } - else - while (rs.next() && (numberOfRecords > 0)) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElementNS(NS, + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = + validColNames[j - 1]; + String colValue = JDBCUtil.convertToString(j, rs, + rsmd, driverName); + + + final Element e = + normalDoc.createElementNS(NS, + XMLCharUtil.makeValidNCName(colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + elementRoot.appendChild(record); + } + else + while (rs.next() && (numberOfRecords > 0)) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElementNS(NS, - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = - validColNames[j - 1]; - String colValue = JDBCUtil.convertToString(j, rs, - rsmd, driverName); - - - final Element e = - normalDoc.createElementNS(NS, - XMLCharUtil.makeValidNCName(colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - - } - elementRoot.appendChild(record); - numberOfRecords--; - } - - wrapperBuilder.addPart(part.getName(), - elementRoot); - } - normalDoc = wrapperBuilder.getResult(); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00703.JDBCN_Failed_NM_Part") + returnPartName + - "in message " + msg.getQName(); - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing message in its "; - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing "; - throw new MessagingException(msgEx); - } - } else { - final String operationName = - meta.getBindingOperation().getName(); - final Element normalRoot = - normalDoc.createElement(operationName); - normalDoc.appendChild(normalRoot); - - if (returnPartName != null) { - final Element returnElement = normalDoc.createElement( - returnPartName); - - // get resultset metadata rsmd and add it to the element - final ResultSetMetaData rsmd = rs.getMetaData(); - String[] validColNames = new String[rsmd.getColumnCount()]; - validColNames = validateColumnNames(rsmd, validColNames); - - if (numberOfRecords == -1) - while (rs.next()) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElementNS(NS, + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = + validColNames[j - 1]; + String colValue = JDBCUtil.convertToString(j, rs, + rsmd, driverName); + + + final Element e = + normalDoc.createElementNS(NS, + XMLCharUtil.makeValidNCName(colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + + } + elementRoot.appendChild(record); + numberOfRecords--; + } + + wrapperBuilder.addPart(part.getName(), + elementRoot); + } + normalDoc = wrapperBuilder.getResult(); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00703.JDBCN_Failed_NM_Part") + returnPartName + + "in message " + msg.getQName(); + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing message in its "; + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing "; + throw new MessagingException(msgEx); + } + } else { + final String operationName = + meta.getBindingOperation().getName(); + final Element normalRoot = + normalDoc.createElement(operationName); + normalDoc.appendChild(normalRoot); + + if (returnPartName != null) { + final Element returnElement = normalDoc.createElement( + returnPartName); + + // get resultset metadata rsmd and add it to the element + final ResultSetMetaData rsmd = rs.getMetaData(); + String[] validColNames = new String[rsmd.getColumnCount()]; + validColNames = validateColumnNames(rsmd, validColNames); + + if (numberOfRecords == -1) + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElement( - mRecordPrefix + "_Record"); //113494 - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = validColNames[j - 1]; - String colValue = - JDBCUtil.convertToString(j, rs, rsmd, - driverName); - - final Element e = normalDoc.createElement( - XMLCharUtil.makeValidNCName(colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", "true"); - } else - e.setAttribute("isNull", "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - returnElement.appendChild(record); - } - else - while (rs.next() && (numberOfRecords > 0)) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElement( + mRecordPrefix + "_Record"); //113494 + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = validColNames[j - 1]; + String colValue = + JDBCUtil.convertToString(j, rs, rsmd, + driverName); + + final Element e = normalDoc.createElement( + XMLCharUtil.makeValidNCName(colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", "true"); + } else + e.setAttribute("isNull", "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + returnElement.appendChild(record); + } + else + while (rs.next() && (numberOfRecords > 0)) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - final Element record = normalDoc.createElement( - "record"); - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = validColNames[j - 1]; - String colValue = - JDBCUtil.convertToString(j, rs, rsmd, - driverName); - - final Element e = normalDoc.createElement( - XMLCharUtil.makeValidNCName(colName)); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", "true"); - } else - e.setAttribute("isNull", "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - record.appendChild(e); - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - - } - returnElement.appendChild(record); - numberOfRecords--; - } - - normalRoot.appendChild(returnElement); - } - } - - if (JDBCNormalizer.mLogger.isLoggable(Level.INFO)) - JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", - normalDoc); - - normalMsg.setContent(new DOMSource(normalDoc)); - } catch (final ParserConfigurationException tex) { - final String msg = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER"); - throw new MessagingException(msg, tex); - } catch (final WrapperProcessingException ex) { - final String exMsg = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + ex.getMessage(); - throw new MessagingException(exMsg, ex); - } catch (final IOException ex) { - final String exMsg = JDBCNormalizer.mMessages.getString( - "DBBC_R00707.JDBCN_Failed_Base64_Encode"); - throw new MessagingException(exMsg, ex); - } - - return normalMsg; - } - - /** - * @param cs - * @param exchange - * @param meta - * @return - * @throws MessagingException - * @throws SQLException - * @throws ParserConfigurationException - * @throws TransformerConfigurationException - * @throws TransformerException - */ - public NormalizedMessage normalizeProcedure(final CallableStatement cs, - final MessageExchange exchange, final OperationMetaData meta, final String dbName) - throws MessagingException, SQLException, ParserConfigurationException, - TransformerConfigurationException, TransformerException { - final NormalizedMessage normalMsg = exchange.createMessage(); - - try { - Document normalDoc = JDBCNormalizer.newDocument(); - String returnPartName = null; - String NS = ""; - final SPOperationOutput jdbcOpOutput = - meta.getJDBCSPOperationOutput(); - if (jdbcOpOutput != null) { - returnPartName = jdbcOpOutput.getReturnPartName(); - - if (returnPartName == null) { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + - "missing " + JDBCOperationOutput.ATTR_RETURN_PART_NAME + - " attribute in " + - JDBCConstants.QNAME_OPERATION_OUTPUT; - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + - "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; - throw new MessagingException(msgEx); - } - - if (HelperFactory.WRAPPER_ENABLED) { - String operationOutputName = null; - Message msg = null; - final Output output = meta.getOperation().getOutput(); - - if (output != null) { - operationOutputName = output.getName(); - msg = output.getMessage(); - - if (msg != null) { - wrapperBuilder.initialize(normalDoc, msg, - operationOutputName); - - final Part part = msg.getPart(returnPartName); - - if (part != null) { - final Element returnPartElement = normalDoc.createElement( - returnPartName); - final QName type = part.getTypeName(); - { - if (type != null) { - // get resultset metadata rsmd and add it to the - // element - for (int i = 0; i < outParamIndex.size(); i++) { - int paramIndex = - (Integer) outParamIndex.get(i); - String paramType = outParamTypes.get( - paramIndex); - String paramName = outParamNames.get( - paramIndex); - ResultSet rs = null; - try { - if (paramType.equalsIgnoreCase( - "REF CURSOR") || paramType.equalsIgnoreCase( - "RESULTSET")) { - if (dbName.trim().contains( - "sql server") || dbName.trim().contains( - "adaptive server")) - rs = (ResultSet) cs.getResultSet(); - else - rs = - (ResultSet) cs.getObject(paramIndex); - if (rs != null) { - final ResultSetMetaData rsmd = - rs.getMetaData(); - while (rs.next()) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + final Element record = normalDoc.createElement( + "record"); + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = validColNames[j - 1]; + String colValue = + JDBCUtil.convertToString(j, rs, rsmd, + driverName); + + final Element e = normalDoc.createElement( + XMLCharUtil.makeValidNCName(colName)); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", "true"); + } else + e.setAttribute("isNull", "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + record.appendChild(e); + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + + } + returnElement.appendChild(record); + numberOfRecords--; + } + + normalRoot.appendChild(returnElement); + } + } + + if (JDBCNormalizer.mLogger.isLoggable(Level.INFO)) + JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", + normalDoc); + + normalMsg.setContent(new DOMSource(normalDoc)); + } catch (final ParserConfigurationException tex) { + final String msg = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER"); + throw new MessagingException(msg, tex); + } catch (final WrapperProcessingException ex) { + final String exMsg = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + ex.getMessage(); + throw new MessagingException(exMsg, ex); + } catch (final IOException ex) { + final String exMsg = JDBCNormalizer.mMessages.getString( + "DBBC_R00707.JDBCN_Failed_Base64_Encode"); + throw new MessagingException(exMsg, ex); + } + + return normalMsg; + } + + /** + * @param cs + * @param exchange + * @param meta + * @return + * @throws MessagingException + * @throws SQLException + * @throws ParserConfigurationException + * @throws TransformerConfigurationException + * @throws TransformerException + */ + public NormalizedMessage normalizeProcedure(final CallableStatement cs, + final MessageExchange exchange, final OperationMetaData meta, final String dbName) + throws MessagingException, SQLException, ParserConfigurationException, + TransformerConfigurationException, TransformerException { + final NormalizedMessage normalMsg = exchange.createMessage(); + + try { + Document normalDoc = JDBCNormalizer.newDocument(); + String returnPartName = null; + String NS = ""; + final SPOperationOutput jdbcOpOutput = + meta.getJDBCSPOperationOutput(); + if (jdbcOpOutput != null) { + returnPartName = jdbcOpOutput.getReturnPartName(); + + if (returnPartName == null) { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + + "missing " + JDBCOperationOutput.ATTR_RETURN_PART_NAME + + " attribute in " + + JDBCConstants.QNAME_OPERATION_OUTPUT; + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + + "missing " + JDBCConstants.QNAME_OPERATION_OUTPUT; + throw new MessagingException(msgEx); + } + + if (HelperFactory.WRAPPER_ENABLED) { + String operationOutputName = null; + Message msg = null; + final Output output = meta.getOperation().getOutput(); + + if (output != null) { + operationOutputName = output.getName(); + msg = output.getMessage(); + + if (msg != null) { + wrapperBuilder.initialize(normalDoc, msg, + operationOutputName); + + final Part part = msg.getPart(returnPartName); + + if (part != null) { + final Element returnPartElement = normalDoc.createElement( + returnPartName); + final QName type = part.getTypeName(); + { + if (type != null) { + // get resultset metadata rsmd and add it to the + // element + for (int i = 0; i < outParamIndex.size(); i++) { + int paramIndex = + (Integer) outParamIndex.get(i); + String paramType = outParamTypes.get( + paramIndex); + String paramName = outParamNames.get( + paramIndex); + ResultSet rs = null; + try { + if (paramType.equalsIgnoreCase( + "REF CURSOR") || paramType.equalsIgnoreCase( + "RESULTSET")) { + if (dbName.trim().contains( + "sql server") || dbName.trim().contains( + "adaptive server")) + rs = (ResultSet) cs.getResultSet(); + else + rs = + (ResultSet) cs.getObject(paramIndex); + if (rs != null) { + final ResultSetMetaData rsmd = + rs.getMetaData(); + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable( - Level.FINE)) - mLogger.log( - Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - Element paramElem = - normalDoc.createElement( - paramName + "_0_Resultset"); - returnPartElement.appendChild( - paramElem); - - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = - rsmd.getColumnName( - j); - String colValue = - JDBCUtil.convertToString( - j, rs, rsmd, - dbName); - final Element e = - normalDoc.createElement( - colName); - - if (rs.wasNull()) { - colValue = ""; - e.setAttribute( - "isNull", - "true"); - } else - e.setAttribute( - "isNull", - "false"); - e.appendChild(normalDoc.createTextNode( - colValue)); - paramElem.appendChild( - e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log( - Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - } - } - } else { - Object paramValue = null; - if (paramType.equalsIgnoreCase( - "CLOB")) { - java.sql.Clob clob = - (java.sql.Clob) cs.getObject(paramIndex); - if (clob != null) - paramValue = clob.getSubString(1, - (int) clob.length()); - } else if (paramType.equalsIgnoreCase("BLOB")) { - java.sql.Blob blob = - (java.sql.Blob) cs.getObject(paramIndex); - if (blob != null) - paramValue = new String( - blob.getBytes(1, - (int) blob.length())); - } else - paramValue = cs.getObject( - paramIndex); - final Element e = normalDoc.createElement(paramName); - if (paramValue == null) { - paramValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode(paramValue. - toString())); - returnPartElement.appendChild(e); - } - } catch (SQLException sqle) { - throw sqle; - } finally { - if (rs != null) - try { - rs.close(); - } catch (SQLException e) { - /* Ignore... */ ; - } - } - - } - wrapperBuilder.addPart(part.getName(), - returnPartElement); - } else { - final QName element = part.getElementName(); - NS = element.getNamespaceURI(); - - final Element elementRoot = normalDoc.createElementNS(NS, - element.getLocalPart()); - - // returnPartElement.appendChild(elementRoot); - // get resultset metadata rsmd and add it to the element - for (int i = 0; i < outParamIndex.size(); i++) { - int paramIndex = - (Integer) outParamIndex.get(i); - String paramType = outParamTypes.get( - paramIndex); - String paramName = outParamNames.get( - paramIndex); - ResultSet rs = null; - try { - if (paramType.equalsIgnoreCase( - "REF CURSOR") || paramType.equalsIgnoreCase( - "RESULTSET")) { - if (dbName.trim().contains( - "sql server") || dbName.trim().contains( - "adaptive server")) - rs = (ResultSet) cs.getResultSet(); - else - rs = - (ResultSet) cs.getObject(paramIndex); - if (rs != null) { - final ResultSetMetaData rsmd = - rs.getMetaData(); - while (rs.next()) { + if (mLogger.isLoggable( + Level.FINE)) + mLogger.log( + Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + Element paramElem = + normalDoc.createElement( + paramName + "_0_Resultset"); + returnPartElement.appendChild( + paramElem); + + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = + rsmd.getColumnName( + j); + String colValue = + JDBCUtil.convertToString( + j, rs, rsmd, + dbName); + final Element e = + normalDoc.createElement( + colName); + + if (rs.wasNull()) { + colValue = ""; + e.setAttribute( + "isNull", + "true"); + } else + e.setAttribute( + "isNull", + "false"); + e.appendChild(normalDoc.createTextNode( + colValue)); + paramElem.appendChild( + e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log( + Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + } + } + } else { + Object paramValue = null; + if (paramType.equalsIgnoreCase( + "CLOB")) { + java.sql.Clob clob = + (java.sql.Clob) cs.getObject(paramIndex); + if (clob != null) + paramValue = clob.getSubString(1, + (int) clob.length()); + } else if (paramType.equalsIgnoreCase("BLOB")) { + java.sql.Blob blob = + (java.sql.Blob) cs.getObject(paramIndex); + if (blob != null) + paramValue = new String( + blob.getBytes(1, + (int) blob.length())); + } else + paramValue = cs.getObject( + paramIndex); + final Element e = normalDoc.createElement(paramName); + if (paramValue == null) { + paramValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode(paramValue. + toString())); + returnPartElement.appendChild(e); + } + } catch (SQLException sqle) { + throw sqle; + } finally { + if (rs != null) + try { + rs.close(); + } catch (SQLException e) { + /* Ignore... */ ; + } + } + + } + wrapperBuilder.addPart(part.getName(), + returnPartElement); + } else { + final QName element = part.getElementName(); + NS = element.getNamespaceURI(); + + final Element elementRoot = normalDoc.createElementNS(NS, + element.getLocalPart()); + + // returnPartElement.appendChild(elementRoot); + // get resultset metadata rsmd and add it to the element + for (int i = 0; i < outParamIndex.size(); i++) { + int paramIndex = + (Integer) outParamIndex.get(i); + String paramType = outParamTypes.get( + paramIndex); + String paramName = outParamNames.get( + paramIndex); + ResultSet rs = null; + try { + if (paramType.equalsIgnoreCase( + "REF CURSOR") || paramType.equalsIgnoreCase( + "RESULTSET")) { + if (dbName.trim().contains( + "sql server") || dbName.trim().contains( + "adaptive server")) + rs = (ResultSet) cs.getResultSet(); + else + rs = + (ResultSet) cs.getObject(paramIndex); + if (rs != null) { + final ResultSetMetaData rsmd = + rs.getMetaData(); + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable( - Level.FINE)) - mLogger.log( - Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - Element paramElem = - normalDoc.createElementNS( - NS, - paramName + "_0_Resultset"); - elementRoot.appendChild( - paramElem); - - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = - rsmd.getColumnName( - j); - String colValue = - JDBCUtil.convertToString( - j, rs, rsmd, - dbName); - final Element e = - normalDoc.createElementNS( - NS, colName); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute( - "isNull", - "true"); - } else - e.setAttribute( - "isNull", - "false"); - e.appendChild(normalDoc.createTextNode( - colValue)); - paramElem.appendChild( - e); - if (mLogger.isLoggable( - Level.FINEST)) - mLogger.log( - Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - } - } - } else { - Object paramValue = null; - if (paramType.equalsIgnoreCase( - "CLOB")) { - java.sql.Clob clob = - (java.sql.Clob) cs.getObject(paramIndex); - if (clob != null) - paramValue = clob.getSubString(1, - (int) clob.length()); - } else if (paramType.equalsIgnoreCase("BLOB")) { - java.sql.Blob blob = - (java.sql.Blob) cs.getObject(paramIndex); - if (blob != null) - paramValue = new String( - blob.getBytes(1, - (int) blob.length())); - } else - paramValue = cs.getObject( - paramIndex); - final Element e = normalDoc.createElementNS(NS, - paramName); - if (paramValue == null) { - paramValue = ""; - e.setAttribute("isNull", - "true"); - } else - e.setAttribute("isNull", - "false"); - e.appendChild(normalDoc.createTextNode(paramValue. - toString())); - elementRoot.appendChild(e); - } - } catch (SQLException sqle) { - throw sqle; - } finally { - if (rs != null) - try { - rs.close(); - } catch (SQLException e) { - /* Ignore... */ ; - } - } - } - wrapperBuilder.addPart(part.getName(), - elementRoot); - } - normalDoc = wrapperBuilder.getResult(); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00703.JDBCN_Failed_NM_Part") + returnPartName + - "in message " + msg.getQName(); - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing message in its "; - throw new MessagingException(msgEx); - } - } else { - final String msgEx = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + - meta.getOperation().getName() + - " is missing "; - throw new MessagingException(msgEx); - } - } else { - final String operationName = - meta.getBindingOperation().getName(); - final Element normalRoot = - normalDoc.createElement(operationName); - normalDoc.appendChild(normalRoot); - - if (returnPartName != null) { - final Element returnElement = normalDoc.createElement( - returnPartName); - - // get resultset metadata rsmd and add it to the element - for (int i = 0; i < outParamIndex.size(); i++) { - int paramIndex = (Integer) outParamIndex.get(i); - String paramType = outParamTypes.get(paramIndex); - String paramName = outParamNames.get(paramIndex); - ResultSet rs = null; - try { - if (paramType.equalsIgnoreCase("REF CURSOR") || paramType. - equalsIgnoreCase("RESULTSET")) { - if (dbName.trim().contains("sql server") || dbName.trim(). - contains("adaptive server")) - rs = (ResultSet) cs.getResultSet(); - else - rs = (ResultSet) cs.getObject(paramIndex); - if (rs != null) { - final ResultSetMetaData rsmd = rs.getMetaData(); - while (rs.next()) { + if (mLogger.isLoggable( + Level.FINE)) + mLogger.log( + Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + Element paramElem = + normalDoc.createElementNS( + NS, + paramName + "_0_Resultset"); + elementRoot.appendChild( + paramElem); + + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = + rsmd.getColumnName( + j); + String colValue = + JDBCUtil.convertToString( + j, rs, rsmd, + dbName); + final Element e = + normalDoc.createElementNS( + NS, colName); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute( + "isNull", + "true"); + } else + e.setAttribute( + "isNull", + "false"); + e.appendChild(normalDoc.createTextNode( + colValue)); + paramElem.appendChild( + e); + if (mLogger.isLoggable( + Level.FINEST)) + mLogger.log( + Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + } + } + } else { + Object paramValue = null; + if (paramType.equalsIgnoreCase( + "CLOB")) { + java.sql.Clob clob = + (java.sql.Clob) cs.getObject(paramIndex); + if (clob != null) + paramValue = clob.getSubString(1, + (int) clob.length()); + } else if (paramType.equalsIgnoreCase("BLOB")) { + java.sql.Blob blob = + (java.sql.Blob) cs.getObject(paramIndex); + if (blob != null) + paramValue = new String( + blob.getBytes(1, + (int) blob.length())); + } else + paramValue = cs.getObject( + paramIndex); + final Element e = normalDoc.createElementNS(NS, + paramName); + if (paramValue == null) { + paramValue = ""; + e.setAttribute("isNull", + "true"); + } else + e.setAttribute("isNull", + "false"); + e.appendChild(normalDoc.createTextNode(paramValue. + toString())); + elementRoot.appendChild(e); + } + } catch (SQLException sqle) { + throw sqle; + } finally { + if (rs != null) + try { + rs.close(); + } catch (SQLException e) { + /* Ignore... */ ; + } + } + } + wrapperBuilder.addPart(part.getName(), + elementRoot); + } + normalDoc = wrapperBuilder.getResult(); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00703.JDBCN_Failed_NM_Part") + returnPartName + + "in message " + msg.getQName(); + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing message in its "; + throw new MessagingException(msgEx); + } + } else { + final String msgEx = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER") + + meta.getOperation().getName() + + " is missing "; + throw new MessagingException(msgEx); + } + } else { + final String operationName = + meta.getBindingOperation().getName(); + final Element normalRoot = + normalDoc.createElement(operationName); + normalDoc.appendChild(normalRoot); + + if (returnPartName != null) { + final Element returnElement = normalDoc.createElement( + returnPartName); + + // get resultset metadata rsmd and add it to the element + for (int i = 0; i < outParamIndex.size(); i++) { + int paramIndex = (Integer) outParamIndex.get(i); + String paramType = outParamTypes.get(paramIndex); + String paramName = outParamNames.get(paramIndex); + ResultSet rs = null; + try { + if (paramType.equalsIgnoreCase("REF CURSOR") || paramType. + equalsIgnoreCase("RESULTSET")) { + if (dbName.trim().contains("sql server") || dbName.trim(). + contains("adaptive server")) + rs = (ResultSet) cs.getResultSet(); + else + rs = (ResultSet) cs.getObject(paramIndex); + if (rs != null) { + final ResultSetMetaData rsmd = rs.getMetaData(); + while (rs.next()) { mRowCount++; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00706.JDBCN_ProcessNextRecord"); - Element paramElem = normalDoc.createElementNS(NS, - paramName + "_0_Resultset"); - returnElement.appendChild(paramElem); - - for (int j = 1; j <= rsmd.getColumnCount(); j++) { - final String colName = rsmd.getColumnName(j); - String colValue = JDBCUtil.convertToString(j, rs, rsmd, - dbName); - mLogger.log(Level.FINE, - "Got resultset for param: " + paramName + " colName: " + colName + " value: " + colValue); - final Element e = normalDoc.createElementNS(NS, colName); - if (rs.wasNull()) { - colValue = ""; - e.setAttribute("isNull", "true"); - } else - e.setAttribute("isNull", "false"); - e.appendChild(normalDoc.createTextNode(colValue)); - returnElement.appendChild(e); - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.FINEST, - "Col Name == " + colName + " and Col Val == " + colValue); - } - } - } - } else { - Object paramValue = null; - if (paramType.equalsIgnoreCase("CLOB")) { - java.sql.Clob clob = (java.sql.Clob) cs.getObject(paramIndex); - if (clob != null) - paramValue = clob.getSubString(1, - (int) clob.length()); - } else if (paramType.equalsIgnoreCase("BLOB")) { - java.sql.Blob blob = (java.sql.Blob) cs.getObject(paramIndex); - if (blob != null) - paramValue = new String(blob.getBytes(1, - (int) blob.length())); - } else - paramValue = cs.getObject(paramIndex); - final Element e = normalDoc.createElementNS(NS, - paramName); - if (paramValue == null) { - paramValue = ""; - e.setAttribute("isNull", "true"); - } else - e.setAttribute("isNull", "false"); - e.appendChild(normalDoc.createTextNode(paramValue.toString())); - returnElement.appendChild(e); - } - } catch (SQLException sqle) { - throw sqle; - } finally { - if (rs != null) - try { - rs.close(); - } catch (SQLException e) { - /* Ignore... */ ; - } - } - } - normalRoot.appendChild(returnElement); - } - } - if (JDBCNormalizer.mLogger.isLoggable(Level.FINE)) - DebugLog.debugLog(mLogger, Level.INFO, - "***normalize Procedure***", normalDoc); - - if (JDBCNormalizer.mLogger.isLoggable(Level.INFO)) - JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", - normalDoc); - - normalMsg.setContent(new DOMSource(normalDoc)); - } catch (final ParserConfigurationException tex) { - final String msg = JDBCNormalizer.mMessages.getString( - "DBBC_E00704.JDBCN_Failed_NM_WS_OPER"); - throw new MessagingException(msg, tex); - } catch (final WrapperProcessingException ex) { - final String exMsg = JDBCNormalizer.mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM") + ex.getMessage(); - throw new MessagingException(exMsg, ex); - } catch (final IOException ex) { - final String exMsg = JDBCNormalizer.mMessages.getString( - "DBBC_R00707.JDBCN_Failed_Base64_Encode"); - throw new MessagingException(exMsg, ex); - } - - return normalMsg; - } - - /** - * - * @return - * @throws ParserConfigurationException - */ - private static final Document newDocument() throws ParserConfigurationException { - if (JDBCNormalizer.mBuilder == null) { - final DocumentBuilderFactory factory = - DocumentBuilderFactory.newInstance(); - JDBCNormalizer.mBuilder = factory.newDocumentBuilder(); - } - - return JDBCNormalizer.mBuilder.newDocument(); - } - - private String[] validateColumnNames(ResultSetMetaData rsmd, String[] colNames) throws SQLException { - try { - for (int i = 0; i < rsmd.getColumnCount(); i++) - colNames[i] = rsmd.getColumnName(i + 1); - } catch (SQLException e) { - throw e; - } - for (int i = 0; i < colNames.length - 1; i++) - for (int j = i + 1; j < colNames.length; j++) - if (colNames[i].equalsIgnoreCase(colNames[j])) { - String temp = colNames[j] + "_1"; - do { - temp = validate(colNames, temp); - } while (status); - colNames[j] = temp; - } - return colNames; - } - - private String validate(String[] colNames, String temp) { - for (int i = 0; i < colNames.length; i++) - if (temp.equalsIgnoreCase(colNames[i])) { - temp = temp + "_1"; - status = true; - return temp; - } else - status = false; - return temp; - } - - protected void setOutParamIndex(ArrayList outParamIndex) { - this.outParamIndex = outParamIndex; - } - - protected void setOutParamTypes(HashMap outParamTypes) { - this.outParamTypes = outParamTypes; - } - - protected void setOutParamNames(HashMap outParamNames) { - this.outParamNames = outParamNames; - } - - public void setConnection(Connection con) { - this.connection = con; - } - - public void setInboundExchangeProcessRecordsMap(Map map) { - this.mInboundExchangeProcessRecordsMap = map; - } - - public void setRecordsProcessedList(ArrayList list) { - this.mProcessedList = list; - } - - public void setJDBCClusterManager(JDBCClusterManager jdbcClusterManager) { - this.mJDBCClusterManager = jdbcClusterManager; - } - - private boolean isRecordInserted(EndpointBean endpoint, Connection con, String pkName, - String colValue) { - boolean recordInserted = true; - String insertQuery = - "insert into OWNER_" + endpoint.getTableName() + "(" + pkName + ",INSTANCE_NAME) values(?,?)"; - PreparedStatement ps = null; - ParameterMetaData paramMetaData = null; - int parameters = 0; - try { - ps = con.prepareStatement(insertQuery); - paramMetaData = ps.getParameterMetaData(); - if (paramMetaData != null) - parameters = paramMetaData.getParameterCount(); - } catch (final SQLException ex) { - mLogger.log(Level.WARNING, ex.getLocalizedMessage()); - return false; - } - if (parameters != 0) - if ((colValue != null) && !colValue.trim().equals("")) { - // set default type. - int columnType = java.sql.Types.VARCHAR; - try { - columnType = paramMetaData.getParameterType(1); - ps.setObject(1, JDBCUtil.convert(colValue, columnType), - columnType); - columnType = paramMetaData.getParameterType(2); - ps.setObject(2, JDBCUtil.convert(endpoint.getInstanceName(), - columnType), columnType); - int rowsUpdated = ps.executeUpdate(); - recordInserted = true; - } catch (final Exception e) { - mLogger.log(Level.WARNING, e.getLocalizedMessage()); - mLogger.log(Level.INFO, mMessages.getString( - "DBBC-R01127.JDBCN_RECORD_LOCKED", - new Object[]{endpoint.getInstanceName()})); - recordInserted = false; - } - } - return recordInserted; - } - - private boolean isRecordProcessed(String colValue) { - boolean recordProcessed = true; - if (mProcessedList.isEmpty() || !mProcessedList.contains(colValue)) { - mProcessedList.add(colValue); - recordProcessed = false; - } - return recordProcessed; - } -} + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00706.JDBCN_ProcessNextRecord"); + Element paramElem = normalDoc.createElementNS(NS, + paramName + "_0_Resultset"); + returnElement.appendChild(paramElem); + + for (int j = 1; j <= rsmd.getColumnCount(); j++) { + final String colName = rsmd.getColumnName(j); + String colValue = JDBCUtil.convertToString(j, rs, rsmd, + dbName); + mLogger.log(Level.FINE, + "Got resultset for param: " + paramName + " colName: " + colName + " value: " + colValue); + final Element e = normalDoc.createElementNS(NS, colName); + if (rs.wasNull()) { + colValue = ""; + e.setAttribute("isNull", "true"); + } else + e.setAttribute("isNull", "false"); + e.appendChild(normalDoc.createTextNode(colValue)); + returnElement.appendChild(e); + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.FINEST, + "Col Name == " + colName + " and Col Val == " + colValue); + } + } + } + } else { + Object paramValue = null; + if (paramType.equalsIgnoreCase("CLOB")) { + java.sql.Clob clob = (java.sql.Clob) cs.getObject(paramIndex); + if (clob != null) + paramValue = clob.getSubString(1, + (int) clob.length()); + } else if (paramType.equalsIgnoreCase("BLOB")) { + java.sql.Blob blob = (java.sql.Blob) cs.getObject(paramIndex); + if (blob != null) + paramValue = new String(blob.getBytes(1, + (int) blob.length())); + } else + paramValue = cs.getObject(paramIndex); + final Element e = normalDoc.createElementNS(NS, + paramName); + if (paramValue == null) { + paramValue = ""; + e.setAttribute("isNull", "true"); + } else + e.setAttribute("isNull", "false"); + e.appendChild(normalDoc.createTextNode(paramValue.toString())); + returnElement.appendChild(e); + } + } catch (SQLException sqle) { + throw sqle; + } finally { + if (rs != null) + try { + rs.close(); + } catch (SQLException e) { + /* Ignore... */ ; + } + } + } + normalRoot.appendChild(returnElement); + } + } + if (JDBCNormalizer.mLogger.isLoggable(Level.FINE)) + DebugLog.debugLog(mLogger, Level.INFO, + "***normalize Procedure***", normalDoc); + + if (JDBCNormalizer.mLogger.isLoggable(Level.INFO)) + JDBCNormalizer.mLogger.log(Level.INFO, "normalized message", + normalDoc); + + normalMsg.setContent(new DOMSource(normalDoc)); + } catch (final ParserConfigurationException tex) { + final String msg = JDBCNormalizer.mMessages.getString( + "DBBC_E00704.JDBCN_Failed_NM_WS_OPER"); + throw new MessagingException(msg, tex); + } catch (final WrapperProcessingException ex) { + final String exMsg = JDBCNormalizer.mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM") + ex.getMessage(); + throw new MessagingException(exMsg, ex); + } catch (final IOException ex) { + final String exMsg = JDBCNormalizer.mMessages.getString( + "DBBC_R00707.JDBCN_Failed_Base64_Encode"); + throw new MessagingException(exMsg, ex); + } + + return normalMsg; + } + + /** + * + * @return + * @throws ParserConfigurationException + */ + private static final Document newDocument() throws ParserConfigurationException { + if (JDBCNormalizer.mBuilder == null) { + final DocumentBuilderFactory factory = + DocumentBuilderFactory.newInstance(); + JDBCNormalizer.mBuilder = factory.newDocumentBuilder(); + } + + return JDBCNormalizer.mBuilder.newDocument(); + } + + private String[] validateColumnNames(ResultSetMetaData rsmd, String[] colNames) throws SQLException { + try { + for (int i = 0; i < rsmd.getColumnCount(); i++) + colNames[i] = rsmd.getColumnName(i + 1); + } catch (SQLException e) { + throw e; + } + for (int i = 0; i < colNames.length - 1; i++) + for (int j = i + 1; j < colNames.length; j++) + if (colNames[i].equalsIgnoreCase(colNames[j])) { + String temp = colNames[j] + "_1"; + do { + temp = validate(colNames, temp); + } while (status); + colNames[j] = temp; + } + return colNames; + } + + private String validate(String[] colNames, String temp) { + for (int i = 0; i < colNames.length; i++) + if (temp.equalsIgnoreCase(colNames[i])) { + temp = temp + "_1"; + status = true; + return temp; + } else + status = false; + return temp; + } + + protected void setOutParamIndex(ArrayList outParamIndex) { + this.outParamIndex = outParamIndex; + } + + protected void setOutParamTypes(HashMap outParamTypes) { + this.outParamTypes = outParamTypes; + } + + protected void setOutParamNames(HashMap outParamNames) { + this.outParamNames = outParamNames; + } + + public void setConnection(Connection con) { + this.connection = con; + } + + public void setInboundExchangeProcessRecordsMap(Map map) { + this.mInboundExchangeProcessRecordsMap = map; + } + + public void setRecordsProcessedList(ArrayList list) { + this.mProcessedList = list; + } + + public void setJDBCClusterManager(JDBCClusterManager jdbcClusterManager) { + this.mJDBCClusterManager = jdbcClusterManager; + } + + private boolean isRecordInserted(EndpointBean endpoint, Connection con, String pkName, + String colValue) { + boolean recordInserted = true; + String insertQuery = + "insert into OWNER_" + endpoint.getTableName() + "(" + pkName + ",INSTANCE_NAME) values(?,?)"; + PreparedStatement ps = null; + ParameterMetaData paramMetaData = null; + int parameters = 0; + try { + ps = con.prepareStatement(insertQuery); + paramMetaData = ps.getParameterMetaData(); + if (paramMetaData != null) + parameters = paramMetaData.getParameterCount(); + } catch (final SQLException ex) { + mLogger.log(Level.WARNING, ex.getLocalizedMessage()); + return false; + } + if (parameters != 0) + if ((colValue != null) && !colValue.trim().equals("")) { + // set default type. + int columnType = java.sql.Types.VARCHAR; + try { + columnType = paramMetaData.getParameterType(1); + ps.setObject(1, JDBCUtil.convert(colValue, columnType), + columnType); + columnType = paramMetaData.getParameterType(2); + ps.setObject(2, JDBCUtil.convert(endpoint.getInstanceName(), + columnType), columnType); + int rowsUpdated = ps.executeUpdate(); + recordInserted = true; + } catch (final Exception e) { + mLogger.log(Level.WARNING, e.getLocalizedMessage()); + mLogger.log(Level.INFO, mMessages.getString( + "DBBC-R01127.JDBCN_RECORD_LOCKED", + new Object[]{endpoint.getInstanceName()})); + recordInserted = false; + } + } + return recordInserted; + } + + private boolean isRecordProcessed(String colValue) { + boolean recordProcessed = true; + if (mProcessedList.isEmpty() || !mProcessedList.contains(colValue)) { + mProcessedList.add(colValue); + recordProcessed = false; + } + return recordProcessed; + } +} diff --git a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/OutboundMessageProcessor.java b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/OutboundMessageProcessor.java index 9e645d38c..631f1ec12 100644 --- a/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/OutboundMessageProcessor.java +++ b/ojc-core/databasebc/databasebcimpl/src/org/glassfish/openesb/databasebc/OutboundMessageProcessor.java @@ -1,2261 +1,2261 @@ -/* - * BEGIN_HEADER - DO NOT EDIT - * - * The contents of this file are subject to the terms - * of the Common Development and Distribution License - * (the "License"). You may not use this file except - * in compliance with the License. - * - * You can obtain a copy of the license at - * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. - * See the License for the specific language governing - * permissions and limitations under the License. - * - * When distributing Covered Code, include this CDDL - * HEADER in each file and include the License file at - * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. - * If applicable add the following below this CDDL HEADER, - * with the fields enclosed by brackets "[]" replaced with - * your own identifying information: Portions Copyright - * [year] [name of copyright owner] - */ - -/* - * @(#)OutboundMessageProcessor.java - * - * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. - * - * END_HEADER - DO NOT EDIT - */ -package org.glassfish.openesb.databasebc; - -import com.sun.jbi.alerter.NotificationEvent; -import com.sun.jbi.nms.exchange.ExchangePattern; -import org.glassfish.openesb.databasebc.extensions.JDBCOperationInput; -import java.net.URI; -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.jbi.servicedesc.ServiceEndpoint; -import javax.jbi.messaging.*; -import javax.naming.Context; -import javax.naming.NamingException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import com.sun.jbi.internationalization.Messages; -import org.glassfish.openesb.databasebc.transaction.*; - -import javax.transaction.xa.XAResource; -import org.glassfish.openesb.databasebc.model.runtime.DBConnectionInfo; -import javax.sql.*; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; - -import com.sun.jbi.common.qos.messaging.MessagingChannel; -import com.sun.jbi.common.descriptor.EndpointInfo; -import com.sun.jbi.common.qos.redelivery.Redelivery; -import com.sun.jbi.common.qos.redelivery.RedeliveryConfig; -import com.sun.jbi.common.qos.redelivery.RedeliveryStatus; -import org.glassfish.openesb.databasebc.util.AlertsUtil; -import com.sun.jbi.eManager.provider.EndpointStatus; -import org.glassfish.openesb.databasebc.extensions.SPOperationInput; - -import net.java.hulp.measure.Probe; - -/** - * Process replies/requests received from the SE. - */ -public class OutboundMessageProcessor implements Runnable { - - private static final Messages mMessages = Messages.getMessages( - OutboundMessageProcessor.class); - private static final Logger mLogger = Messages.getLogger( - OutboundMessageProcessor.class); - Map mEndpoints; - DocumentBuilder mDocBuilder; - private MessagingChannel mChannel; - private MessageExchange mExchange; - private JDBCComponentContext mContext; - private Map mInboundExchanges; - DBConnectionInfo dbConnectionInfo; - XAConnection xaConnection = null; - private String mXAEnabled = null; - Connection connection = null; - PreparedStatement ps = null; - ResultSet rs = null; - CallableStatement cs = null; - //private TransactionManager mTxManager = null; - private XidImpl xid = null; - TransactionHelper mtxHelper = null; - private boolean mtxFlag; - XAResource xaResource = null; - // Settings for custom reliability header extensions - public static final String CUSTOM_RELIABILITY_MESSAGE_ID_PROPERTY = - "com.stc.jbi.messaging.messageid"; // NOI18N - public static final String CUSTOM_RELIABILITY_HEADER_NAMESPACE_URI = - "http://schemas.stc.com/ws/2005/07/custrm"; // NOI18N - public static final String CUSTOM_RELIABILITY_HEADER_LOCAL_NAME = - "MessageID"; // NOI18N - /** - * JBI message exchange properties for message grouping and sequencing (new CRMP) - */ - public static final String CRMP_GROUP_ID = "com.sun.jbi.messaging.groupid"; - public static final String CRMP_MESSAGE_ID = - "com.sun.jbi.messaging.messageid"; - private static final String CLIENT = "Client"; - private static final String SERVER = "Server"; - private ReplyListener replyListener = null; - private ArrayList outParamIndex = new ArrayList(); - private HashMap outParamTypes = - new HashMap(); - private HashMap outParamNames = - new HashMap(); - - protected OutboundMessageProcessor(final MessagingChannel chnl, final MessageExchange exchange, final Map endpoints, - final JDBCComponentContext context, final Map inboundMessageExchanges) throws ParserConfigurationException { - mChannel = chnl; - mEndpoints = endpoints; - mExchange = exchange; - mContext = context; - mInboundExchanges = inboundMessageExchanges; - //mTxManager = (TransactionManager) context.getTransactionManager(); - - final DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory. - newInstance(); - mDocBuilder = docBuilderFact.newDocumentBuilder(); - // mtxHelper = new TransactionHelper(); - dbConnectionInfo = new DBConnectionInfo(); - } - - /** - * - */ - //@Override - public void run() { - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.FINEST, "DBBC_R00606.OMP_Accept_msg", mExchange. - getExchangeId()); - else if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, "DBBC_R00630.OMP_Accept_msg"); - - try { - execute(); - } catch (final Exception ex) { - mLogger.log(Level.SEVERE, OutboundMessageProcessor.mMessages.getString( - "DBBC_E00607.OMP_Unexpected_exception", ex.getLocalizedMessage()), - ex); - String text = mMessages.getString( - "DBBC_E00607.OMP_Unexpected_exception", ex.getLocalizedMessage()); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00607"); - } - - if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.INFO, "DBBC_R00608.OMP_Complete_processing"); - } - - /** - * Process the message exchange - */ - public void execute() { - if (mExchange != null) { - final String exchangeId = mExchange.getExchangeId(); - - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, "DBBC_R00606.OMP_Accept_msg", exchangeId); - else if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, "DBBC_R00630.OMP_Accept_msg"); - - final boolean inbound = mInboundExchanges.containsKey(exchangeId); - final ListenerMeta listenerMeta = (ListenerMeta) mInboundExchanges.get( - exchangeId); - MessageExchangeReplyListener listener = null; - - if (listenerMeta != null) - listener = listenerMeta.getMessageExchangeReplyListener(); - - if (inbound) { - final long invocationTime = listenerMeta.getRequestInvocationTime(); - - final long difference = - System.currentTimeMillis() - invocationTime; - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, "DBBC_R00609.OMP_Resp_Ex", - new Object[]{exchangeId, - difference}); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.INFO, "DBBC_R00631.OMP_Resp_Ex", - new Object[]{exchangeId}); - } - - final URI pattern = mExchange.getPattern(); - - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, "DBBC_R00610.OMP_Pattern", - new Object[]{exchangeId, pattern}); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.INFO, "DBBC_R00632.OMP_Pattern", - new Object[]{pattern}); - - ServiceEndpoint serviceEndpoint = Redelivery.getEndpoint(mExchange); - final String serviceName = - serviceEndpoint.getServiceName().toString(); - final String endpointName = serviceEndpoint.getEndpointName(); - - if (mLogger.isLoggable(Level.FINE)) - mLogger.fine("Gettin bean for " + serviceName + endpointName); - - String epName = null; - - if (inbound) - epName = EndpointBean.getUniqueName(serviceName, endpointName, - EndpointBean.ENDPOINT_TYPE_INBOUND); - else - epName = EndpointBean.getUniqueName(serviceName, endpointName, - EndpointBean.ENDPOINT_TYPE_OUTBOUND); - - final EndpointBean epb = (EndpointBean) mEndpoints.get(epName); - - - - // Create a reply listener and add the ME Support for the same - if (replyListener == null) - replyListener = new ReplyListenerImpl(epb); - MessageExchangeSupport.addReplyListener(exchangeId, replyListener, - epb); - - final String status = epb.getValue(EndpointBean.STATUS); - - if (!status.equals(EndpointBean.STATUS_RUNNING)) { - // If the endpoint is not in the RUNNING state (i.e. is stopped - // or - // shutdown), ignore the message - if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.INFO, "DBBC_R00611.OMP_EP_state"); - } else - switch (ExchangePattern.valueOf(mExchange)) { - case IN_OUT: - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, "DBBC_R00612.OMP_Recv_InOut", - mExchange.getExchangeId()); - else if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, "DBBC_R00612.OMP_Recv_InOut", - ""); - if (mExchange.isTransacted()) { - // Start of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.EnterContext").fine( - "context"); - processInOutXA((InOut) mExchange, epb); - // End of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.ExitContext").fine( - "context"); - } else { - // Start of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.EnterContext").fine( - "context"); - processInOut((InOut) mExchange, epb); - // End of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.ExitContext").fine( - "context"); - } - break; - case IN_ONLY: - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.FINE, - "DBBC_R00613.OMP_Recv_InOnly", mExchange.getExchangeId()); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.INFO, - "DBBC_R00613.OMP_Recv_InOnly", ""); - - if (inbound) { - // Start of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.EnterContext").fine( - "context"); - processInOnlyInbound((InOnly) mExchange, epb, - listener); - // End of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.ExitContext").fine( - "context"); - } else { - // Start of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.EnterContext").fine( - "context"); - processInOnly((InOnly) mExchange, epb); - // End of nested diagnostic context prior to processing of message - Logger.getLogger("com.sun.ExitContext").fine( - "context"); - } - break; - case ROBUST_IN_ONLY: - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.WARNING, - "DBBC_W00614.OMP_Not_supported_inonly", - mExchange.getExchangeId()); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_W00614.OMP_Not_supported_inonly", ""); - break; - case IN_OPTIONAL_OUT: - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.WARNING, - "DBBC_W00615.OMP_Not_supported_outin", - mExchange.getExchangeId()); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_W00615.OMP_Not_supported_outin", ""); - break; - default: - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.WARNING, - "DBBC_W00617.OMP_Invalid_pattern", - exchangeId); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_W00617.OMP_Invalid_pattern", ""); - return; - } - } // if(exchange) - } - - /** - * @param inonly - * @param endpoint - * @param listener - */ - protected void processInOnlyInbound(final InOnly inonly, - final EndpointBean endpoint, - final MessageExchangeReplyListener listener) { - mLogger.info("DBBC_R00618.OMP_Processing_InOnly_inbound"); - - if (inonly.getStatus() == ExchangeStatus.DONE) - updateTallyReceives(endpoint, true); - else if (inonly.getStatus() == ExchangeStatus.ERROR) { - RedeliveryStatus retryStatus = - Redelivery.getRedeliveryStatus(inonly); - if (retryStatus != null && !retryStatus.hasFailed()) - try { - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E01037.Redelivering_message", - new Object[]{retryStatus.getRemainingRetries()}); - mLogger.log(Level.WARNING, text); - - } - MessageExchangeSupport.notifyOfRedelivery(inonly); - } catch (Exception e) { - String groupId = (String) inonly.getProperty(CRMP_GROUP_ID); - String messageId = (String) inonly.getProperty( - CRMP_MESSAGE_ID); - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E01036.Failed_to_process_redelivery", - new Object[]{groupId, messageId}); - mLogger.log(Level.WARNING, text, e); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - endpoint.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E01036"); - } - } - else - try { - // No more retries...handle all the recourse actions. Only one that we need to handle in - // a BC-specific way is the suspending of endpoints - suspendEndpoint(inonly, endpoint); - - listener.processReplyMessage(inonly); - } catch (final Exception ex) { - mLogger.log(Level.SEVERE, - "DBBC_E00619.OMP_Failed_processing_inonly_inbound", - ex); - } - updateTallyReceives(endpoint, false); - String msg = mMessages.getString( - "DBBC_E00619.OMP_Failed_processing_inonly_inbound", - new Object[]{inonly.getEndpoint().getServiceName(), - inonly.getEndpoint().getEndpointName(), - inonly.getOperation()}); - - mLogger.log(Level.WARNING, msg); - return; - } else if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.WARNING, - "DBBC_W00620.OMP_Unexpected_ME_status", new Object[]{ - inonly.getEndpoint(), inonly.getStatus()}); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.WARNING, - "DBBC_W00633.OMP_Unexpected_ME_status", - new Object[]{inonly.getEndpoint()}); - - try { - listener.processReplyMessage(inonly); - } catch (final Exception ex) { - mLogger.log(Level.SEVERE, - "DBBC_E00619.OMP_Failed_processing_inonly_inbound", ex); - } - } - - private void suspendEndpoint(InOnly inonly, EndpointBean endpoint) throws Exception { - - ServiceEndpoint serviceEndpoint = Redelivery.getEndpoint(inonly); - - EndpointInfo endpointInfo = EndpointInfo.valueOf( - serviceEndpoint, - false); // false = consumer endpoint - - RedeliveryConfig config = - mContext.getBindingChannel().getServiceQuality( - endpointInfo, RedeliveryConfig.class); - - if (config != null && config.getFailure() == RedeliveryConfig.Failure.suspend) - // Suspend endpoint. - mContext.getDeployer().suspend(endpoint); - } - - /** - * @param inout - * @param epb - */ - protected void processInOut(final InOut inout, final EndpointBean epb) { - Connection connection = null; - String faultCode = null; - String faultDetail = null; - boolean success = true; - if (inout.getStatus() == ExchangeStatus.DONE) { - - // remove the redelivery listener handler - no retry needed. - MessageExchangeSupport.removeReplyListener(inout.getExchangeId()); - - updateTallyReceives(epb, true); - } else if (inout.getStatus() == ExchangeStatus.ERROR) { - - // added for retry support - - updateTallyReceives(epb, false); - - // send alerts - String errorMsg = inout.getError().getMessage(); - if (errorMsg != null) { - String msg = mMessages.getString( - "DBBC-E00720.Message_exchange_error", - new Object[]{ - String.valueOf(inout.getService()), - inout.getEndpoint().getEndpointName(), - errorMsg - }); - mLogger.log(Level.SEVERE, msg); - AlertsUtil.getAlerter().warning(msg, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00720"); - } else { - String msg = mMessages.getString( - "DBBC-E00721.Message_exchange_error_no_detail", - new Object[]{ - String.valueOf(inout.getService()), - inout.getEndpoint().getEndpointName() - }); - mLogger.log(Level.SEVERE, msg); - AlertsUtil.getAlerter().warning(msg, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00721"); - } - /** - // let's see if retry is configured or not - EndpointInfo info = new EndpointInfo(false, - epb.getEndpointName(), - null, - epb.getServiceName(), - null); - RedeliveryConfig retryConfig = mChannel.getServiceQuality(info, RedeliveryConfig.class); - **/ - RedeliveryStatus retryStatus = Redelivery.getRedeliveryStatus(inout); - if (retryStatus != null && retryStatus.getRemainingRetries() > 0) - try { - MessageExchangeSupport.notifyOfRedelivery(inout); - } catch (Exception e) { - String groupId = (String) inout.getProperty(CRMP_GROUP_ID); - String messageId = (String) inout.getProperty( - CRMP_MESSAGE_ID); - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E01036.Failed_to_process_redelivery", - new Object[]{groupId, messageId}); - mLogger.log(Level.WARNING, text, e); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E01036"); - } - } - - //epb.getEndpointStatus().incrementReceivedErrors(); - } else { - - // added for retry support - try { - MessageExchangeSupport.notifyOfReply(inout); - } catch (Exception ex) { - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E00759.Exception_during_reply_processing", ex. - getLocalizedMessage()); - mLogger.log(Level.SEVERE, text, ex); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00759"); - } - success = false; - } - - try { - updateTallyReceivedRequests(epb); - Map operationNameToMetaData = (Map) epb.getValueObj( - EndpointBean.OPERATION_NAME_TO_META_DATA); - OperationMetaData meta = (OperationMetaData) operationNameToMetaData.get(inout.getOperation(). - getLocalPart()); - - if (meta == null) - throw new MessagingException(mMessages.getString( - "DBBC_E00621.OMP_oper_NotDefined") + inout.getOperation()); - - final NormalizedMessage inMsg = inout.getInMessage(); - NormalizedMessage outMsg = mExchange.createMessage(); - //boolean success = true; - String statusMessage = ""; - - try { - rs = null; - int rowsUpdated = -1; - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - String generatedKeyValue = ""; - String outputValue = ""; - - // writeMessage(inMsg, destinationAddress, false); - JDBCOperationInput input = meta.getJDBCSql(); - if (input != null) { - final String sql = input.getSql(); - Object jndiNameObj = - inMsg.getProperty( - JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); - try { - if (jndiNameObj != null) { - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); - connection = getDatabaseConnection(inMsg); - } else { - String jndiName = epb.getValue( - EndpointBean.JDBC_DATABASE_JNDI_NAME); - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiName); - connection = getDatabaseConnection(epb); - } - } catch (Exception e) { - faultCode = SERVER; - faultDetail = "Unable to get connection : " + e.toString(); - String faultString = mMessages.getString( - "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString()}); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00627"); - throw new Exception(faultString, e); - } - if (isSelectStatement(sql)) { - try { - rs = executeOutboundSQLSelect(inMsg, epb, meta, - connection); - } catch (final SQLException ex) { - faultCode = SERVER; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + ex. - getLocalizedMessage(); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation(), ex.getLocalizedMessage()}); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00706"); - throw new Exception(faultString, ex); - } catch (final Exception ex) { - faultCode = CLIENT; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + ex. - getLocalizedMessage(); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation(), ex.getLocalizedMessage()}); - throw new Exception(faultString, ex); - } - - if (rs != null) - statusMessage = "Success : ResultSet returned "; - - final JDBCNormalizer normalizer = - new JDBCNormalizer(); - Probe normalizationMeasurement = null; - try { - normalizationMeasurement = - Probe.info(getClass(), - epb.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); - - outMsg = normalizer.normalizeSelect(rs, inout, - meta, connection.getMetaData(). - getDriverName()); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString()}); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00702"); - throw new Exception(faultString, e); - } finally { - if (normalizationMeasurement != null) - normalizationMeasurement.end(); - } - } else { - try { - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - String generatedKey = meta.getJDBCSql(). - getGeneratedKey(); - if (isInsertStatement(sql) && generatedKey != null && !"".equals( - generatedKey)) { - generatedKeyValue = - executeOutboundSQLWithGeneratedKeys( - inMsg, epb, meta, connection); - outputValue = generatedKeyValue; - statusMessage = - "Success : Generated Key = " + generatedKeyValue; - } else { - rowsUpdated = executeOutboundSQL(inMsg, epb, - meta, connection); - statusMessage = - "Success : " + rowsUpdated + " are updated ."; - outputValue = String.valueOf(rowsUpdated); - } - } catch (final SQLException ex) { - faultCode = SERVER; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString(), ex. - getLocalizedMessage()}); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00706"); - throw new Exception(faultString, ex); - } catch (final Exception ex) { - faultCode = CLIENT; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString()}); - throw new Exception(faultString, ex); - } - - - final JDBCNormalizer normalizer = - new JDBCNormalizer(); - Probe normalizationMeasurement = null; - try { - normalizationMeasurement = - Probe.info(getClass(), - epb.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - outMsg = - normalizer.normalize(outputValue, inout, - meta); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = - mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM", - new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString(), e. - getLocalizedMessage()}); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00702"); - throw new Exception(faultString, e); - } finally { - if (normalizationMeasurement != null) - normalizationMeasurement.end(); - } - } - inout.setOutMessage(outMsg); - } else { - SPOperationInput spInput = - meta.getJDBCSPOperationInput(); - if (spInput != null) { - Object jndiNameObj = - inMsg.getProperty( - JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); - try { - if (jndiNameObj != null) { - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); - connection = getDatabaseConnection(inMsg); - } else { - String jndiName = - epb.getValue( - EndpointBean.JDBC_DATABASE_JNDI_NAME); - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiName); - connection = getDatabaseConnection(epb); - } - } catch (Exception e) { - faultCode = SERVER; - faultDetail = "Unable to get connection : " + e.toString(); - String faultString = - mMessages.getString( - "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString()}); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00627"); - throw new Exception(faultString, e); - } - cs = executeOutboundProc(inMsg, epb, meta, - connection); - final JDBCNormalizer normalizer = - new JDBCNormalizer(); - final JDBCDenormalizer denormalizer = - new JDBCDenormalizer(); - if (connection.getMetaData().getDatabaseProductName(). - toLowerCase().contains("sql server") || connection. - getMetaData().getDatabaseProductName(). - toLowerCase().contains("adaptive server")) - if (outParamIndex.size() == 0) { - outParamNames.put(1, denormalizer.getProcName(meta. - getJDBCSPOperationInput(). - getExecutionString())); - outParamTypes.put(1, "RESULTSET"); - outParamIndex.add( - Integer.valueOf(Double.valueOf(1).intValue())); - } /*else - for (int i = 1; i <= outParamIndex.size(); i++) - if ((outParamNames.get(i) != null) && (outParamNames.get(i). - equalsIgnoreCase( - "RETURN_VALUE"))) { - outParamNames.put(i, denormalizer.getProcName(meta. - getJDBCSPOperationInput(). - getExecutionString())); - outParamTypes.put(i, "RETURN_VALUE"); - }*/ - normalizer.setOutParamIndex(outParamIndex); - normalizer.setOutParamNames(outParamNames); - normalizer.setOutParamTypes(outParamTypes); - Probe normalizationMeasurement = null; - try { - normalizationMeasurement = - Probe.info(getClass(), - epb.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); - outMsg = normalizer.normalizeProcedure(cs, inout, meta, connection.getMetaData(). - getDatabaseProductName().toLowerCase()); - } catch (final SQLException ex) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = mMessages.getString( - "DBBC_E00727.JDBCN_Failed_NM_SQL", new Object[]{ - ex.getClass().getName(), - ex.getLocalizedMessage() - }); - throw new Exception(faultString, ex); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = - mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString()}); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00702"); - throw new Exception(faultString, e); - } finally { - if (normalizationMeasurement != null) - normalizationMeasurement.end(); - - } - inout.setOutMessage(outMsg); - - } - } - } catch (final Exception ex) { - mLogger.log(Level.SEVERE, - mMessages.getString("DBBC_E00622.OMP_Failed_writing"), - ex); - // should this populate a full fault instead? - AlertsUtil.getAlerter().warning(mMessages.getString( - "DBBC_E00622.OMP_Failed_writing"), - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00622"); - // inout.setError(ex); - statusMessage = "Failed " + ex.getMessage(); - success = false; - setErrorInExchange(inout, faultCode, faultDetail, ex); - inout.setStatus(ExchangeStatus.ERROR); - - } - - mChannel.send(inout); - - if (success) - updateTallySentReplies(epb); - else - epb.getEndpointStatus().incrementSentErrors(); - } catch (final Exception ex) { - mLogger.log(Level.SEVERE, - mMessages.getString("DBBC_E00623.OMP_Failed_inout"), ex); - throw new RuntimeException(ex); - } finally { - try { - if (rs != null) - rs.close(); - if (cs != null) - cs.close(); - if (ps != null) - ps.close(); - if (connection != null) - connection.close(); - } catch (SQLException sqlexception) { - mLogger.log(Level.SEVERE, - mMessages.getString( - "DBBC_E00628.OMP_Cleanup_Failure"), - sqlexception); - } - } - } - } - - private void processInOutXA(final InOut inout, final EndpointBean epb) { - mLogger.log(Level.INFO, "Entering processInOutXA"); - XAConnection xaconnection = null; - Transaction transaction = null; - String faultCode = null; - String faultDetail = null; - boolean success = true; - - if (inout.getStatus() == ExchangeStatus.DONE) { - - // remove the redelivery listener handler - no retry needed. - MessageExchangeSupport.removeReplyListener(inout.getExchangeId()); - - updateTallyReceives(epb, true); - } else if (inout.getStatus() == ExchangeStatus.ERROR) { - - // added for retry support - - updateTallyReceives(epb, false); - - // send alerts - String errorMsg = inout.getError().getMessage(); - if (errorMsg != null) { - String msg = mMessages.getString( - "DBBC-E00720.Message_exchange_error", - new Object[]{ - String.valueOf(inout.getService()), - inout.getEndpoint().getEndpointName(), - errorMsg - }); - mLogger.log(Level.SEVERE, msg); - AlertsUtil.getAlerter().warning(msg, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00720"); - } else { - String msg = mMessages.getString( - "DBBC-E00721.Message_exchange_error_no_detail", - new Object[]{ - String.valueOf(inout.getService()), - inout.getEndpoint().getEndpointName() - }); - mLogger.log(Level.SEVERE, msg); - AlertsUtil.getAlerter().warning(msg, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00721"); - } - /** - // let's see if retry is configured or not - EndpointInfo info = new EndpointInfo(false, - epb.getEndpointName(), - null, - epb.getServiceName(), - null); - RedeliveryConfig retryConfig = mChannel.getServiceQuality(info, RedeliveryConfig.class); - **/ - RedeliveryStatus retryStatus = Redelivery.getRedeliveryStatus(inout); - if (retryStatus != null && retryStatus.getRemainingRetries() > 0) - try { - MessageExchangeSupport.notifyOfRedelivery(inout); - } catch (Exception e) { - String groupId = (String) inout.getProperty(CRMP_GROUP_ID); - String messageId = (String) inout.getProperty( - CRMP_MESSAGE_ID); - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E01036.Failed_to_process_redelivery", - new Object[]{groupId, messageId}); - mLogger.log(Level.WARNING, text, e); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E01036"); - } - } - - //epb.getEndpointStatus().incrementReceivedErrors(); - } else { - - // added for retry support - try { - MessageExchangeSupport.notifyOfReply(inout); - } catch (Exception ex) { - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E00759.Exception_during_reply_processing", ex. - getLocalizedMessage()); - mLogger.log(Level.SEVERE, text, ex); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00759"); - } - success = false; - } - - try { - updateTallyReceivedRequests(epb); - Map operationNameToMetaData = (Map) epb.getValueObj( - EndpointBean.OPERATION_NAME_TO_META_DATA); - OperationMetaData meta = (OperationMetaData) operationNameToMetaData.get(inout.getOperation(). - getLocalPart()); - - if (meta == null) - throw new MessagingException(mMessages.getString( - "DBBC_E00621.OMP_oper_NotDefined") + inout.getOperation()); - - final NormalizedMessage inMsg = inout.getInMessage(); - NormalizedMessage outMsg = mExchange.createMessage(); - - String statusMessage = ""; - String jndiName = null; - - try { - rs = null; - int rowsUpdated = -1; - - String generatedKeyValue = ""; - String outputValue = ""; - - // writeMessage(inMsg, destinationAddress, false); - JDBCOperationInput input = meta.getJDBCSql(); - if (input != null) { - final String sql = input.getSql(); - jndiName = epb.getValue( - EndpointBean.JDBC_DATABASE_JNDI_NAME); - - if (inout.isTransacted()) - // Removing manual enlistment. Moving to automatic resource enlistment - // mtxHelper.handleOutbound(mExchange); - // enlistResource(epb); - transaction = - (Transaction) inout.getProperty( - MessageExchange.JTA_TRANSACTION_PROPERTY_NAME); - if (transaction != null) - resumeThreadTx(transaction); - - try { - connection = getDatabaseConnection(epb); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = "Unable to get connection : " + e.toString(); - String faultString = mMessages.getString( - "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString()}); - AlertsUtil.getAlerter().warning(mMessages.getString( - "DBBC_E00627.OMP_Failed_LookUp_JNDI"), - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00627"); - throw new Exception(faultString, e); - } - connection.setAutoCommit(true); - - - /* PP: Glassfish does not return a XADataSource and always returns - * a DataSource30 object which does not implement getXAResource() method - xaconnection = getXADatabaseConnection(epb); - XAResource xaresource = xaconnection.getXAResource(); - transaction.enlistResource(xaresource); - connection = xaconnection.getConnection();*/ - - if (isSelectStatement(sql)) { - try { - rs = executeOutboundSQLSelect(inMsg, epb, meta, - connection); - } catch (final SQLException ex) { - faultCode = SERVER; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString(), ex. - getLocalizedMessage() - }); - processException(ex, transaction, inout, epb, - faultCode, faultDetail); - AlertsUtil.getAlerter().warning(faultDetail, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00626"); - throw new Exception(faultString, ex); - } catch (final Exception ex) { - faultCode = CLIENT; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString() - }); - processException(ex, transaction, inout, epb, - faultCode, faultDetail); - throw new Exception(faultString, ex); - } - if (rs != null) - statusMessage = "Success : ResultSet returned "; - - final JDBCNormalizer normalizer = - new JDBCNormalizer(); - Probe normalizationMeasurement = null; - - try { - normalizationMeasurement = - Probe.info(getClass(), - epb.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); - - outMsg = normalizer.normalizeSelect(rs, inout, - meta, connection.getMetaData(). - getDriverName()); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString(), e.getLocalizedMessage() - }); - processException(e, transaction, inout, epb, - faultCode, faultDetail); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00702"); - throw new Exception(faultString, e); - } finally { - if (normalizationMeasurement != null) - normalizationMeasurement.end(); - } - inout.setOutMessage(outMsg); - } else { - if (meta.getJDBCOperationInput().getOperationType(). - equalsIgnoreCase(JDBCOperations.OPERATION_TYPE_EXECUTE. - toString())) { - try { - cs = executeOutboundProc(inMsg, epb, meta, - connection); - } catch (final SQLException ex) { - faultCode = SERVER; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString(), ex. - getLocalizedMessage() - }); - processException(ex, transaction, inout, epb, - faultCode, faultDetail); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00626"); - throw new Exception(faultString, ex); - } catch (final Exception ex) { - faultCode = CLIENT; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString() - }); - processException(ex, transaction, inout, epb, - faultCode, faultDetail); - throw new Exception(faultString, ex); - } - final JDBCNormalizer normalizer = - new JDBCNormalizer(); - Probe normalizationMeasurement = null; - try { - normalizationMeasurement = - Probe.info(getClass(), - epb.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); - outMsg = normalizer.normalizeProcedure(cs, - inout, meta, connection.getMetaData(). - getDatabaseProductName()); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString() - }); - processException(e, transaction, inout, epb, - faultCode, faultDetail); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00702"); - throw new Exception(faultString, e); - } finally { - if (normalizationMeasurement != null) - normalizationMeasurement.end(); - } - } else { - try { - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - String generatedKey = meta.getJDBCSql(). - getGeneratedKey(); - if (isInsertStatement(sql) && generatedKey != null && !"". - equals(generatedKey)) { - generatedKeyValue = - executeOutboundSQLWithGeneratedKeys( - inMsg, epb, meta, connection); - outputValue = generatedKeyValue; - statusMessage = - "Success : Generated Key = " + generatedKeyValue; - } else { - rowsUpdated = executeOutboundSQL(inMsg, - epb, meta, connection); - statusMessage = - "Success : " + rowsUpdated + " are updated ."; - outputValue = - String.valueOf(rowsUpdated); - } - } catch (final SQLException ex) { - faultCode = SERVER; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString(), ex. - getLocalizedMessage() - }); - processException(ex, transaction, inout, epb, - faultCode, faultDetail); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00706"); - } catch (final Exception ex) { - faultCode = CLIENT; - faultDetail = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString() - }); - processException(ex, transaction, inout, epb, - faultCode, faultDetail); - throw new Exception(faultString, ex); - } - - - final JDBCNormalizer normalizer = - new JDBCNormalizer(); - Probe normalizationMeasurement = null; - try { - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - outMsg = normalizer.normalize(outputValue, - inout, meta); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - inout.getOperation().toString() - }); - AlertsUtil.getAlerter().warning(faultString, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - null, - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC_E00702"); - processException(e, transaction, inout, epb, - faultCode, faultDetail); - throw new Exception(faultString, e); - } finally { - if (normalizationMeasurement != null) - normalizationMeasurement.end(); - } - } - inout.setOutMessage(outMsg); - } - } else { - SPOperationInput spInput = - meta.getJDBCSPOperationInput(); - if (spInput != null) { - Object jndiNameObj = - inMsg.getProperty( - JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); - if (inout.isTransacted()) - // Removing manual enlistment. Moving to automatic resource enlistment - // mtxHelper.handleOutbound(mExchange); - // enlistResource(epb); - transaction = - (Transaction) inout.getProperty( - MessageExchange.JTA_TRANSACTION_PROPERTY_NAME); - if (transaction != null) - resumeThreadTx(transaction); - try { - if (jndiNameObj != null) { - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); - connection = getDatabaseConnection(inMsg); - } else { - jndiName = - epb.getValue( - EndpointBean.JDBC_DATABASE_JNDI_NAME); - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiName); - connection = getDatabaseConnection(epb); - } - } catch (Exception e) { - faultCode = SERVER; - faultDetail = "Unable to get connection : " + e.toString(); - String faultString = - mMessages.getString( - "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString()}); - processException(e, transaction, inout, epb, - faultCode, faultDetail); - throw new Exception(faultString, e); - } - connection.setAutoCommit(true); - cs = executeOutboundProc(inMsg, epb, meta, - connection); - final JDBCNormalizer normalizer = - new JDBCNormalizer(); - final JDBCDenormalizer denormalizer = - new JDBCDenormalizer(); - if (connection.getMetaData().getDatabaseProductName(). - toLowerCase().contains("sql server") || connection. - getMetaData().getDatabaseProductName(). - toLowerCase().contains("adaptive server")) - if (outParamIndex.size() == 0) { - outParamNames.put(1, denormalizer.getProcName(meta. - getJDBCSPOperationInput(). - getExecutionString())); - outParamTypes.put(1, "RESULTSET"); - outParamIndex.add( - Integer.valueOf(Double.valueOf(1).intValue())); - } else - for (int i = 1; i <= outParamIndex.size(); i++) - if ((outParamNames.get(i) != null) && (outParamNames.get(i). - equalsIgnoreCase( - "RETURN_VALUE"))) { - outParamNames.put(i, denormalizer.getProcName(meta. - getJDBCSPOperationInput(). - getExecutionString())); - outParamTypes.put(i, "RESULTSET"); - } - normalizer.setOutParamIndex(outParamIndex); - normalizer.setOutParamNames(outParamNames); - normalizer.setOutParamTypes(outParamTypes); - Probe normalizationMeasurement = null; - try { - normalizationMeasurement = - Probe.info(getClass(), - epb.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); - outMsg = normalizer.normalizeProcedure(cs, inout, meta, connection.getMetaData(). - getDatabaseProductName().toLowerCase()); - } catch (Exception e) { - faultCode = SERVER; - faultDetail = - "Unable to normalize response from the external service."; - String faultString = - mMessages.getString( - "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ - inout.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString()}); - processException(e, transaction, inout, epb, - faultCode, faultDetail); - throw new Exception(faultString, e); - } finally { - if (normalizationMeasurement != null) - normalizationMeasurement.end(); - - } - inout.setOutMessage(outMsg); - - } - } - } catch (final Exception ex) { - mLogger.log(Level.SEVERE, - OutboundMessageProcessor.mMessages.getString( - "DBBC_E00622.OMP_Failed_writing"), ex.getLocalizedMessage()); - success = false; - setErrorInExchange(inout, faultCode, faultDetail, ex); - inout.setStatus(ExchangeStatus.ERROR); - } - } catch (final Exception ex) { - mLogger.log(Level.SEVERE, - OutboundMessageProcessor.mMessages.getString( - "DBBC_E00623.OMP_Failed_inout"), ex); - throw new RuntimeException(ex); - } finally { - try { - getTransactionManager().suspend(); - mChannel.send(inout); - - - if (success) - updateTallySentReplies(epb); - else - epb.getEndpointStatus().incrementSentErrors(); - if (rs != null) - rs.close(); - if (cs != null) - cs.close(); - - if (ps != null) - ps.close(); - if (connection != null) - connection.close(); - } catch (SQLException sqlexception) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00628.OMP_Cleanup_Failure"), sqlexception); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00628.OMP_Cleanup_Failure")); - } catch (Exception ex) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00628.OMP_Cleanup_Failure"), ex); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00628.OMP_Cleanup_Failure")); - - } - } - } - } - - /** - * @param inonly - * @param epb - */ - protected void processInOnly(final InOnly inonly, final EndpointBean epb) { - Connection connection = null; - Transaction transaction = null; - boolean success = true; - String faultCode = null; - String faultDetail = null; - if (inonly.getStatus() == ExchangeStatus.DONE) - // remove the redelivery listener handler - no retry needed. - MessageExchangeSupport.removeReplyListener(inonly.getExchangeId()); - else if (inonly.getStatus() == ExchangeStatus.ERROR) { - - // added for retry support - updateTallyReceives(epb, false); - - // send alerts - String errorMsg = inonly.getError().getMessage(); - if (errorMsg != null) { - String msg = mMessages.getString( - "DBBC-E00720.Message_exchange_error", - new Object[]{ - String.valueOf(inonly.getService()), - inonly.getEndpoint().getEndpointName(), - errorMsg - }); - mLogger.log(Level.SEVERE, msg); - AlertsUtil.getAlerter().warning(msg, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00720"); - } else { - String msg = mMessages.getString( - "DBBC-E00721.Message_exchange_error_no_detail", - new Object[]{ - String.valueOf(inonly.getService()), - inonly.getEndpoint().getEndpointName() - }); - mLogger.log(Level.SEVERE, msg); - AlertsUtil.getAlerter().warning(msg, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00721"); - } - /** - // let's see if retry is configured or not - EndpointInfo info = new EndpointInfo(false, - epb.getEndpointName(), - null, - epb.getServiceName(), - null); - RedeliveryConfig retryConfig = mChannel.getServiceQuality(info, RedeliveryConfig.class); - **/ - RedeliveryStatus retryStatus = - Redelivery.getRedeliveryStatus(inonly); - if (retryStatus != null && retryStatus.getRemainingRetries() > 0) { - try { - MessageExchangeSupport.notifyOfRedelivery(inonly); - } catch (Exception e) { - String groupId = (String) inonly.getProperty(CRMP_GROUP_ID); - String messageId = (String) inonly.getProperty( - CRMP_MESSAGE_ID); - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E01036.Failed_to_process_redelivery", - new Object[]{groupId, messageId}); - mLogger.log(Level.WARNING, text, e); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E01036"); - } - } - updateTallyReceives(epb, false); - } - } - - // added for retry support - try { - MessageExchangeSupport.notifyOfReply(inonly); - } catch (Exception ex) { - if (mLogger.isLoggable(Level.WARNING)) { - String text = mMessages.getString( - "DBBC-E00759.Exception_during_reply_processing", ex. - getLocalizedMessage()); - mLogger.log(Level.SEVERE, text, ex); - AlertsUtil.getAlerter().warning(text, - JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, - epb.getDeploymentId(), - AlertsUtil.getServerType(), - AlertsUtil.COMPONENT_TYPE_BINDING, - NotificationEvent.OPERATIONAL_STATE_RUNNING, - NotificationEvent.EVENT_TYPE_ALERT, - "DBBC-E00759"); - } - success = false; - } - - try { - updateTallyReceivedRequests(epb); - - final NormalizedMessage inMsg = inonly.getInMessage(); - final Map operationNameToMetaData = (Map) epb.getValueObj( - EndpointBean.OPERATION_NAME_TO_META_DATA); - final OperationMetaData meta = (OperationMetaData) operationNameToMetaData.get(inonly.getOperation(). - getLocalPart()); - - if (meta == null) - throw new MessagingException(OutboundMessageProcessor.mMessages. - getString("DBBC_E00621.OMP_oper_NotDefined") + inonly. - getOperation()); - - - if (inonly.isTransacted()) - // Removing manual enlistment. Moving to automatic resource enlistment - // mtxHelper.handleOutbound(mExchange); - // enlistResource(epb); - transaction = (Transaction) inonly.getProperty( - MessageExchange.JTA_TRANSACTION_PROPERTY_NAME); - - try { - if (transaction != null) - getTransactionManager().resume(transaction); - Object jndiNameObj = - inMsg.getProperty( - JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); - try { - if (jndiNameObj != null) { - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); - connection = getDatabaseConnection(inMsg); - } else { - String jndiName = epb.getValue( - EndpointBean.JDBC_DATABASE_JNDI_NAME); - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00629.OMP_UsedJNDI") + jndiName); - connection = getDatabaseConnection(epb); - } - } catch (Exception e) { - faultCode = SERVER; - faultDetail = "Unable to get connection : " + e.toString(); - String faultString = mMessages.getString( - "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ - inonly.getExchangeId(), epb.getValue( - EndpointBean.ENDPOINT_NAME), - mExchange.getOperation().toString()}); - throw new Exception(faultString, e); - } - - if (transaction != null) - connection.setAutoCommit(true); - // writeMessage(inMsg, destinationAddress, false); - if (meta.getJDBCOperationInput().getOperationType(). - equalsIgnoreCase( - JDBCOperations.OPERATION_TYPE_EXECUTE.toString())) - // executeOutboundProc(inMsg, epb, meta); - // Auto enlistment: pass the transaction retrieved from the Message exchange. - cs = executeOutboundProc(inMsg, epb, meta, connection); - else - // executeOutboundSQL(inMsg, epb, meta); - // Auto enlistment: pass the transaction retrieved from the Message exchange. - executeOutboundSQL(inMsg, epb, meta, connection); - inonly.setStatus(ExchangeStatus.DONE); - } catch (final SQLException ex) { - processException(ex, transaction, inonly, epb, faultCode, - faultDetail); - } catch (final MessagingException ex) { - processException(ex, transaction, inonly, epb, faultCode, - faultDetail); - } catch (final Exception ex) { - processException(ex, transaction, inonly, epb, faultCode, - faultDetail); - } finally { - try { - if (cs != null) - cs.close(); - - if (ps != null) - ps.close(); - if (connection != null) - connection.close(); - } catch (SQLException sqlexception) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00628.OMP_Cleanup_Failure"), sqlexception); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00628.OMP_Cleanup_Failure")); - } - } - - /* - * if (inonly.isTransacted()) { mtxHelper.handleInbound(mExchange); } - */ - - if (transaction != null) - getTransactionManager().suspend(); - mChannel.send(inonly); - - - if (success) - updateTallySends(epb, success); - else - epb.getEndpointStatus().incrementSentErrors(); - } catch (final Exception ex) { - if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00624.OMP_Failed_inonly"), ex); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.SEVERE, mMessages.getString( - "DBBC_E00624.OMP_Failed_inonly")); - - } - } - - /** - * @param nMsg - * @param eBean - * @param opMetaData - * @return - * @throws MessagingException - */ - protected ResultSet executeOutboundSQLSelect(final NormalizedMessage nMsg, - final EndpointBean eBean, - final OperationMetaData opMetaData, - Connection connection) throws SQLException, MessagingException { - String sql = null; - try { - sql = opMetaData.getJDBCSql().getSql(); - mLogger.log(Level.INFO, - OutboundMessageProcessor.mMessages.getString( - "DBBC_R00625.OMP_Exec_SQL") + sql); - - ps = connection.prepareStatement(sql); - - final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); - Probe denormalizationMeasurement = Probe.info(getClass(), - eBean.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); - - denormalizer.denormalizeOutbound(nMsg, getDBName(eBean, nMsg), - opMetaData, ps); - - if (denormalizationMeasurement != null) - denormalizationMeasurement.end(); - - rs = ps.executeQuery(); - } catch (final SQLException ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. - getSQLState() + " ErrorCode: " + ex.getErrorCode(); - throw new SQLException(msg); - } catch (final MessagingException ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } catch (final Exception ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } - return rs; - } - - /** - * @param nMsg - * @param eBean - * @param opMetaData - * @return - * @throws MessagingException - */ - protected int executeOutboundSQL(final NormalizedMessage nMsg, - final EndpointBean eBean, - final OperationMetaData opMetaData, - Connection connection) throws SQLException, MessagingException { - String sql = null; - int rowsUpdated = -1; - - try { - sql = opMetaData.getJDBCSql().getSql(); - mLogger.log(Level.INFO, mMessages.getString( - "DBBC_R00625.OMP_Exec_SQL") + sql); - - ps = connection.prepareStatement(sql); - - final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); - Probe denormalizationMeasurement = Probe.info(getClass(), - eBean.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); - - denormalizer.denormalizeOutbound(nMsg, getDBName(eBean, nMsg), - opMetaData, ps); - if (denormalizationMeasurement != null) - denormalizationMeasurement.end(); - - rowsUpdated = ps.executeUpdate(); - } catch (final SQLException ex) { - final String msg = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. - getSQLState() + " ErrorCode: " + ex.getErrorCode(); - throw new SQLException(msg); - } catch (final MessagingException ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } catch (final Exception ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } - return rowsUpdated; - } - - /* - * Added by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - /** - * @param nMsg - * @param eBean - * @param opMetaData - * @return - * @throws MessagingException - */ - protected String executeOutboundSQLWithGeneratedKeys(final NormalizedMessage nMsg, - final EndpointBean eBean, - final OperationMetaData opMetaData, - Connection connection) throws SQLException, MessagingException { - mLogger.log(Level.INFO, "Entering executeOutboundSQLWithGeneratedKeys"); - String sql = null; - int rowsUpdated = -1; - String generatedKeyValue = null; - - try { - sql = opMetaData.getJDBCSql().getSql(); - mLogger.log(Level.INFO, mMessages.getString( - "DBBC_R00625.OMP_Exec_SQL") + sql); - - String outputColumn = opMetaData.getJDBCSql().getGeneratedKey(); - - ps = connection.prepareStatement(sql, new String[]{outputColumn}); - - final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); - Probe denormalizationMeasurement = Probe.info(getClass(), - eBean.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); - - denormalizer.denormalizeOutbound(nMsg, getDBName(eBean, nMsg), - opMetaData, ps); - if (denormalizationMeasurement != null) - denormalizationMeasurement.end(); - - - rowsUpdated = ps.executeUpdate(); - ResultSet rs = ps.getGeneratedKeys(); - if (rs != null && rs.next()) - generatedKeyValue = rs.getString(1); - } catch (final SQLException ex) { - final String msg = mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. - getSQLState() + " ErrorCode: " + ex.getErrorCode(); - throw new SQLException(msg); - } catch (final MessagingException ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } catch (final Exception ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } - mLogger.log(Level.INFO, "Exiting executeOutboundSQLWithGeneratedKeys"); - return generatedKeyValue; - } - - /** - * @param nMsg - * @param eBean - * @param opMetaData - * @return - * @throws MessagingException - */ - protected CallableStatement executeOutboundProc(final NormalizedMessage nMsg, - final EndpointBean eBean, - final OperationMetaData opMetaData, - Connection connnection) throws SQLException, MessagingException { - String sql = null; - int rowsUpdated = -1; - - try { - sql = opMetaData.getJDBCSPOperationInput().getExecutionString(); - mLogger.log(Level.INFO, mMessages.getString( - "DBBC_R00625.OMP_Exec_SQL") + sql); - - cs = connnection.prepareCall(sql); - DatabaseMetaData dbmeta = connnection.getMetaData(); - - final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); - - if (eBean.getValue(EndpointBean.JDBC_DATABASE_NAME) != null) - denormalizer.setDatabaseName(eBean.getValue( - EndpointBean.JDBC_DATABASE_NAME)); - Probe denormalizationMeasurement = Probe.info(getClass(), - eBean.getUniqueName(), - JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); - denormalizer.denormalizeOutboundProc(nMsg, opMetaData, dbmeta, cs); - if (denormalizationMeasurement != null) - denormalizationMeasurement.end(); - - outParamIndex = denormalizer.getOutParamIndex(); - outParamTypes = denormalizer.getOutParamTypes(); - outParamNames = denormalizer.getOutParamNames(); - // rowsUpdated = cs.executeUpdate(); - boolean b = cs.execute(); - return cs; - } catch (final SQLException ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_R00624.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. - getSQLState() + " ErrorCode: " + ex.getErrorCode(); - throw new SQLException(msg); - } catch (final MessagingException ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } catch (final Exception ex) { - final String msg = OutboundMessageProcessor.mMessages.getString( - "DBBC_R00624.OMP_Failed_Exec_SQL") + sql + - " Reason: " + ex.getLocalizedMessage(); - throw new MessagingException(msg, ex); - } - - // return rowsUpdated; - } - - // resumes the transaction - private void resumeThreadTx(Transaction tx) throws Exception { - if (tx != null) { - ((TransactionManager) mContext.getContext().getTransactionManager()). - resume(tx); - mLogger.log(Level.INFO, " ", new Object[]{tx.toString()}); - } - } - - /** - * @param jndiName - * @return - * @throws javax.naming.NamingException - */ - private Object getDataSourceFromContext(final String jndiName) throws javax.naming.NamingException { - final Context c = mContext.getContext().getNamingContext(); - - return c.lookup(jndiName); - } - - /** - * @param jndiName - * @return - * @throws Exception - */ - private Connection getDatabaseConnection(final String jndiName) throws Exception { - final DataSource ds = (DataSource) getDataSourceFromContext(jndiName); - final Connection con = ds.getConnection(); - - return con; - } - - private Connection getDatabaseConnection(final EndpointBean epbean) throws Exception { - if (epbean.getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME) == null || epbean. - getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME).equals("")) { - final String driverClass = epbean.getValue( - EndpointBean.JDBC_DATABASE_DRIVER_CLASS); - final String dbURL = epbean.getValue(EndpointBean.JDBC_DATABASE_URL); - final String user = epbean.getValue(EndpointBean.JDBC_DATABASE_USER); - final String password = epbean.getValue( - EndpointBean.JDBC_DATABASE_PASSWORD); - // Thread.currentThread().getContextClassLoader().loadClass(driverClass).newInstance(); - Class.forName(driverClass).newInstance(); - - return DriverManager.getConnection(dbURL, user, password); - } else { - final DataSource ds = (DataSource) getDataSourceFromContext(epbean. - getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME)); - final Connection con = ds.getConnection(); - - return con; - } - } - - private Connection getDatabaseConnection(NormalizedMessage nm) - throws SQLException, NamingException { - Object p = nm.getProperty( - JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); - String jndiName = null; - Connection conn = null; - if (p != null) - jndiName = p.toString(); - if (jndiName != null) { - DataSource ds = (DataSource) getDataSourceFromContext(jndiName); - conn = ds.getConnection(); - } - return conn; - } - - private XAConnection getXADatabaseConnection(final EndpointBean epbean) throws Exception { - try { - final DataSource ds = (DataSource) getDataSourceFromContext(epbean. - getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME)); - if (ds instanceof XADataSource) { - XAConnection con = ((XADataSource) ds).getXAConnection(); - return con; - } - } catch (Exception e) { - if (mLogger.isLoggable(Level.FINEST)) - mLogger.log(Level.SEVERE, "Either the JNDI NAME is NULL or Could not establish connection using JNDI NAME :" + - EndpointBean.JDBC_DATABASE_JNDI_NAME, e); - else if (mLogger.isLoggable(Level.FINE)) - mLogger.log(Level.SEVERE, "Either the JNDI NAME is NULL or Could not establish connection using JNDI NAME :" + - EndpointBean.JDBC_DATABASE_JNDI_NAME + " Reason: " + e. - getLocalizedMessage()); - else if (mLogger.isLoggable(Level.INFO)) - mLogger.log(Level.SEVERE, - "Either the JNDI NAME is NULL or Could not establish connection using JNDI NAME :"); - } - return null; - } - - /** - * @param prepStmtSQLText - * @return - */ - private boolean isSelectStatement(final String prepStmtSQLText) { - prepStmtSQLText.trim(); - - final StringTokenizer tok = new StringTokenizer(prepStmtSQLText); - - if (tok.hasMoreTokens()) { - final String firstTok = (String) tok.nextToken(); - - if (firstTok.equalsIgnoreCase("select")) - return true; - } - - return false; - } - - /* - * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted - */ - /** - * @param prepStmtSQLText - * @return - */ - private boolean isInsertStatement(final String prepStmtSQLText) { - prepStmtSQLText.trim(); - - final StringTokenizer tok = new StringTokenizer(prepStmtSQLText); - - if (tok.hasMoreTokens()) { - final String firstTok = (String) tok.nextToken(); - - if (firstTok.equalsIgnoreCase("insert")) - return true; - } - - return false; - } - - private TransactionManager getTransactionManager() { - return (TransactionManager) mContext.getContext().getTransactionManager(); - } - - private boolean processException(final Exception ex, Transaction transaction, - final MessageExchange inonly, final EndpointBean epb, - String faultCode, String faultDetail) { - boolean success = false; - mLogger.log(Level.WARNING, OutboundMessageProcessor.mMessages.getString( - "DBBC_E00622.OMP_Failed_writing"), ex); - - try { - if (transaction != null) - transaction.setRollbackOnly(); - } catch (javax.transaction.SystemException e) { - //ignore since the code below will take care of setting error on ME. - } - faultCode = CLIENT; - faultDetail = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize"); - String faultString = mMessages.getString( - "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{inonly. - getExchangeId(), epb.getValue(EndpointBean.ENDPOINT_NAME), inonly. - getOperation(). - toString()}); - setErrorInExchange(inonly, faultCode, faultDetail, ex); - try { - inonly.setStatus(ExchangeStatus.ERROR); - } catch (MessagingException mex) { - //ignore - } - return success; - } - - private void updateTallyReceivedReplies(EndpointBean e) { - if (e != null) { - EndpointStatus status = e.getEndpointStatus(); - if (status != null) - status.incrementReceivedReplies(); - } - } - - private void updateTallyReceivedRequests(EndpointBean e) { - if (e != null) { - EndpointStatus status = e.getEndpointStatus(); - if (status != null) - status.incrementReceivedRequests(); - } - } - - private void updateTallySentReplies(EndpointBean e) { - if (e != null) { - EndpointStatus status = e.getEndpointStatus(); - if (status != null) - status.incrementSentReplies(); - } - } - - private void updateTallySentRequests(EndpointBean e) { - if (e != null) { - EndpointStatus status = e.getEndpointStatus(); - if (status != null) - status.incrementSentRequests(); - } - } - - private void updateTallyReceives(EndpointBean e, boolean successfulReceive) { - if (e != null) { - EndpointStatus status = e.getEndpointStatus(); - if (status != null) - if (successfulReceive) - status.incrementReceivedDones(); - else - status.incrementReceivedErrors(); - } - } - - private void updateTallySends(EndpointBean e, boolean successfulSend) { - if (e != null) { - EndpointStatus status = e.getEndpointStatus(); - if (status != null) - if (successfulSend) - status.incrementSentDones(); - else - status.incrementSentErrors(); - } - } - - private String getDBName(EndpointBean eBean, NormalizedMessage nMsg) - throws javax.naming.NamingException, java.sql.SQLException { - if (eBean.getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME) == null || eBean. - getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME).equals("")) - return dbConnectionInfo.getDataBaseName(eBean.getValue( - EndpointBean.JDBC_DATABASE_URL), null, null); - else { - String jndiName = eBean.getValue( - EndpointBean.JDBC_DATABASE_JNDI_NAME); - if (nMsg.getProperty( - JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME) != null) - jndiName = nMsg.getProperty( - JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME). - toString(); - return dbConnectionInfo.getDataBaseName(null, null, - (DataSource) getDataSourceFromContext(jndiName)); - - } - } - - private void setErrorInExchange(MessageExchange ex, String faultCode, - String faultDetail, Exception e) { - ex.setError(e); - ex.setProperty("com.sun.jbi.crl.faultcode", faultCode); - ex.setProperty("com.sun.jbi.crl.faultstring", e.getMessage()); - ex.setProperty("com.sun.jbi.crl.faultactor", "sun-database-binding"); - ex.setProperty("com.sun.jbi.crl.faultdetail", - faultDetail + e.getMessage()); - } -} +/* + * BEGIN_HEADER - DO NOT EDIT + * + * The contents of this file are subject to the terms + * of the Common Development and Distribution License + * (the "License"). You may not use this file except + * in compliance with the License. + * + * You can obtain a copy of the license at + * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. + * See the License for the specific language governing + * permissions and limitations under the License. + * + * When distributing Covered Code, include this CDDL + * HEADER in each file and include the License file at + * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. + * If applicable add the following below this CDDL HEADER, + * with the fields enclosed by brackets "[]" replaced with + * your own identifying information: Portions Copyright + * [year] [name of copyright owner] + */ + +/* + * @(#)OutboundMessageProcessor.java + * + * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. + * + * END_HEADER - DO NOT EDIT + */ +package org.glassfish.openesb.databasebc; + +import com.sun.jbi.alerter.NotificationEvent; +import com.sun.jbi.nms.exchange.ExchangePattern; +import org.glassfish.openesb.databasebc.extensions.JDBCOperationInput; +import java.net.URI; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.jbi.servicedesc.ServiceEndpoint; +import javax.jbi.messaging.*; +import javax.naming.Context; +import javax.naming.NamingException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import com.sun.jbi.internationalization.Messages; +import org.glassfish.openesb.databasebc.transaction.*; + +import javax.transaction.xa.XAResource; +import org.glassfish.openesb.databasebc.model.runtime.DBConnectionInfo; +import javax.sql.*; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; + +import com.sun.jbi.common.qos.messaging.MessagingChannel; +import com.sun.jbi.common.descriptor.EndpointInfo; +import com.sun.jbi.common.qos.redelivery.Redelivery; +import com.sun.jbi.common.qos.redelivery.RedeliveryConfig; +import com.sun.jbi.common.qos.redelivery.RedeliveryStatus; +import org.glassfish.openesb.databasebc.util.AlertsUtil; +import com.sun.jbi.eManager.provider.EndpointStatus; +import org.glassfish.openesb.databasebc.extensions.SPOperationInput; + +import net.java.hulp.measure.Probe; + +/** + * Process replies/requests received from the SE. + */ +public class OutboundMessageProcessor implements Runnable { + + private static final Messages mMessages = Messages.getMessages( + OutboundMessageProcessor.class); + private static final Logger mLogger = Messages.getLogger( + OutboundMessageProcessor.class); + Map mEndpoints; + DocumentBuilder mDocBuilder; + private MessagingChannel mChannel; + private MessageExchange mExchange; + private JDBCComponentContext mContext; + private Map mInboundExchanges; + DBConnectionInfo dbConnectionInfo; + XAConnection xaConnection = null; + private String mXAEnabled = null; + Connection connection = null; + PreparedStatement ps = null; + ResultSet rs = null; + CallableStatement cs = null; + //private TransactionManager mTxManager = null; + private XidImpl xid = null; + TransactionHelper mtxHelper = null; + private boolean mtxFlag; + XAResource xaResource = null; + // Settings for custom reliability header extensions + public static final String CUSTOM_RELIABILITY_MESSAGE_ID_PROPERTY = + "com.stc.jbi.messaging.messageid"; // NOI18N + public static final String CUSTOM_RELIABILITY_HEADER_NAMESPACE_URI = + "http://schemas.stc.com/ws/2005/07/custrm"; // NOI18N + public static final String CUSTOM_RELIABILITY_HEADER_LOCAL_NAME = + "MessageID"; // NOI18N + /** + * JBI message exchange properties for message grouping and sequencing (new CRMP) + */ + public static final String CRMP_GROUP_ID = "com.sun.jbi.messaging.groupid"; + public static final String CRMP_MESSAGE_ID = + "com.sun.jbi.messaging.messageid"; + private static final String CLIENT = "Client"; + private static final String SERVER = "Server"; + private ReplyListener replyListener = null; + private ArrayList outParamIndex = new ArrayList(); + private HashMap outParamTypes = + new HashMap(); + private HashMap outParamNames = + new HashMap(); + + protected OutboundMessageProcessor(final MessagingChannel chnl, final MessageExchange exchange, final Map endpoints, + final JDBCComponentContext context, final Map inboundMessageExchanges) throws ParserConfigurationException { + mChannel = chnl; + mEndpoints = endpoints; + mExchange = exchange; + mContext = context; + mInboundExchanges = inboundMessageExchanges; + //mTxManager = (TransactionManager) context.getTransactionManager(); + + final DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory. + newInstance(); + mDocBuilder = docBuilderFact.newDocumentBuilder(); + // mtxHelper = new TransactionHelper(); + dbConnectionInfo = new DBConnectionInfo(); + } + + /** + * + */ + //@Override + public void run() { + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.FINEST, "DBBC_R00606.OMP_Accept_msg", mExchange. + getExchangeId()); + else if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, "DBBC_R00630.OMP_Accept_msg"); + + try { + execute(); + } catch (final Exception ex) { + mLogger.log(Level.SEVERE, OutboundMessageProcessor.mMessages.getString( + "DBBC_E00607.OMP_Unexpected_exception", ex.getLocalizedMessage()), + ex); + String text = mMessages.getString( + "DBBC_E00607.OMP_Unexpected_exception", ex.getLocalizedMessage()); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00607"); + } + + if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.INFO, "DBBC_R00608.OMP_Complete_processing"); + } + + /** + * Process the message exchange + */ + public void execute() { + if (mExchange != null) { + final String exchangeId = mExchange.getExchangeId(); + + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, "DBBC_R00606.OMP_Accept_msg", exchangeId); + else if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, "DBBC_R00630.OMP_Accept_msg"); + + final boolean inbound = mInboundExchanges.containsKey(exchangeId); + final ListenerMeta listenerMeta = (ListenerMeta) mInboundExchanges.get( + exchangeId); + MessageExchangeReplyListener listener = null; + + if (listenerMeta != null) + listener = listenerMeta.getMessageExchangeReplyListener(); + + if (inbound) { + final long invocationTime = listenerMeta.getRequestInvocationTime(); + + final long difference = + System.currentTimeMillis() - invocationTime; + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, "DBBC_R00609.OMP_Resp_Ex", + new Object[]{exchangeId, + difference}); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.INFO, "DBBC_R00631.OMP_Resp_Ex", + new Object[]{exchangeId}); + } + + final URI pattern = mExchange.getPattern(); + + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, "DBBC_R00610.OMP_Pattern", + new Object[]{exchangeId, pattern}); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.INFO, "DBBC_R00632.OMP_Pattern", + new Object[]{pattern}); + + ServiceEndpoint serviceEndpoint = Redelivery.getEndpoint(mExchange); + final String serviceName = + serviceEndpoint.getServiceName().toString(); + final String endpointName = serviceEndpoint.getEndpointName(); + + if (mLogger.isLoggable(Level.FINE)) + mLogger.fine("Gettin bean for " + serviceName + endpointName); + + String epName = null; + + if (inbound) + epName = EndpointBean.getUniqueName(serviceName, endpointName, + EndpointBean.ENDPOINT_TYPE_INBOUND); + else + epName = EndpointBean.getUniqueName(serviceName, endpointName, + EndpointBean.ENDPOINT_TYPE_OUTBOUND); + + final EndpointBean epb = (EndpointBean) mEndpoints.get(epName); + + + + // Create a reply listener and add the ME Support for the same + if (replyListener == null) + replyListener = new ReplyListenerImpl(epb); + MessageExchangeSupport.addReplyListener(exchangeId, replyListener, + epb); + + final String status = epb.getValue(EndpointBean.STATUS); + + if (!status.equals(EndpointBean.STATUS_RUNNING)) { + // If the endpoint is not in the RUNNING state (i.e. is stopped + // or + // shutdown), ignore the message + if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.INFO, "DBBC_R00611.OMP_EP_state"); + } else + switch (ExchangePattern.valueOf(mExchange)) { + case IN_OUT: + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, "DBBC_R00612.OMP_Recv_InOut", + mExchange.getExchangeId()); + else if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, "DBBC_R00612.OMP_Recv_InOut", + ""); + if (mExchange.isTransacted()) { + // Start of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.EnterContext").fine( + "context"); + processInOutXA((InOut) mExchange, epb); + // End of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.ExitContext").fine( + "context"); + } else { + // Start of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.EnterContext").fine( + "context"); + processInOut((InOut) mExchange, epb); + // End of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.ExitContext").fine( + "context"); + } + break; + case IN_ONLY: + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.FINE, + "DBBC_R00613.OMP_Recv_InOnly", mExchange.getExchangeId()); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.INFO, + "DBBC_R00613.OMP_Recv_InOnly", ""); + + if (inbound) { + // Start of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.EnterContext").fine( + "context"); + processInOnlyInbound((InOnly) mExchange, epb, + listener); + // End of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.ExitContext").fine( + "context"); + } else { + // Start of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.EnterContext").fine( + "context"); + processInOnly((InOnly) mExchange, epb); + // End of nested diagnostic context prior to processing of message + Logger.getLogger("com.sun.ExitContext").fine( + "context"); + } + break; + case ROBUST_IN_ONLY: + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.WARNING, + "DBBC_W00614.OMP_Not_supported_inonly", + mExchange.getExchangeId()); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_W00614.OMP_Not_supported_inonly", ""); + break; + case IN_OPTIONAL_OUT: + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.WARNING, + "DBBC_W00615.OMP_Not_supported_outin", + mExchange.getExchangeId()); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_W00615.OMP_Not_supported_outin", ""); + break; + default: + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.WARNING, + "DBBC_W00617.OMP_Invalid_pattern", + exchangeId); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_W00617.OMP_Invalid_pattern", ""); + return; + } + } // if(exchange) + } + + /** + * @param inonly + * @param endpoint + * @param listener + */ + protected void processInOnlyInbound(final InOnly inonly, + final EndpointBean endpoint, + final MessageExchangeReplyListener listener) { + mLogger.info("DBBC_R00618.OMP_Processing_InOnly_inbound"); + + if (inonly.getStatus() == ExchangeStatus.DONE) + updateTallyReceives(endpoint, true); + else if (inonly.getStatus() == ExchangeStatus.ERROR) { + RedeliveryStatus retryStatus = + Redelivery.getRedeliveryStatus(inonly); + if (retryStatus != null && !retryStatus.hasFailed()) + try { + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E01037.Redelivering_message", + new Object[]{retryStatus.getRemainingRetries()}); + mLogger.log(Level.WARNING, text); + + } + MessageExchangeSupport.notifyOfRedelivery(inonly); + } catch (Exception e) { + String groupId = (String) inonly.getProperty(CRMP_GROUP_ID); + String messageId = (String) inonly.getProperty( + CRMP_MESSAGE_ID); + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E01036.Failed_to_process_redelivery", + new Object[]{groupId, messageId}); + mLogger.log(Level.WARNING, text, e); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + endpoint.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E01036"); + } + } + else + try { + // No more retries...handle all the recourse actions. Only one that we need to handle in + // a BC-specific way is the suspending of endpoints + suspendEndpoint(inonly, endpoint); + + listener.processReplyMessage(inonly); + } catch (final Exception ex) { + mLogger.log(Level.SEVERE, + "DBBC_E00619.OMP_Failed_processing_inonly_inbound", + ex); + } + updateTallyReceives(endpoint, false); + String msg = mMessages.getString( + "DBBC_E00619.OMP_Failed_processing_inonly_inbound", + new Object[]{inonly.getEndpoint().getServiceName(), + inonly.getEndpoint().getEndpointName(), + inonly.getOperation()}); + + mLogger.log(Level.WARNING, msg); + return; + } else if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.WARNING, + "DBBC_W00620.OMP_Unexpected_ME_status", new Object[]{ + inonly.getEndpoint(), inonly.getStatus()}); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.WARNING, + "DBBC_W00633.OMP_Unexpected_ME_status", + new Object[]{inonly.getEndpoint()}); + + try { + listener.processReplyMessage(inonly); + } catch (final Exception ex) { + mLogger.log(Level.SEVERE, + "DBBC_E00619.OMP_Failed_processing_inonly_inbound", ex); + } + } + + private void suspendEndpoint(InOnly inonly, EndpointBean endpoint) throws Exception { + + ServiceEndpoint serviceEndpoint = Redelivery.getEndpoint(inonly); + + EndpointInfo endpointInfo = EndpointInfo.valueOf( + serviceEndpoint, + false); // false = consumer endpoint + + RedeliveryConfig config = + mContext.getBindingChannel().getServiceQuality( + endpointInfo, RedeliveryConfig.class); + + if (config != null && config.getFailure() == RedeliveryConfig.Failure.suspend) + // Suspend endpoint. + mContext.getDeployer().suspend(endpoint); + } + + /** + * @param inout + * @param epb + */ + protected void processInOut(final InOut inout, final EndpointBean epb) { + Connection connection = null; + String faultCode = null; + String faultDetail = null; + boolean success = true; + if (inout.getStatus() == ExchangeStatus.DONE) { + + // remove the redelivery listener handler - no retry needed. + MessageExchangeSupport.removeReplyListener(inout.getExchangeId()); + + updateTallyReceives(epb, true); + } else if (inout.getStatus() == ExchangeStatus.ERROR) { + + // added for retry support + + updateTallyReceives(epb, false); + + // send alerts + String errorMsg = inout.getError().getMessage(); + if (errorMsg != null) { + String msg = mMessages.getString( + "DBBC-E00720.Message_exchange_error", + new Object[]{ + String.valueOf(inout.getService()), + inout.getEndpoint().getEndpointName(), + errorMsg + }); + mLogger.log(Level.SEVERE, msg); + AlertsUtil.getAlerter().warning(msg, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00720"); + } else { + String msg = mMessages.getString( + "DBBC-E00721.Message_exchange_error_no_detail", + new Object[]{ + String.valueOf(inout.getService()), + inout.getEndpoint().getEndpointName() + }); + mLogger.log(Level.SEVERE, msg); + AlertsUtil.getAlerter().warning(msg, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00721"); + } + /** + // let's see if retry is configured or not + EndpointInfo info = new EndpointInfo(false, + epb.getEndpointName(), + null, + epb.getServiceName(), + null); + RedeliveryConfig retryConfig = mChannel.getServiceQuality(info, RedeliveryConfig.class); + **/ + RedeliveryStatus retryStatus = Redelivery.getRedeliveryStatus(inout); + if (retryStatus != null && retryStatus.getRemainingRetries() > 0) + try { + MessageExchangeSupport.notifyOfRedelivery(inout); + } catch (Exception e) { + String groupId = (String) inout.getProperty(CRMP_GROUP_ID); + String messageId = (String) inout.getProperty( + CRMP_MESSAGE_ID); + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E01036.Failed_to_process_redelivery", + new Object[]{groupId, messageId}); + mLogger.log(Level.WARNING, text, e); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E01036"); + } + } + + //epb.getEndpointStatus().incrementReceivedErrors(); + } else { + + // added for retry support + try { + MessageExchangeSupport.notifyOfReply(inout); + } catch (Exception ex) { + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E00759.Exception_during_reply_processing", ex. + getLocalizedMessage()); + mLogger.log(Level.SEVERE, text, ex); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00759"); + } + success = false; + } + + try { + updateTallyReceivedRequests(epb); + Map operationNameToMetaData = (Map) epb.getValueObj( + EndpointBean.OPERATION_NAME_TO_META_DATA); + OperationMetaData meta = (OperationMetaData) operationNameToMetaData.get(inout.getOperation(). + getLocalPart()); + + if (meta == null) + throw new MessagingException(mMessages.getString( + "DBBC_E00621.OMP_oper_NotDefined") + inout.getOperation()); + + final NormalizedMessage inMsg = inout.getInMessage(); + NormalizedMessage outMsg = mExchange.createMessage(); + //boolean success = true; + String statusMessage = ""; + + try { + rs = null; + int rowsUpdated = -1; + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + String generatedKeyValue = ""; + String outputValue = ""; + + // writeMessage(inMsg, destinationAddress, false); + JDBCOperationInput input = meta.getJDBCSql(); + if (input != null) { + final String sql = input.getSql(); + Object jndiNameObj = + inMsg.getProperty( + JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); + try { + if (jndiNameObj != null) { + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); + connection = getDatabaseConnection(inMsg); + } else { + String jndiName = epb.getValue( + EndpointBean.JDBC_DATABASE_JNDI_NAME); + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiName); + connection = getDatabaseConnection(epb); + } + } catch (Exception e) { + faultCode = SERVER; + faultDetail = "Unable to get connection : " + e.toString(); + String faultString = mMessages.getString( + "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString()}); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00627"); + throw new Exception(faultString, e); + } + if (isSelectStatement(sql)) { + try { + rs = executeOutboundSQLSelect(inMsg, epb, meta, + connection); + } catch (final SQLException ex) { + faultCode = SERVER; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + ex. + getLocalizedMessage(); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation(), ex.getLocalizedMessage()}); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00706"); + throw new Exception(faultString, ex); + } catch (final Exception ex) { + faultCode = CLIENT; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + ex. + getLocalizedMessage(); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation(), ex.getLocalizedMessage()}); + throw new Exception(faultString, ex); + } + + if (rs != null) + statusMessage = "Success : ResultSet returned "; + + final JDBCNormalizer normalizer = + new JDBCNormalizer(); + Probe normalizationMeasurement = null; + try { + normalizationMeasurement = + Probe.info(getClass(), + epb.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); + + outMsg = normalizer.normalizeSelect(rs, inout, + meta, connection.getMetaData(). + getDriverName()); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString()}); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00702"); + throw new Exception(faultString, e); + } finally { + if (normalizationMeasurement != null) + normalizationMeasurement.end(); + } + } else { + try { + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + String generatedKey = meta.getJDBCSql(). + getGeneratedKey(); + if (isInsertStatement(sql) && generatedKey != null && !"".equals( + generatedKey)) { + generatedKeyValue = + executeOutboundSQLWithGeneratedKeys( + inMsg, epb, meta, connection); + outputValue = generatedKeyValue; + statusMessage = + "Success : Generated Key = " + generatedKeyValue; + } else { + rowsUpdated = executeOutboundSQL(inMsg, epb, + meta, connection); + statusMessage = + "Success : " + rowsUpdated + " are updated ."; + outputValue = String.valueOf(rowsUpdated); + } + } catch (final SQLException ex) { + faultCode = SERVER; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString(), ex. + getLocalizedMessage()}); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00706"); + throw new Exception(faultString, ex); + } catch (final Exception ex) { + faultCode = CLIENT; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString()}); + throw new Exception(faultString, ex); + } + + + final JDBCNormalizer normalizer = + new JDBCNormalizer(); + Probe normalizationMeasurement = null; + try { + normalizationMeasurement = + Probe.info(getClass(), + epb.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + outMsg = + normalizer.normalize(outputValue, inout, + meta); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = + mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM", + new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString(), e. + getLocalizedMessage()}); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00702"); + throw new Exception(faultString, e); + } finally { + if (normalizationMeasurement != null) + normalizationMeasurement.end(); + } + } + inout.setOutMessage(outMsg); + } else { + SPOperationInput spInput = + meta.getJDBCSPOperationInput(); + if (spInput != null) { + Object jndiNameObj = + inMsg.getProperty( + JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); + try { + if (jndiNameObj != null) { + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); + connection = getDatabaseConnection(inMsg); + } else { + String jndiName = + epb.getValue( + EndpointBean.JDBC_DATABASE_JNDI_NAME); + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiName); + connection = getDatabaseConnection(epb); + } + } catch (Exception e) { + faultCode = SERVER; + faultDetail = "Unable to get connection : " + e.toString(); + String faultString = + mMessages.getString( + "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString()}); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00627"); + throw new Exception(faultString, e); + } + cs = executeOutboundProc(inMsg, epb, meta, + connection); + final JDBCNormalizer normalizer = + new JDBCNormalizer(); + final JDBCDenormalizer denormalizer = + new JDBCDenormalizer(); + if (connection.getMetaData().getDatabaseProductName(). + toLowerCase().contains("sql server") || connection. + getMetaData().getDatabaseProductName(). + toLowerCase().contains("adaptive server")) + if (outParamIndex.size() == 0) { + outParamNames.put(1, denormalizer.getProcName(meta. + getJDBCSPOperationInput(). + getExecutionString())); + outParamTypes.put(1, "RESULTSET"); + outParamIndex.add( + Integer.valueOf(Double.valueOf(1).intValue())); + } /*else + for (int i = 1; i <= outParamIndex.size(); i++) + if ((outParamNames.get(i) != null) && (outParamNames.get(i). + equalsIgnoreCase( + "RETURN_VALUE"))) { + outParamNames.put(i, denormalizer.getProcName(meta. + getJDBCSPOperationInput(). + getExecutionString())); + outParamTypes.put(i, "RETURN_VALUE"); + }*/ + normalizer.setOutParamIndex(outParamIndex); + normalizer.setOutParamNames(outParamNames); + normalizer.setOutParamTypes(outParamTypes); + Probe normalizationMeasurement = null; + try { + normalizationMeasurement = + Probe.info(getClass(), + epb.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); + outMsg = normalizer.normalizeProcedure(cs, inout, meta, connection.getMetaData(). + getDatabaseProductName().toLowerCase()); + } catch (final SQLException ex) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = mMessages.getString( + "DBBC_E00727.JDBCN_Failed_NM_SQL", new Object[]{ + ex.getClass().getName(), + ex.getLocalizedMessage() + }); + throw new Exception(faultString, ex); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = + mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString()}); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00702"); + throw new Exception(faultString, e); + } finally { + if (normalizationMeasurement != null) + normalizationMeasurement.end(); + + } + inout.setOutMessage(outMsg); + + } + } + } catch (final Exception ex) { + mLogger.log(Level.SEVERE, + mMessages.getString("DBBC_E00622.OMP_Failed_writing"), + ex); + // should this populate a full fault instead? + AlertsUtil.getAlerter().warning(mMessages.getString( + "DBBC_E00622.OMP_Failed_writing"), + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00622"); + // inout.setError(ex); + statusMessage = "Failed " + ex.getMessage(); + success = false; + setErrorInExchange(inout, faultCode, faultDetail, ex); + inout.setStatus(ExchangeStatus.ERROR); + + } + + mChannel.send(inout); + + if (success) + updateTallySentReplies(epb); + else + epb.getEndpointStatus().incrementSentErrors(); + } catch (final Exception ex) { + mLogger.log(Level.SEVERE, + mMessages.getString("DBBC_E00623.OMP_Failed_inout"), ex); + throw new RuntimeException(ex); + } finally { + try { + if (rs != null) + rs.close(); + if (cs != null) + cs.close(); + if (ps != null) + ps.close(); + if (connection != null) + connection.close(); + } catch (SQLException sqlexception) { + mLogger.log(Level.SEVERE, + mMessages.getString( + "DBBC_E00628.OMP_Cleanup_Failure"), + sqlexception); + } + } + } + } + + private void processInOutXA(final InOut inout, final EndpointBean epb) { + mLogger.log(Level.INFO, "Entering processInOutXA"); + XAConnection xaconnection = null; + Transaction transaction = null; + String faultCode = null; + String faultDetail = null; + boolean success = true; + + if (inout.getStatus() == ExchangeStatus.DONE) { + + // remove the redelivery listener handler - no retry needed. + MessageExchangeSupport.removeReplyListener(inout.getExchangeId()); + + updateTallyReceives(epb, true); + } else if (inout.getStatus() == ExchangeStatus.ERROR) { + + // added for retry support + + updateTallyReceives(epb, false); + + // send alerts + String errorMsg = inout.getError().getMessage(); + if (errorMsg != null) { + String msg = mMessages.getString( + "DBBC-E00720.Message_exchange_error", + new Object[]{ + String.valueOf(inout.getService()), + inout.getEndpoint().getEndpointName(), + errorMsg + }); + mLogger.log(Level.SEVERE, msg); + AlertsUtil.getAlerter().warning(msg, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00720"); + } else { + String msg = mMessages.getString( + "DBBC-E00721.Message_exchange_error_no_detail", + new Object[]{ + String.valueOf(inout.getService()), + inout.getEndpoint().getEndpointName() + }); + mLogger.log(Level.SEVERE, msg); + AlertsUtil.getAlerter().warning(msg, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00721"); + } + /** + // let's see if retry is configured or not + EndpointInfo info = new EndpointInfo(false, + epb.getEndpointName(), + null, + epb.getServiceName(), + null); + RedeliveryConfig retryConfig = mChannel.getServiceQuality(info, RedeliveryConfig.class); + **/ + RedeliveryStatus retryStatus = Redelivery.getRedeliveryStatus(inout); + if (retryStatus != null && retryStatus.getRemainingRetries() > 0) + try { + MessageExchangeSupport.notifyOfRedelivery(inout); + } catch (Exception e) { + String groupId = (String) inout.getProperty(CRMP_GROUP_ID); + String messageId = (String) inout.getProperty( + CRMP_MESSAGE_ID); + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E01036.Failed_to_process_redelivery", + new Object[]{groupId, messageId}); + mLogger.log(Level.WARNING, text, e); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E01036"); + } + } + + //epb.getEndpointStatus().incrementReceivedErrors(); + } else { + + // added for retry support + try { + MessageExchangeSupport.notifyOfReply(inout); + } catch (Exception ex) { + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E00759.Exception_during_reply_processing", ex. + getLocalizedMessage()); + mLogger.log(Level.SEVERE, text, ex); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00759"); + } + success = false; + } + + try { + updateTallyReceivedRequests(epb); + Map operationNameToMetaData = (Map) epb.getValueObj( + EndpointBean.OPERATION_NAME_TO_META_DATA); + OperationMetaData meta = (OperationMetaData) operationNameToMetaData.get(inout.getOperation(). + getLocalPart()); + + if (meta == null) + throw new MessagingException(mMessages.getString( + "DBBC_E00621.OMP_oper_NotDefined") + inout.getOperation()); + + final NormalizedMessage inMsg = inout.getInMessage(); + NormalizedMessage outMsg = mExchange.createMessage(); + + String statusMessage = ""; + String jndiName = null; + + try { + rs = null; + int rowsUpdated = -1; + + String generatedKeyValue = ""; + String outputValue = ""; + + // writeMessage(inMsg, destinationAddress, false); + JDBCOperationInput input = meta.getJDBCSql(); + if (input != null) { + final String sql = input.getSql(); + jndiName = epb.getValue( + EndpointBean.JDBC_DATABASE_JNDI_NAME); + + if (inout.isTransacted()) + // Removing manual enlistment. Moving to automatic resource enlistment + // mtxHelper.handleOutbound(mExchange); + // enlistResource(epb); + transaction = + (Transaction) inout.getProperty( + MessageExchange.JTA_TRANSACTION_PROPERTY_NAME); + if (transaction != null) + resumeThreadTx(transaction); + + try { + connection = getDatabaseConnection(epb); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = "Unable to get connection : " + e.toString(); + String faultString = mMessages.getString( + "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString()}); + AlertsUtil.getAlerter().warning(mMessages.getString( + "DBBC_E00627.OMP_Failed_LookUp_JNDI"), + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00627"); + throw new Exception(faultString, e); + } + connection.setAutoCommit(true); + + + /* PP: Glassfish does not return a XADataSource and always returns + * a DataSource30 object which does not implement getXAResource() method + xaconnection = getXADatabaseConnection(epb); + XAResource xaresource = xaconnection.getXAResource(); + transaction.enlistResource(xaresource); + connection = xaconnection.getConnection();*/ + + if (isSelectStatement(sql)) { + try { + rs = executeOutboundSQLSelect(inMsg, epb, meta, + connection); + } catch (final SQLException ex) { + faultCode = SERVER; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString(), ex. + getLocalizedMessage() + }); + processException(ex, transaction, inout, epb, + faultCode, faultDetail); + AlertsUtil.getAlerter().warning(faultDetail, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00626"); + throw new Exception(faultString, ex); + } catch (final Exception ex) { + faultCode = CLIENT; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString() + }); + processException(ex, transaction, inout, epb, + faultCode, faultDetail); + throw new Exception(faultString, ex); + } + if (rs != null) + statusMessage = "Success : ResultSet returned "; + + final JDBCNormalizer normalizer = + new JDBCNormalizer(); + Probe normalizationMeasurement = null; + + try { + normalizationMeasurement = + Probe.info(getClass(), + epb.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); + + outMsg = normalizer.normalizeSelect(rs, inout, + meta, connection.getMetaData(). + getDriverName()); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString(), e.getLocalizedMessage() + }); + processException(e, transaction, inout, epb, + faultCode, faultDetail); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00702"); + throw new Exception(faultString, e); + } finally { + if (normalizationMeasurement != null) + normalizationMeasurement.end(); + } + inout.setOutMessage(outMsg); + } else { + if (meta.getJDBCOperationInput().getOperationType(). + equalsIgnoreCase(JDBCOperations.OPERATION_TYPE_EXECUTE. + toString())) { + try { + cs = executeOutboundProc(inMsg, epb, meta, + connection); + } catch (final SQLException ex) { + faultCode = SERVER; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString(), ex. + getLocalizedMessage() + }); + processException(ex, transaction, inout, epb, + faultCode, faultDetail); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00626"); + throw new Exception(faultString, ex); + } catch (final Exception ex) { + faultCode = CLIENT; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString() + }); + processException(ex, transaction, inout, epb, + faultCode, faultDetail); + throw new Exception(faultString, ex); + } + final JDBCNormalizer normalizer = + new JDBCNormalizer(); + Probe normalizationMeasurement = null; + try { + normalizationMeasurement = + Probe.info(getClass(), + epb.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); + outMsg = normalizer.normalizeProcedure(cs, + inout, meta, connection.getMetaData(). + getDatabaseProductName()); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString() + }); + processException(e, transaction, inout, epb, + faultCode, faultDetail); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00702"); + throw new Exception(faultString, e); + } finally { + if (normalizationMeasurement != null) + normalizationMeasurement.end(); + } + } else { + try { + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + String generatedKey = meta.getJDBCSql(). + getGeneratedKey(); + if (isInsertStatement(sql) && generatedKey != null && !"". + equals(generatedKey)) { + generatedKeyValue = + executeOutboundSQLWithGeneratedKeys( + inMsg, epb, meta, connection); + outputValue = generatedKeyValue; + statusMessage = + "Success : Generated Key = " + generatedKeyValue; + } else { + rowsUpdated = executeOutboundSQL(inMsg, + epb, meta, connection); + statusMessage = + "Success : " + rowsUpdated + " are updated ."; + outputValue = + String.valueOf(rowsUpdated); + } + } catch (final SQLException ex) { + faultCode = SERVER; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString(), ex. + getLocalizedMessage() + }); + processException(ex, transaction, inout, epb, + faultCode, faultDetail); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00706"); + } catch (final Exception ex) { + faultCode = CLIENT; + faultDetail = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString() + }); + processException(ex, transaction, inout, epb, + faultCode, faultDetail); + throw new Exception(faultString, ex); + } + + + final JDBCNormalizer normalizer = + new JDBCNormalizer(); + Probe normalizationMeasurement = null; + try { + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + outMsg = normalizer.normalize(outputValue, + inout, meta); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + inout.getOperation().toString() + }); + AlertsUtil.getAlerter().warning(faultString, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + null, + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC_E00702"); + processException(e, transaction, inout, epb, + faultCode, faultDetail); + throw new Exception(faultString, e); + } finally { + if (normalizationMeasurement != null) + normalizationMeasurement.end(); + } + } + inout.setOutMessage(outMsg); + } + } else { + SPOperationInput spInput = + meta.getJDBCSPOperationInput(); + if (spInput != null) { + Object jndiNameObj = + inMsg.getProperty( + JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); + if (inout.isTransacted()) + // Removing manual enlistment. Moving to automatic resource enlistment + // mtxHelper.handleOutbound(mExchange); + // enlistResource(epb); + transaction = + (Transaction) inout.getProperty( + MessageExchange.JTA_TRANSACTION_PROPERTY_NAME); + if (transaction != null) + resumeThreadTx(transaction); + try { + if (jndiNameObj != null) { + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); + connection = getDatabaseConnection(inMsg); + } else { + jndiName = + epb.getValue( + EndpointBean.JDBC_DATABASE_JNDI_NAME); + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiName); + connection = getDatabaseConnection(epb); + } + } catch (Exception e) { + faultCode = SERVER; + faultDetail = "Unable to get connection : " + e.toString(); + String faultString = + mMessages.getString( + "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString()}); + processException(e, transaction, inout, epb, + faultCode, faultDetail); + throw new Exception(faultString, e); + } + connection.setAutoCommit(true); + cs = executeOutboundProc(inMsg, epb, meta, + connection); + final JDBCNormalizer normalizer = + new JDBCNormalizer(); + final JDBCDenormalizer denormalizer = + new JDBCDenormalizer(); + if (connection.getMetaData().getDatabaseProductName(). + toLowerCase().contains("sql server") || connection. + getMetaData().getDatabaseProductName(). + toLowerCase().contains("adaptive server")) + if (outParamIndex.size() == 0) { + outParamNames.put(1, denormalizer.getProcName(meta. + getJDBCSPOperationInput(). + getExecutionString())); + outParamTypes.put(1, "RESULTSET"); + outParamIndex.add( + Integer.valueOf(Double.valueOf(1).intValue())); + } else + for (int i = 1; i <= outParamIndex.size(); i++) + if ((outParamNames.get(i) != null) && (outParamNames.get(i). + equalsIgnoreCase( + "RETURN_VALUE"))) { + outParamNames.put(i, denormalizer.getProcName(meta. + getJDBCSPOperationInput(). + getExecutionString())); + outParamTypes.put(i, "RESULTSET"); + } + normalizer.setOutParamIndex(outParamIndex); + normalizer.setOutParamNames(outParamNames); + normalizer.setOutParamTypes(outParamTypes); + Probe normalizationMeasurement = null; + try { + normalizationMeasurement = + Probe.info(getClass(), + epb.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_NORMALIZATION); + outMsg = normalizer.normalizeProcedure(cs, inout, meta, connection.getMetaData(). + getDatabaseProductName().toLowerCase()); + } catch (Exception e) { + faultCode = SERVER; + faultDetail = + "Unable to normalize response from the external service."; + String faultString = + mMessages.getString( + "DBBC_E00702.JDBCN_Failed_NM", new Object[]{ + inout.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString()}); + processException(e, transaction, inout, epb, + faultCode, faultDetail); + throw new Exception(faultString, e); + } finally { + if (normalizationMeasurement != null) + normalizationMeasurement.end(); + + } + inout.setOutMessage(outMsg); + + } + } + } catch (final Exception ex) { + mLogger.log(Level.SEVERE, + OutboundMessageProcessor.mMessages.getString( + "DBBC_E00622.OMP_Failed_writing"), ex.getLocalizedMessage()); + success = false; + setErrorInExchange(inout, faultCode, faultDetail, ex); + inout.setStatus(ExchangeStatus.ERROR); + } + } catch (final Exception ex) { + mLogger.log(Level.SEVERE, + OutboundMessageProcessor.mMessages.getString( + "DBBC_E00623.OMP_Failed_inout"), ex); + throw new RuntimeException(ex); + } finally { + try { + getTransactionManager().suspend(); + mChannel.send(inout); + + + if (success) + updateTallySentReplies(epb); + else + epb.getEndpointStatus().incrementSentErrors(); + if (rs != null) + rs.close(); + if (cs != null) + cs.close(); + + if (ps != null) + ps.close(); + if (connection != null) + connection.close(); + } catch (SQLException sqlexception) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00628.OMP_Cleanup_Failure"), sqlexception); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00628.OMP_Cleanup_Failure")); + } catch (Exception ex) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00628.OMP_Cleanup_Failure"), ex); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00628.OMP_Cleanup_Failure")); + + } + } + } + } + + /** + * @param inonly + * @param epb + */ + protected void processInOnly(final InOnly inonly, final EndpointBean epb) { + Connection connection = null; + Transaction transaction = null; + boolean success = true; + String faultCode = null; + String faultDetail = null; + if (inonly.getStatus() == ExchangeStatus.DONE) + // remove the redelivery listener handler - no retry needed. + MessageExchangeSupport.removeReplyListener(inonly.getExchangeId()); + else if (inonly.getStatus() == ExchangeStatus.ERROR) { + + // added for retry support + updateTallyReceives(epb, false); + + // send alerts + String errorMsg = inonly.getError().getMessage(); + if (errorMsg != null) { + String msg = mMessages.getString( + "DBBC-E00720.Message_exchange_error", + new Object[]{ + String.valueOf(inonly.getService()), + inonly.getEndpoint().getEndpointName(), + errorMsg + }); + mLogger.log(Level.SEVERE, msg); + AlertsUtil.getAlerter().warning(msg, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00720"); + } else { + String msg = mMessages.getString( + "DBBC-E00721.Message_exchange_error_no_detail", + new Object[]{ + String.valueOf(inonly.getService()), + inonly.getEndpoint().getEndpointName() + }); + mLogger.log(Level.SEVERE, msg); + AlertsUtil.getAlerter().warning(msg, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00721"); + } + /** + // let's see if retry is configured or not + EndpointInfo info = new EndpointInfo(false, + epb.getEndpointName(), + null, + epb.getServiceName(), + null); + RedeliveryConfig retryConfig = mChannel.getServiceQuality(info, RedeliveryConfig.class); + **/ + RedeliveryStatus retryStatus = + Redelivery.getRedeliveryStatus(inonly); + if (retryStatus != null && retryStatus.getRemainingRetries() > 0) { + try { + MessageExchangeSupport.notifyOfRedelivery(inonly); + } catch (Exception e) { + String groupId = (String) inonly.getProperty(CRMP_GROUP_ID); + String messageId = (String) inonly.getProperty( + CRMP_MESSAGE_ID); + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E01036.Failed_to_process_redelivery", + new Object[]{groupId, messageId}); + mLogger.log(Level.WARNING, text, e); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E01036"); + } + } + updateTallyReceives(epb, false); + } + } + + // added for retry support + try { + MessageExchangeSupport.notifyOfReply(inonly); + } catch (Exception ex) { + if (mLogger.isLoggable(Level.WARNING)) { + String text = mMessages.getString( + "DBBC-E00759.Exception_during_reply_processing", ex. + getLocalizedMessage()); + mLogger.log(Level.SEVERE, text, ex); + AlertsUtil.getAlerter().warning(text, + JDBCBindingLifeCycle.SHORT_DISPLAY_NAME, + epb.getDeploymentId(), + AlertsUtil.getServerType(), + AlertsUtil.COMPONENT_TYPE_BINDING, + NotificationEvent.OPERATIONAL_STATE_RUNNING, + NotificationEvent.EVENT_TYPE_ALERT, + "DBBC-E00759"); + } + success = false; + } + + try { + updateTallyReceivedRequests(epb); + + final NormalizedMessage inMsg = inonly.getInMessage(); + final Map operationNameToMetaData = (Map) epb.getValueObj( + EndpointBean.OPERATION_NAME_TO_META_DATA); + final OperationMetaData meta = (OperationMetaData) operationNameToMetaData.get(inonly.getOperation(). + getLocalPart()); + + if (meta == null) + throw new MessagingException(OutboundMessageProcessor.mMessages. + getString("DBBC_E00621.OMP_oper_NotDefined") + inonly. + getOperation()); + + + if (inonly.isTransacted()) + // Removing manual enlistment. Moving to automatic resource enlistment + // mtxHelper.handleOutbound(mExchange); + // enlistResource(epb); + transaction = (Transaction) inonly.getProperty( + MessageExchange.JTA_TRANSACTION_PROPERTY_NAME); + + try { + if (transaction != null) + getTransactionManager().resume(transaction); + Object jndiNameObj = + inMsg.getProperty( + JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); + try { + if (jndiNameObj != null) { + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiNameObj.toString()); + connection = getDatabaseConnection(inMsg); + } else { + String jndiName = epb.getValue( + EndpointBean.JDBC_DATABASE_JNDI_NAME); + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00629.OMP_UsedJNDI") + jndiName); + connection = getDatabaseConnection(epb); + } + } catch (Exception e) { + faultCode = SERVER; + faultDetail = "Unable to get connection : " + e.toString(); + String faultString = mMessages.getString( + "DBBC_E00627.OMP_Failed_LookUp_JNDI", new Object[]{ + inonly.getExchangeId(), epb.getValue( + EndpointBean.ENDPOINT_NAME), + mExchange.getOperation().toString()}); + throw new Exception(faultString, e); + } + + if (transaction != null) + connection.setAutoCommit(true); + // writeMessage(inMsg, destinationAddress, false); + if (meta.getJDBCOperationInput().getOperationType(). + equalsIgnoreCase( + JDBCOperations.OPERATION_TYPE_EXECUTE.toString())) + // executeOutboundProc(inMsg, epb, meta); + // Auto enlistment: pass the transaction retrieved from the Message exchange. + cs = executeOutboundProc(inMsg, epb, meta, connection); + else + // executeOutboundSQL(inMsg, epb, meta); + // Auto enlistment: pass the transaction retrieved from the Message exchange. + executeOutboundSQL(inMsg, epb, meta, connection); + inonly.setStatus(ExchangeStatus.DONE); + } catch (final SQLException ex) { + processException(ex, transaction, inonly, epb, faultCode, + faultDetail); + } catch (final MessagingException ex) { + processException(ex, transaction, inonly, epb, faultCode, + faultDetail); + } catch (final Exception ex) { + processException(ex, transaction, inonly, epb, faultCode, + faultDetail); + } finally { + try { + if (cs != null) + cs.close(); + + if (ps != null) + ps.close(); + if (connection != null) + connection.close(); + } catch (SQLException sqlexception) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00628.OMP_Cleanup_Failure"), sqlexception); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00628.OMP_Cleanup_Failure")); + } + } + + /* + * if (inonly.isTransacted()) { mtxHelper.handleInbound(mExchange); } + */ + + if (transaction != null) + getTransactionManager().suspend(); + mChannel.send(inonly); + + + if (success) + updateTallySends(epb, success); + else + epb.getEndpointStatus().incrementSentErrors(); + } catch (final Exception ex) { + if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00624.OMP_Failed_inonly"), ex); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.SEVERE, mMessages.getString( + "DBBC_E00624.OMP_Failed_inonly")); + + } + } + + /** + * @param nMsg + * @param eBean + * @param opMetaData + * @return + * @throws MessagingException + */ + protected ResultSet executeOutboundSQLSelect(final NormalizedMessage nMsg, + final EndpointBean eBean, + final OperationMetaData opMetaData, + Connection connection) throws SQLException, MessagingException { + String sql = null; + try { + sql = opMetaData.getJDBCSql().getSql(); + mLogger.log(Level.INFO, + OutboundMessageProcessor.mMessages.getString( + "DBBC_R00625.OMP_Exec_SQL") + sql); + + ps = connection.prepareStatement(sql); + + final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); + Probe denormalizationMeasurement = Probe.info(getClass(), + eBean.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); + + denormalizer.denormalizeOutbound(nMsg, getDBName(eBean, nMsg), + opMetaData, ps); + + if (denormalizationMeasurement != null) + denormalizationMeasurement.end(); + + rs = ps.executeQuery(); + } catch (final SQLException ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. + getSQLState() + " ErrorCode: " + ex.getErrorCode(); + throw new SQLException(msg); + } catch (final MessagingException ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } catch (final Exception ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } + return rs; + } + + /** + * @param nMsg + * @param eBean + * @param opMetaData + * @return + * @throws MessagingException + */ + protected int executeOutboundSQL(final NormalizedMessage nMsg, + final EndpointBean eBean, + final OperationMetaData opMetaData, + Connection connection) throws SQLException, MessagingException { + String sql = null; + int rowsUpdated = -1; + + try { + sql = opMetaData.getJDBCSql().getSql(); + mLogger.log(Level.INFO, mMessages.getString( + "DBBC_R00625.OMP_Exec_SQL") + sql); + + ps = connection.prepareStatement(sql); + + final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); + Probe denormalizationMeasurement = Probe.info(getClass(), + eBean.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); + + denormalizer.denormalizeOutbound(nMsg, getDBName(eBean, nMsg), + opMetaData, ps); + if (denormalizationMeasurement != null) + denormalizationMeasurement.end(); + + rowsUpdated = ps.executeUpdate(); + } catch (final SQLException ex) { + final String msg = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. + getSQLState() + " ErrorCode: " + ex.getErrorCode(); + throw new SQLException(msg); + } catch (final MessagingException ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } catch (final Exception ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } + return rowsUpdated; + } + + /* + * Added by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + /** + * @param nMsg + * @param eBean + * @param opMetaData + * @return + * @throws MessagingException + */ + protected String executeOutboundSQLWithGeneratedKeys(final NormalizedMessage nMsg, + final EndpointBean eBean, + final OperationMetaData opMetaData, + Connection connection) throws SQLException, MessagingException { + mLogger.log(Level.INFO, "Entering executeOutboundSQLWithGeneratedKeys"); + String sql = null; + int rowsUpdated = -1; + String generatedKeyValue = null; + + try { + sql = opMetaData.getJDBCSql().getSql(); + mLogger.log(Level.INFO, mMessages.getString( + "DBBC_R00625.OMP_Exec_SQL") + sql); + + String outputColumn = opMetaData.getJDBCSql().getGeneratedKey(); + + ps = connection.prepareStatement(sql, new String[]{outputColumn}); + + final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); + Probe denormalizationMeasurement = Probe.info(getClass(), + eBean.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); + + denormalizer.denormalizeOutbound(nMsg, getDBName(eBean, nMsg), + opMetaData, ps); + if (denormalizationMeasurement != null) + denormalizationMeasurement.end(); + + + rowsUpdated = ps.executeUpdate(); + ResultSet rs = ps.getGeneratedKeys(); + if (rs != null && rs.next()) + generatedKeyValue = rs.getString(1); + } catch (final SQLException ex) { + final String msg = mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. + getSQLState() + " ErrorCode: " + ex.getErrorCode(); + throw new SQLException(msg); + } catch (final MessagingException ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } catch (final Exception ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } + mLogger.log(Level.INFO, "Exiting executeOutboundSQLWithGeneratedKeys"); + return generatedKeyValue; + } + + /** + * @param nMsg + * @param eBean + * @param opMetaData + * @return + * @throws MessagingException + */ + protected CallableStatement executeOutboundProc(final NormalizedMessage nMsg, + final EndpointBean eBean, + final OperationMetaData opMetaData, + Connection connnection) throws SQLException, MessagingException { + String sql = null; + int rowsUpdated = -1; + + try { + sql = opMetaData.getJDBCSPOperationInput().getExecutionString(); + mLogger.log(Level.INFO, mMessages.getString( + "DBBC_R00625.OMP_Exec_SQL") + sql); + + cs = connnection.prepareCall(sql); + DatabaseMetaData dbmeta = connnection.getMetaData(); + + final JDBCDenormalizer denormalizer = new JDBCDenormalizer(); + + if (eBean.getValue(EndpointBean.JDBC_DATABASE_NAME) != null) + denormalizer.setDatabaseName(eBean.getValue( + EndpointBean.JDBC_DATABASE_NAME)); + Probe denormalizationMeasurement = Probe.info(getClass(), + eBean.getUniqueName(), + JDBCBindingLifeCycle.PERF_CAT_DENORMALIZATION); + denormalizer.denormalizeOutboundProc(nMsg, opMetaData, dbmeta, cs); + if (denormalizationMeasurement != null) + denormalizationMeasurement.end(); + + outParamIndex = denormalizer.getOutParamIndex(); + outParamTypes = denormalizer.getOutParamTypes(); + outParamNames = denormalizer.getOutParamNames(); + // rowsUpdated = cs.executeUpdate(); + boolean b = cs.execute(); + return cs; + } catch (final SQLException ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_R00624.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage() + " SQLState: " + ex. + getSQLState() + " ErrorCode: " + ex.getErrorCode(); + throw new SQLException(msg); + } catch (final MessagingException ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_E00626.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } catch (final Exception ex) { + final String msg = OutboundMessageProcessor.mMessages.getString( + "DBBC_R00624.OMP_Failed_Exec_SQL") + sql + + " Reason: " + ex.getLocalizedMessage(); + throw new MessagingException(msg, ex); + } + + // return rowsUpdated; + } + + // resumes the transaction + private void resumeThreadTx(Transaction tx) throws Exception { + if (tx != null) { + ((TransactionManager) mContext.getContext().getTransactionManager()). + resume(tx); + mLogger.log(Level.INFO, " ", new Object[]{tx.toString()}); + } + } + + /** + * @param jndiName + * @return + * @throws javax.naming.NamingException + */ + private Object getDataSourceFromContext(final String jndiName) throws javax.naming.NamingException { + final Context c = mContext.getContext().getNamingContext(); + + return c.lookup(jndiName); + } + + /** + * @param jndiName + * @return + * @throws Exception + */ + private Connection getDatabaseConnection(final String jndiName) throws Exception { + final DataSource ds = (DataSource) getDataSourceFromContext(jndiName); + final Connection con = ds.getConnection(); + + return con; + } + + private Connection getDatabaseConnection(final EndpointBean epbean) throws Exception { + if (epbean.getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME) == null || epbean. + getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME).equals("")) { + final String driverClass = epbean.getValue( + EndpointBean.JDBC_DATABASE_DRIVER_CLASS); + final String dbURL = epbean.getValue(EndpointBean.JDBC_DATABASE_URL); + final String user = epbean.getValue(EndpointBean.JDBC_DATABASE_USER); + final String password = epbean.getValue( + EndpointBean.JDBC_DATABASE_PASSWORD); + // Thread.currentThread().getContextClassLoader().loadClass(driverClass).newInstance(); + Class.forName(driverClass).newInstance(); + + return DriverManager.getConnection(dbURL, user, password); + } else { + final DataSource ds = (DataSource) getDataSourceFromContext(epbean. + getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME)); + final Connection con = ds.getConnection(); + + return con; + } + } + + private Connection getDatabaseConnection(NormalizedMessage nm) + throws SQLException, NamingException { + Object p = nm.getProperty( + JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME); + String jndiName = null; + Connection conn = null; + if (p != null) + jndiName = p.toString(); + if (jndiName != null) { + DataSource ds = (DataSource) getDataSourceFromContext(jndiName); + conn = ds.getConnection(); + } + return conn; + } + + private XAConnection getXADatabaseConnection(final EndpointBean epbean) throws Exception { + try { + final DataSource ds = (DataSource) getDataSourceFromContext(epbean. + getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME)); + if (ds instanceof XADataSource) { + XAConnection con = ((XADataSource) ds).getXAConnection(); + return con; + } + } catch (Exception e) { + if (mLogger.isLoggable(Level.FINEST)) + mLogger.log(Level.SEVERE, "Either the JNDI NAME is NULL or Could not establish connection using JNDI NAME :" + + EndpointBean.JDBC_DATABASE_JNDI_NAME, e); + else if (mLogger.isLoggable(Level.FINE)) + mLogger.log(Level.SEVERE, "Either the JNDI NAME is NULL or Could not establish connection using JNDI NAME :" + + EndpointBean.JDBC_DATABASE_JNDI_NAME + " Reason: " + e. + getLocalizedMessage()); + else if (mLogger.isLoggable(Level.INFO)) + mLogger.log(Level.SEVERE, + "Either the JNDI NAME is NULL or Could not establish connection using JNDI NAME :"); + } + return null; + } + + /** + * @param prepStmtSQLText + * @return + */ + private boolean isSelectStatement(final String prepStmtSQLText) { + prepStmtSQLText.trim(); + + final StringTokenizer tok = new StringTokenizer(prepStmtSQLText); + + if (tok.hasMoreTokens()) { + final String firstTok = (String) tok.nextToken(); + + if (firstTok.equalsIgnoreCase("select")) + return true; + } + + return false; + } + + /* + * Modified by Logicoy for [ task #20 ] DB BC - Insert statement should return primary key auto-increment value inserted + */ + /** + * @param prepStmtSQLText + * @return + */ + private boolean isInsertStatement(final String prepStmtSQLText) { + prepStmtSQLText.trim(); + + final StringTokenizer tok = new StringTokenizer(prepStmtSQLText); + + if (tok.hasMoreTokens()) { + final String firstTok = (String) tok.nextToken(); + + if (firstTok.equalsIgnoreCase("insert")) + return true; + } + + return false; + } + + private TransactionManager getTransactionManager() { + return (TransactionManager) mContext.getContext().getTransactionManager(); + } + + private boolean processException(final Exception ex, Transaction transaction, + final MessageExchange inonly, final EndpointBean epb, + String faultCode, String faultDetail) { + boolean success = false; + mLogger.log(Level.WARNING, OutboundMessageProcessor.mMessages.getString( + "DBBC_E00622.OMP_Failed_writing"), ex); + + try { + if (transaction != null) + transaction.setRollbackOnly(); + } catch (javax.transaction.SystemException e) { + //ignore since the code below will take care of setting error on ME. + } + faultCode = CLIENT; + faultDetail = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize"); + String faultString = mMessages.getString( + "DBBC_E00706.JDBCDN_Failed_Denormalize", new Object[]{inonly. + getExchangeId(), epb.getValue(EndpointBean.ENDPOINT_NAME), inonly. + getOperation(). + toString()}); + setErrorInExchange(inonly, faultCode, faultDetail, ex); + try { + inonly.setStatus(ExchangeStatus.ERROR); + } catch (MessagingException mex) { + //ignore + } + return success; + } + + private void updateTallyReceivedReplies(EndpointBean e) { + if (e != null) { + EndpointStatus status = e.getEndpointStatus(); + if (status != null) + status.incrementReceivedReplies(); + } + } + + private void updateTallyReceivedRequests(EndpointBean e) { + if (e != null) { + EndpointStatus status = e.getEndpointStatus(); + if (status != null) + status.incrementReceivedRequests(); + } + } + + private void updateTallySentReplies(EndpointBean e) { + if (e != null) { + EndpointStatus status = e.getEndpointStatus(); + if (status != null) + status.incrementSentReplies(); + } + } + + private void updateTallySentRequests(EndpointBean e) { + if (e != null) { + EndpointStatus status = e.getEndpointStatus(); + if (status != null) + status.incrementSentRequests(); + } + } + + private void updateTallyReceives(EndpointBean e, boolean successfulReceive) { + if (e != null) { + EndpointStatus status = e.getEndpointStatus(); + if (status != null) + if (successfulReceive) + status.incrementReceivedDones(); + else + status.incrementReceivedErrors(); + } + } + + private void updateTallySends(EndpointBean e, boolean successfulSend) { + if (e != null) { + EndpointStatus status = e.getEndpointStatus(); + if (status != null) + if (successfulSend) + status.incrementSentDones(); + else + status.incrementSentErrors(); + } + } + + private String getDBName(EndpointBean eBean, NormalizedMessage nMsg) + throws javax.naming.NamingException, java.sql.SQLException { + if (eBean.getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME) == null || eBean. + getValue(EndpointBean.JDBC_DATABASE_JNDI_NAME).equals("")) + return dbConnectionInfo.getDataBaseName(eBean.getValue( + EndpointBean.JDBC_DATABASE_URL), null, null); + else { + String jndiName = eBean.getValue( + EndpointBean.JDBC_DATABASE_JNDI_NAME); + if (nMsg.getProperty( + JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME) != null) + jndiName = nMsg.getProperty( + JDBCComponentContext.NM_PROP_DATABASEBC_CONNECTION_JNDI_NAME). + toString(); + return dbConnectionInfo.getDataBaseName(null, null, + (DataSource) getDataSourceFromContext(jndiName)); + + } + } + + private void setErrorInExchange(MessageExchange ex, String faultCode, + String faultDetail, Exception e) { + ex.setError(e); + ex.setProperty("com.sun.jbi.crl.faultcode", faultCode); + ex.setProperty("com.sun.jbi.crl.faultstring", e.getMessage()); + ex.setProperty("com.sun.jbi.crl.faultactor", "sun-database-binding"); + ex.setProperty("com.sun.jbi.crl.faultdetail", + faultDetail + e.getMessage()); + } +}