Example usage for org.apache.commons.lang StringUtils contains

List of usage examples for org.apache.commons.lang StringUtils contains

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils contains.

Prototype

public static boolean contains(String str, String searchStr) 

Source Link

Document

Checks if String contains a search String, handling null.

Usage

From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQL.java

/**
 * //ww  w. j  av a 2s. co m
 */
public void convert(final String databaseName, final String tableName, final String srcFileName,
        final String xmlFileName) {
    String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", };
    HashMap<String, Integer> monthHash = new HashMap<String, Integer>();
    for (String mn : months) {
        monthHash.put(mn, monthHash.size() + 1);
    }

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/" + databaseName + "?characterEncoding=UTF-8&autoReconnect=true",
                "root", "root");
        stmt = conn.createStatement();

        FMPCreateTable fmpInfo = new FMPCreateTable(tableName, null, true);
        fmpInfo.process(xmlFileName);

        boolean doCreateTable = true;
        if (doCreateTable) {
            processFieldSizes(fmpInfo, srcFileName);

            PrintWriter pw = new PrintWriter(new File("fields.txt"));
            int i = 0;
            for (FieldDef fd : fmpInfo.getFields()) {
                pw.println(i + " " + fd.getName() + "\t" + fd.getType() + "\t" + fd.isDouble());
                i++;
            }
            pw.close();

            BasicSQLUtils.update(conn, fmpInfo.dropTableStr());

            String sqlCreateTable = fmpInfo.createTableStr();

            BasicSQLUtils.update(conn, sqlCreateTable);

            System.out.println(sqlCreateTable);
        }

        String prepSQL = fmpInfo.getPrepareStmtStr(true, true);
        System.out.println(prepSQL);
        pStmt = conn.prepareStatement(prepSQL);

        Vector<FieldDef> fieldDefs = fmpInfo.getFields();

        int rowCnt = 0;
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName)));
        String str = in.readLine();
        str = in.readLine();
        while (str != null) {
            String line = str;
            char sep = '`';
            String sepStr = "";
            for (char c : seps) {
                if (line.indexOf(c) == -1) {
                    sepStr += c;
                    sep = c;
                    break;
                }
            }
            str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", sepStr);
            Vector<String> fields = split(str, sep);

            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

            int col = 1;
            int inx = 0;
            for (String fld : fields) {
                String value = fld.trim();
                FieldDef fd = fieldDefs.get(inx);

                switch (fd.getType()) {
                case eText:
                case eMemo: {
                    if (value.length() > 0) {
                        //value = FMPCreateTable.convertFromUTF8(value);
                        if (value.length() <= fd.getMaxSize()) {
                            pStmt.setString(col, value);
                        } else {
                            System.err.println(String.format("The data for `%s` max(%d) is too big %d",
                                    fd.getName(), fd.getMaxSize(), value.length()));
                            pStmt.setString(col, null);
                        }
                    } else {
                        pStmt.setString(col, null);
                    }
                }
                    break;

                case eNumber: {
                    if (StringUtils.isNotEmpty(value)) {
                        String origValue = value;
                        String val = value.charAt(0) == '' ? value.substring(1) : value;
                        val = val.charAt(0) == '-' ? val.substring(1) : val;
                        val = val.indexOf('.') > -1 ? StringUtils.replace(val, ".", "") : val;
                        val = val.indexOf('') > -1 ? StringUtils.replace(val, "", "") : val;

                        if (StringUtils.isNumericSpace(val)) {
                            if (fd.isDouble()) {
                                pStmt.setDouble(col, Double.parseDouble(val));
                            } else {
                                pStmt.setInt(col, Integer.parseInt(val));
                            }
                        } else if (val.startsWith("ca. ")) {
                            pStmt.setInt(col, Integer.parseInt(val.substring(4)));
                        } else if (val.startsWith("ca ")) {
                            pStmt.setInt(col, Integer.parseInt(val.substring(3)));
                        } else {
                            System.err.println(col + " Bad Number val[" + val + "] origValue[" + origValue
                                    + "] " + fieldDefs.get(col - 1).getName());
                            pStmt.setObject(col, null);
                        }
                    } else {
                        pStmt.setDate(col, null);
                    }
                }
                    break;

                case eTime: {
                    Time time = null;
                    try {
                        time = Time.valueOf(value);
                    } catch (Exception ex) {
                    }
                    pStmt.setTime(col, time);
                }
                    break;

                case eDate: {
                    String origValue = value;
                    try {
                        if (StringUtils.isNotEmpty(value) && !value.equals("?") && !value.equals("-")) {
                            int len = value.length();
                            if (len == 8 && value.charAt(1) == '-' && value.charAt(3) == '-') // 0-9-1886
                            {
                                String dayStr = value.substring(0, 1);
                                String monStr = value.substring(2, 3);
                                if (StringUtils.isNumeric(dayStr) && StringUtils.isNumeric(monStr)) {
                                    String year = value.substring(4);
                                    int day = Integer.parseInt(dayStr);
                                    int mon = Integer.parseInt(monStr);
                                    if (day == 0)
                                        day = 1;
                                    if (mon == 0)
                                        mon = 1;

                                    value = String.format("%02d-%02d-%s", day, mon, year);
                                } else {
                                    value = StringUtils.replaceChars(value, '.', ' ');
                                    String[] toks = StringUtils.split(value, ' ');
                                    if (toks.length == 3) {
                                        String dyStr = toks[0];
                                        String mnStr = toks[1];
                                        String yrStr = toks[2];
                                        if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr)
                                                && StringUtils.isNumeric(yrStr)) {
                                            int day = Integer.parseInt(dyStr);
                                            int mon = Integer.parseInt(mnStr);
                                            int year = Integer.parseInt(yrStr);
                                            if (day == 0)
                                                day = 1;
                                            if (mon == 0)
                                                mon = 1;

                                            value = String.format("%02d-%02d-%04d", day, mon, year);
                                        } else {
                                            System.err.println(
                                                    col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                        }
                                    } else {
                                        System.err.println(
                                                col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                    }
                                }

                            } else if (len == 8 && (value.charAt(3) == '-' || value.charAt(3) == ' ')) // Apr-1886
                            {
                                String monStr = value.substring(0, 3);
                                Integer month = monthHash.get(monStr);
                                String year = value.substring(4);
                                if (month != null && StringUtils.isNumeric(year)) {
                                    value = String.format("01-%02d-%s", month, year);
                                } else {
                                    value = StringUtils.replaceChars(value, '.', ' ');
                                    String[] toks = StringUtils.split(value, ' ');
                                    if (toks.length == 3) {
                                        String dyStr = toks[0];
                                        String mnStr = toks[1];
                                        String yrStr = toks[2];
                                        if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr)
                                                && StringUtils.isNumeric(yrStr)) {
                                            int day = Integer.parseInt(dyStr);
                                            int mon = Integer.parseInt(mnStr);
                                            int yr = Integer.parseInt(yrStr);
                                            if (day == 0)
                                                day = 1;
                                            if (mon == 0)
                                                mon = 1;

                                            value = String.format("%02d-%02d-%04d", day, mon, yr);
                                        } else {
                                            System.err.println(
                                                    col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                        }
                                    } else {
                                        System.err.println(
                                                col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                    }
                                }

                            } else if ((len == 11 && value.charAt(2) == '-' && value.charAt(6) == '-') || // 10-May-1898
                                    (len == 10 && value.charAt(1) == '-' && value.charAt(5) == '-')) //  7-May-1898
                            {
                                boolean do11 = len == 11;
                                String dayStr = value.substring(0, do11 ? 2 : 1);
                                String monStr = value.substring(do11 ? 3 : 2, do11 ? 6 : 5);

                                Integer month = monthHash.get(monStr);
                                String year = value.substring(do11 ? 7 : 6);
                                if (month != null && StringUtils.isNumeric(dayStr)
                                        && StringUtils.isNumeric(year)) {
                                    int day = Integer.parseInt(dayStr);
                                    if (day == 0)
                                        day = 1;
                                    value = String.format("%02d-%02d-%s", day, month, year);

                                } else {
                                    System.err
                                            .println(col + " Bad Date^[" + value + "]  [" + origValue + "]\n");
                                }
                            } else if (len == 4) {
                                if (StringUtils.isNumeric(value)) {
                                    value = "01-01-" + value;

                                } else if (value.equalsIgnoreCase("s.d.") || value.equalsIgnoreCase("n.d.")
                                        || value.equalsIgnoreCase("s.n.")) {
                                    value = null;
                                }
                            } else if (StringUtils.contains(value, "/")) {
                                value = StringUtils.replace(value, "/", "-");

                            } else if (StringUtils.contains(value, " ")) {
                                value = StringUtils.replace(value, " ", "-");
                            }
                            pStmt.setDate(col,
                                    StringUtils.isNotEmpty(value)
                                            ? new java.sql.Date(sdf.parse(value).getTime())
                                            : null);
                        } else {
                            pStmt.setDate(col, null);
                        }
                    } catch (Exception ex) {
                        System.err.println(col + " Bad Date[" + value + "]  [" + origValue + "]\n" + str);
                        pStmt.setDate(col, null);
                    }
                }
                    break;

                default: {
                    System.err.println("Col: " + col + "  Error - " + fd.getType());
                }
                }
                inx++;
                col++;
            }
            pStmt.execute();
            str = in.readLine();
            rowCnt++;
            if (rowCnt % 1000 == 0) {
                System.out.println(rowCnt);
            }
        }
        in.close();

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            stmt.close();
            conn.close();
            pStmt.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.bluexml.side.Integration.alfresco.xforms.webscript.XFormsWork.java

/**
 * Provides the items to be listed in a selection widget. Returns an XML
 * string with root//from   ww  w.  j a v a  2s. com
 * '&lt;results&gt;':<br>
 * <ul>
 * <li>query (appears once)</li>
 * <ul>
 * <li>count: the total number of objects available in the Lucene result set
 * </li>
 * <li>maxResults: if non-zero, sets the maximum number of objects requested
 * by the client. Returned as received.</li>
 * <li>returned: the number of result items returned to the client</li>
 * <li>filteredOut: if a filtering association was given, tells the number
 * of items that have been filtered out because they already have a
 * reference on that association.</li>
 * <li>typeFound: if <code>false</code>, the type is unknown to Alfresco.</li>
 * <li>query: a string to filter the items. The value returned is the
 * TrimToEmpty'ed version of the value that was received.</li>
 * </ul>
 * <li>item (number of occurrences is 0..*)</li>
 * <ul>
 * <li>id: the complete Alfresco id, including protocol and workspace</li>
 * <li>value: the display label for the item</li>
 * </ul>
 * </ul> Parameters: ("NULL-able" means that an empty value is accepted.)<br/>
 * "type": the data type to search. This parameter is MANDATORY.<br/>
 * "query": the search keyword string. NULL-able.<br/>
 * "queryFilter": an additional search keyword string. NULL-able.<br/>
 * "format": the format pattern for the label of objects. NULL-able.<br/>
 * "maxLength": the length at which labels computed using the format are
 * truncated. NULL-able.<br/>
 * "maxResults": the max number of items allowed in the result set.
 * NULL-able.<br/>
 * "identifier": the local name of a property whose value will be used as
 * the id of results.
 * NULL-able. Quite obviously, that field MUST 1- be non-null, 2- be an
 * actual identifier (i.e.
 * no value is duplicated in the value set)<br/>
 * "filterAssoc": the qualified name of an association by which it will be
 * determined whether
 * nodes are referenced. If present, nodes that are already pointed to by
 * that association will
 * be filtered out of the results. NULL-able.<br/>
 * "isComposition": if "1" and "filterAssoc" is given, denotes that the
 * association is a
 * composition. NULL-able.<br/>
 * "isSearchMode": if "1", an empty item list will be returned on an empty
 * "query". NULL-able.<br/>
 * "luceneQuery": a Lucene query that overrides the one that's normally
 * built here. NULL-able.<br/>
 * 
 * @return
 * @throws Exception
 */
protected String list() throws Exception {
    class ResultBean { // #1406
        String id;
        String label;
        String qname;

        ResultBean(String nodeId, String nodeLabel, String nodeQName) {
            this.id = nodeId;
            this.label = nodeLabel;
            this.qname = nodeQName;
        }
    }

    logger.debug("Initialization of system time: " + System.nanoTime());
    Timer globalTimer = new Timer();
    Timer luceneTimer = new Timer();
    Timer noderefLuceneTimer = new Timer();
    Timer noderefTimer = new Timer();
    Timer labelTimer = new Timer();
    Timer qnameTimer = new Timer();
    Timer filteringTimer = new Timer();
    Timer referenceTimer = new Timer();
    Timer sortTimer = new Timer();

    globalTimer.start();
    //
    // collect parameters. Some of these are not necessary before the filtering/limiting/sorting
    // part but for convenience, all parameters are collected with, possibly, some work done
    // here that will come out as useless, but it makes this function more readable.
    //
    String type = parameters.get("type");
    if (StringUtils.trimToNull(type) == null) {
        return getListOpcodeDefaultResult("<Invalid type>", false);
    }
    String identifier = parameters.get("identifier"); // #1529
    String format = parameters.get("format");
    // URL-decode the format pattern
    if (StringUtils.trimToNull(format) != null) {
        try {
            format = URLDecoder.decode(format, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("UTF-8 is unsupported. Format is defaulted to 'uuid'.");
            format = null;
        }
    }

    int maxResults = 10; // arbitrary default value
    String maxParam = parameters.get("maxResults");
    try {
        maxResults = Integer.parseInt(maxParam);
    } catch (NumberFormatException ne) {
        logger.error("'list' op: wrong number in parameter 'maxResults' (" + maxParam + ")");
    }

    int maxLength = 0; // arbitrary default value
    String lengthParam = parameters.get("maxLength");
    try {
        maxLength = Integer.parseInt(lengthParam);
    } catch (NumberFormatException nfe) {
        logger.error("'list' op: wrong number in parameter 'maxLength' (" + lengthParam + ")");
    }
    // ** #1310
    String filterAssoc = parameters.get("filterAssoc");
    boolean applyFilterAssoc = (StringUtils.trimToNull(filterAssoc) != null);
    String isCompositionParam = parameters.get("isComposition");
    boolean isComposition = StringUtils.equals(isCompositionParam, "1");
    // ** #1310

    String isSearchModeParam = parameters.get("isSearchMode");
    boolean isSearchMode = StringUtils.equals(isSearchModeParam, "1");

    List<String> searchedValues = new ArrayList<String>();
    String query = StringUtils.trimToNull(parameters.get("query"));
    if (query != null) {
        searchedValues.add(query);
    } else {
        if (isSearchMode) {
            return getListOpcodeDefaultResult(query, true); // empty list for search widgets
        }
    }

    String queryFilter = parameters.get("queryFilter");
    if (StringUtils.trimToNull(queryFilter) != null) {
        searchedValues.add(queryFilter);
    }

    String userLuceneQuery = StringUtils.trimToNull(parameters.get("luceneQuery"));
    if (userLuceneQuery != null) {
        try {
            // double-decoded because the string was double-encoded.
            userLuceneQuery = URLDecoder.decode(userLuceneQuery, "UTF-8");
            userLuceneQuery = URLDecoder.decode(userLuceneQuery, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("UTF-8 is unsupported. User Lucene expression will be ignored.");
            userLuceneQuery = null;
        }
    }

    // configure the filtering/limiting
    QName identifierQName = null;
    boolean includeSystemProperties = FORCE_SYSTEM_PROPERTIES_RESOLUTION;
    if (StringUtils.trimToNull(identifier) != null) {
        identifierQName = resolveIdentifierQName(identifier, type);
        includeSystemProperties = (identifierQName != null);
    }

    // perform the search
    luceneTimer.start();
    ResultSet luceneResultSet = getResultSet(type, searchedValues, maxResults, userLuceneQuery,
            includeSystemProperties);
    luceneTimer.stop();
    if (luceneResultSet == null) {
        // result for the pathological case when the type is unknown to Alfresco.
        return getListOpcodeDefaultResult(query, false);
    }
    int luceneResultLength = luceneResultSet.length();
    if (luceneResultLength == 0) {
        return getListOpcodeDefaultResult(query, true);
    }

    //
    //
    // collect items and apply filtering and/or limiting. Node names/labels are also computed.
    //
    //

    /**
     * whether we need to collect all elements before applying the filtering
     * & limiting
     */
    boolean collectAllNodes = false;
    if ((includeSystemProperties) && (query != null)) {
        // when searching system datatypes (e.g. "cm:permson"), we may have to collect all nodes
        // before filtering (happens when no property of the datatype is indexed)
        List<QName> subTypes = formsWebscript.getSubTypes(type);
        Set<QName> attributes = getSearchableAttributes(subTypes.get(0), includeSystemProperties);
        if (attributes.size() == 0) {
            // the datatype is not indexed
            collectAllNodes = true;
        }
    }

    int returnAtMost;
    if (collectAllNodes == false) {
        if (maxResults > 0) {
            returnAtMost = Math.min(luceneResultLength, maxResults);
        } else {
            returnAtMost = luceneResultLength;
        }
    } else {
        returnAtMost = luceneResultLength;
    }

    int effectivelyReturned = 0;
    int filteredOut = 0;
    // collect items and apply filtering and/or limiting
    filteringTimer.start();
    List<ResultBean> resultBeanList = new ArrayList<ResultBean>(returnAtMost);
    noderefLuceneTimer.start();
    List<NodeRef> resultSet = luceneResultSet.getNodeRefs();
    noderefLuceneTimer.stop();
    luceneResultSet.close();
    for (int i = 0; i < returnAtMost; i++) {
        noderefTimer.start();
        NodeRef nodeRef = resultSet.get(i);
        noderefTimer.stop();
        labelTimer.start();
        String label = resolveNodeName(nodeRef, format, includeSystemProperties);
        labelTimer.stop();
        if (maxLength > 0) {
            label = StringUtils.left(label, maxLength);
        }
        qnameTimer.start();
        QName qname = serviceRegistry.getNodeService().getType(nodeRef); // #1510
        String id;
        if (identifierQName == null) {
            id = nodeRef.toString();
        } else {
            id = resolveIdentifierValue(nodeRef, identifierQName);
        }
        String qnameStr = qname.toPrefixString(formsWebscript.getNamespacePrefixResolver());
        qnameTimer.stop();
        ResultBean aBean = new ResultBean(id, label, qnameStr);
        boolean isAddableBean = true; // whether the result will be added to the item list
        if (includeSystemProperties) {
            // for system datatypes, search the label (in case indexing is off for that type)
            if ((collectAllNodes == false) && (query != null) && (aBean.label.contains(query) == false)) {
                isAddableBean = false;
                filteredOut++;
            }
        } else {
            // retrieving objects of a standard BlueXML generated type
            if (applyFilterAssoc) {
                referenceTimer.start();
                if (dataLayer.isRefencenced(nodeRef, filterAssoc, isComposition) == true) {
                    // do not add if already referenced via the filtering association
                    isAddableBean = false;
                    filteredOut++;
                }
                referenceTimer.stop();
            }
        }
        if (isAddableBean) {
            resultBeanList.add(aBean);
            effectivelyReturned++;
        }
    }
    filteringTimer.stop();

    //
    // sort the result list by computed labels. #1406
    sortTimer.start();
    Collections.sort(resultBeanList, new Comparator<ResultBean>() {
        public int compare(ResultBean o1, ResultBean o2) {
            return o1.label.compareTo(o2.label);
        }
    });
    sortTimer.stop();

    //
    // write all results in the items string buffer
    //
    StringBuffer itemsBuf = new StringBuffer("");
    if (collectAllNodes == true) {
        // in case all nodes were collected, the filtering and limiting takes place here
        filteredOut = 0;
        effectivelyReturned = 0;
        for (ResultBean aBean : resultBeanList) {
            if ((query != null)
                    && StringUtils.contains(aBean.label.toLowerCase(), query.toLowerCase()) == false) {
                filteredOut++;
            } else {
                appendResult(itemsBuf, aBean.id, aBean.label, aBean.qname);
                effectivelyReturned++;
                if (effectivelyReturned == returnAtMost) {
                    break;
                }
            }
        }
    } else { // filtering and limiting already happened
        for (ResultBean aBean : resultBeanList) {
            appendResult(itemsBuf, aBean.id, aBean.label, aBean.qname);
        }
    }

    StringBuffer xmlResult = new StringBuffer("");
    xmlResult.append("<results>\n");
    xmlResult.append("<query>\n");
    xmlResult.append("  <count>").append(luceneResultLength).append("</count>\n");
    xmlResult.append("  <maxResults>").append(maxResults).append("</maxResults>\n");
    xmlResult.append("  <returned>").append(effectivelyReturned).append("</returned>\n");
    xmlResult.append("  <filteredOut>").append(filteredOut).append("</filteredOut>\n");
    xmlResult.append("  <typeFound>true</typeFound>\n");
    xmlResult.append("  <query>").append(StringUtils.trimToEmpty(query)).append("</query>\n");
    xmlResult.append("</query>\n");

    xmlResult.append(itemsBuf);

    xmlResult.append("</results>");

    globalTimer.stop();
    logger.debug(">>><<< Timing:");
    logger.debug("Total : " + globalTimer.getTotalTime() + " ns.");
    logger.debug(" Lucene : " + luceneTimer.getTotalTime() + " ns.");
    logger.debug(" Filtering : " + filteringTimer.getTotalTime() + " ns.");
    logger.debug("  Nref Lucene : " + noderefLuceneTimer.getTotalTime() + " ns.");
    logger.debug("  Nref SIDE: " + noderefTimer.getTotalTime() + " ns.");
    logger.debug("  Labels : " + labelTimer.getTotalTime() + " ns.");
    logger.debug("  QName : " + qnameTimer.getTotalTime() + " ns.");
    logger.debug("  Ref? : " + referenceTimer.getTotalTime() + " ns.");
    logger.debug(" Sort : " + sortTimer.getTotalTime() + " ns.");
    logger.debug(">>><<<");

    return xmlResult.toString();
}

From source file:edu.ku.brc.specify.datamodel.busrules.BaseTreeBusRules.java

@Override
public boolean beforeDeleteCommit(Object dataObj, DataProviderSessionIFace session) throws Exception {
    if (!super.beforeDeleteCommit(dataObj, session)) {
        return false;
    }/*from   w  w w . j  a va  2s .  c  om*/
    if (dataObj != null
            && (formViewObj == null || !StringUtils.contains(formViewObj.getView().getName(), "TreeDef"))
            && BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null) {
        return getRequiredLocks(dataObj);
    } else {
        return true;
    }
}

From source file:edu.ku.brc.specify.tasks.ReportsBaseTask.java

/**
 * @param model//from   w  w w.  j a  v  a  2  s  .co  m
 * @return
 * @throws Exception
 */
public DynamicReport buildReport(final TableModel model, final PageSetupDlg pageSetupDlg) throws Exception {
    // Find a Sans Serif Font on the System
    String fontName = null;

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    for (java.awt.Font font : ge.getAllFonts()) {
        String fName = font.getFamily().toLowerCase();
        if (StringUtils.contains(fName, "sansserif") || StringUtils.contains(fName, "arial")
                || StringUtils.contains(fName, "verdana")) {
            fontName = font.getFamily();
        }
    }

    if (fontName == null) {
        fontName = Font._FONT_TIMES_NEW_ROMAN;
    }

    /**
     * Creates the DynamicReportBuilder and sets the basic options for the report
     */
    FastReportBuilder drb = new FastReportBuilder();

    Style columDetail = new Style();
    //columDetail.setBorder(Border.THIN);

    Style columDetailWhite = new Style();
    //columDetailWhite.setBorder(Border.THIN);
    columDetailWhite.setBackgroundColor(Color.WHITE);
    columDetailWhite.setFont(new Font(10, fontName, true));
    columDetailWhite.setHorizontalAlign(HorizontalAlign.CENTER);
    columDetailWhite.setBlankWhenNull(true);

    Style columDetailWhiteBold = new Style();
    //columDetailWhiteBold.setBorder(Border.THIN);
    columDetailWhiteBold.setBackgroundColor(Color.WHITE);

    Style titleStyle = new Style();
    titleStyle.setFont(new Font(14, fontName, true));

    /*Style numberStyle = new Style();
    numberStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
            
    Style amountStyle = new Style();
    amountStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
    amountStyle.setBackgroundColor(Color.cyan);
    amountStyle.setTransparency(Transparency.OPAQUE);*/

    //Font dataRowFont = new Font(10, Font._FONT_VERDANA, true);

    // Odd Row Style
    Style oddRowStyle = new Style();
    //oddRowStyle.setBorder(Border.NO_BORDER);
    //oddRowStyle.setFont(dataRowFont);
    oddRowStyle.setHorizontalAlign(HorizontalAlign.CENTER);

    Color veryLightGrey = new Color(240, 240, 240);
    oddRowStyle.setBackgroundColor(veryLightGrey);
    oddRowStyle.setTransparency(Transparency.OPAQUE);

    // Event Row Style
    //Style evenRowStyle = new Style();
    //evenRowStyle.setBorder(Border.NO_BORDER);
    //evenRowStyle.setFont(dataRowFont);

    // Create Column Headers for the Report
    for (int i = 0; i < model.getColumnCount(); i++) {
        String colName = model.getColumnName(i);

        Class<?> dataClass = model.getColumnClass(i);
        if (dataClass == Object.class) {
            if (model.getRowCount() > 0) {
                Object data = model.getValueAt(0, i);
                if (data != null) {
                    dataClass = data.getClass();
                } else {
                    // Column in first row was null so search down the rows
                    // for a non-empty cell
                    for (int j = 1; j < model.getRowCount(); j++) {
                        data = model.getValueAt(j, i);
                        if (dataClass != null) {
                            dataClass = data.getClass();
                            break;
                        }
                    }

                    if (dataClass == null) {
                        dataClass = String.class;
                    }
                }
            }
        }

        ColumnBuilder colBldr = ColumnBuilder.getInstance().setColumnProperty(colName, dataClass.getName());
        int bracketInx = colName.indexOf('[');
        if (bracketInx > -1) {
            colName = colName.substring(0, bracketInx - 1);
        }
        colBldr.setTitle(colName);
        //colBldr.setWidth(new Integer(100));

        colBldr.setStyle(columDetailWhite);
        //colBldr.setHeaderStyle(columDetailWhite);

        AbstractColumn column = colBldr.build();
        drb.addColumn(column);

        Style headerStyle = new Style();
        headerStyle.setFont(new Font(12, fontName, true));
        //headerStyle.setBorder(Border.THIN);
        headerStyle.setHorizontalAlign(HorizontalAlign.CENTER);
        headerStyle.setVerticalAlign(VerticalAlign.MIDDLE);
        headerStyle.setBackgroundColor(new Color(80, 80, 80));
        headerStyle.setTransparency(Transparency.OPAQUE);
        headerStyle.setTextColor(new Color(255, 255, 255));
        column.setHeaderStyle(headerStyle);
    }

    drb.setTitle(pageSetupDlg.getPageTitle());
    drb.setTitleStyle(titleStyle);
    //drb.setTitleHeight(new Integer(30));
    //drb.setSubtitleHeight(new Integer(20));
    //drb.setDetailHeight(new Integer(15));
    //drb.setDefaultStyles(null, null, null, evenRowStyle);

    drb.setLeftMargin(20);
    drb.setRightMargin(20);
    drb.setTopMargin(10);
    drb.setBottomMargin(10);

    drb.setPrintBackgroundOnOddRows(true);
    drb.setOddRowBackgroundStyle(oddRowStyle);
    drb.setColumnsPerPage(new Integer(1));
    drb.setUseFullPageWidth(true);
    drb.setColumnSpace(new Integer(5));

    // This next line causes an exception
    // Event with DynamicReport 3.0.12 and JasperReposrts 3.7.3
    //drb.addAutoText(AutoText.AUTOTEXT_PAGE_X_OF_Y, AutoText.POSITION_FOOTER, AutoText.ALIGMENT_CENTER);

    Page[] pageSizes = new Page[] { Page.Page_Letter_Portrait(), Page.Page_Legal_Portrait(),
            Page.Page_A4_Portrait(), Page.Page_Letter_Landscape(), Page.Page_Legal_Landscape(),
            Page.Page_A4_Landscape() };
    int pageSizeInx = pageSetupDlg.getPageSize() + (pageSetupDlg.isPortrait() ? 0 : 3);
    drb.setPageSizeAndOrientation(pageSizes[pageSizeInx]);

    DynamicReport dr = drb.build();

    return dr;
}

From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java

protected PackageConfig.Builder getPackageConfig(final Map<String, PackageConfig.Builder> packageConfigs,
        String actionNamespace, final String actionPackage, final Class<?> actionClass, Action action) {
    if (action != null && !action.value().equals(Action.DEFAULT_VALUE)) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using non-default action namespace from the Action annotation of [#0]", action.value());
        }//from  w  w w .j av a2  s. co  m
        String actionName = action.value();
        actionNamespace = StringUtils.contains(actionName, "/")
                ? StringUtils.substringBeforeLast(actionName, "/")
                : StringUtils.EMPTY;
    }

    // Next grab the parent annotation from the class
    ParentPackage parent = AnnotationTools.findAnnotation(actionClass, ParentPackage.class);
    String parentName = null;
    if (parent != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using non-default parent package from annotation of [#0]", parent.value());
        }

        parentName = parent.value();
    }

    // Finally use the default
    if (parentName == null) {
        parentName = defaultParentPackage;
    }

    if (parentName == null) {
        throw new ConfigurationException("Unable to determine the parent XWork package for the action class ["
                + actionClass.getName() + "]");
    }

    PackageConfig parentPkg = configuration.getPackageConfig(parentName);
    if (parentPkg == null) {
        throw new ConfigurationException("Unable to locate parent package [" + parentName + "]");
    }

    // Grab based on package-namespace and if it exists, we need to ensure the existing one has
    // the correct parent package. If not, we need to create a new package config
    String name = actionPackage + "#" + parentPkg.getName() + "#" + actionNamespace;
    PackageConfig.Builder pkgConfig = packageConfigs.get(name);
    if (pkgConfig == null) {
        pkgConfig = new PackageConfig.Builder(name).namespace(actionNamespace).addParent(parentPkg);
        packageConfigs.put(name, pkgConfig);

        //check for @DefaultInterceptorRef in the package
        DefaultInterceptorRef defaultInterceptorRef = AnnotationTools.findAnnotation(actionClass,
                DefaultInterceptorRef.class);
        if (defaultInterceptorRef != null) {
            pkgConfig.defaultInterceptorRef(defaultInterceptorRef.value());

            if (LOG.isTraceEnabled())
                LOG.trace("Setting [#0] as the default interceptor ref for [#1]", defaultInterceptorRef.value(),
                        pkgConfig.getName());
        }
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Created package config named [#0] with a namespace [#1]", name, actionNamespace);
    }

    return pkgConfig;
}

From source file:edu.ku.brc.af.ui.forms.persist.ViewLoader.java

/**
 * @param cellName/*  w w  w  .ja v a 2  s. c  o m*/
 * @param cellId
 * @param rowNumber
 */
private static void processFieldVerify(final String cellName, final String cellId, final int rowNumber) {
    try {
        boolean isOK = false;
        if (StringUtils.contains(cellName, '.')) {
            DBTableInfo tblInfo = fldVerTableInfo;
            String[] fieldNames = StringUtils.split(cellName, ".");
            for (int i = 0; i < fieldNames.length - 1; i++) {
                String type = null;
                DBTableChildIFace child = tblInfo.getItemByName(fieldNames[i]);
                if (child instanceof DBFieldInfo) {
                    DBFieldInfo fldInfo = (DBFieldInfo) child;
                    type = fldInfo.getType();
                    if (type != null) {
                        DBTableInfo tInfo = DBTableIdMgr.getInstance().getByClassName(type);
                        tblInfo = tInfo != null ? tInfo : tblInfo;
                    }
                    isOK = tblInfo.getItemByName(fieldNames[fieldNames.length - 1]) != null;

                } else if (child instanceof DBRelationshipInfo) {
                    DBRelationshipInfo relInfo = (DBRelationshipInfo) child;
                    type = relInfo.getDataClass().getName();
                    if (type != null) {
                        tblInfo = DBTableIdMgr.getInstance().getByClassName(type);
                    }
                }
                //System.out.println(type);
            }

            if (tblInfo != null) {
                isOK = tblInfo.getItemByName(fieldNames[fieldNames.length - 1]) != null;
            }
        } else {
            isOK = fldVerTableInfo.getItemByName(cellName) != null;
        }

        if (!isOK) {
            String msg = " ViewSet[" + instance.viewSetName + "]\n ViewDef[" + fldVerFormViewDef.getName()
                    + "]\n The cell name [" + cellName + "] for cell with Id [" + cellId
                    + "] is not a field\n in Data Object[" + fldVerTableInfo.getName() + "]\n on Row ["
                    + rowNumber + "]";
            if (!isTreeClass) {
                instance.fldVerTableModel.addRow(instance.viewSetName, fldVerFormViewDef.getName(), cellId,
                        cellName, Integer.toString(rowNumber));
            }
            log.error(msg);
        }

    } catch (Exception ex) {
        log.error(ex);
    }
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.java

/**
 * Can create a new item or edit an existing it; or view and existing item.
 * @param rowIndex the index tho be editted
 * @param isEdit whether we are editing or view
 * @param isNew hwther the object is new
 *///  ww w. j av  a 2 s.  c o  m
@SuppressWarnings("unchecked")
protected FormDataObjIFace editRow(final FormDataObjIFace dObjArg, final int rowIndex, final boolean isNew) {
    FormDataObjIFace dObj = dObjArg;

    // Add it in here so the Business Rules has a parent object to
    // get state from.
    if (!doSpecialAdd && parentDataObj != null && isEditing && isNew) {
        parentDataObj.addReference(dObj, dataSetFieldName);
    }

    /* XXX bug #9497:
    boolean editable = isEditing && (perm.canModify() || (perm.canAdd() && (isNew || isNewObj(dObj))));
    final ViewBasedDisplayIFace dialog = FormHelper.createDataObjectDialog(mainComp, dObj, editable, isNew);*/

    final ViewBasedDisplayIFace dialog = FormHelper.createDataObjectDialog(mainComp, dObj, isEditing, isNew);
    if (dialog != null) {
        // Now we need to get the MultiView and add it into the MV tree
        MultiView multiView = dialog.getMultiView();

        // Note: The 'real' parent is the parent of the current MultiView
        // this is because the table's MultiView doesn't have a validator.
        MultiView realParent = mvParent.getMultiViewParent();
        if (realParent != null) {
            realParent.addChildMV(multiView);
        }

        multiView.addCurrentValidator();

        if (isNew && multiView.getCurrentViewAsFormViewObj() != null) {
            multiView.getCurrentViewAsFormViewObj().getBusinessRules().addChildrenToNewDataObjects(dObj);
        }

        dialog.setParentData(parentDataObj);

        DataProviderSessionIFace localSession = null;
        try {
            if (!isSkippingAttach) {
                if (dObj.getId() != null) {
                    localSession = DataProviderFactory.getInstance().createSession();
                    //dObj = localSession.merge(dObj);
                    localSession.attach(dObj);
                    try {
                        localSession.attach(dObj);

                    } catch (org.hibernate.HibernateException ex) {
                        String msg = ex.getMessage();
                        if (StringUtils.isNotEmpty(msg) && StringUtils.contains(msg, "dirty collection")) {
                            //dObj = localSession.merge(dObj);
                        }
                    }
                }
                dialog.setSession(localSession);
            }

            if (isNew) {
                FormViewObj fvo = dialog.getMultiView().getCurrentViewAsFormViewObj();
                if (fvo != null) {
                    fvo.setCreatingNewObject(true);
                    if (fvo.getBusinessRules() != null) {
                        fvo.getBusinessRules().afterCreateNewObj(dObj);
                    }
                }
            }
            dialog.setData(dObj);
            if (localSession != null) {
                localSession.close();
                localSession = null;
            }
            dialog.setSession(null);

            dialog.createUI();

            if (addSearch && includeAddBtn && isEditing && isNew) {
                dialog.setDoSave(true);
                dialog.getOkBtn().setText(UIRegistry.getResourceString("SAVE"));
            }
            dialog.showDisplay(true);

        } catch (Exception ex) {
            ex.printStackTrace();
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TableViewObj.class, ex);

        } finally {
            if (localSession != null) {
                localSession.close();
            }
        }

        // OK, now unhook everything (MVs and the validators)
        multiView.removeCurrentValidator();
        if (realParent != null) {
            realParent.removeChildMV(multiView);
        }

        if (isEditing) {
            if (dialog.getBtnPressed() == ViewBasedDisplayIFace.OK_BTN) {
                dialog.getMultiView().getDataFromUI();
                if (mvParent != null) {
                    tellMultiViewOfChange();

                    Object daObj = dialog.getMultiView().getCurrentViewAsFormViewObj() != null
                            ? dialog.getMultiView().getCurrentViewAsFormViewObj().getCurrentDataObj()
                            : null;
                    if (daObj == null) {
                        daObj = dialog.getMultiView().getData();
                    }
                    dObj = daObj instanceof FormDataObjIFace ? (FormDataObjIFace) daObj : dObj;

                    if (isNew) {
                        if (daObj instanceof Orderable) {
                            // They really should all be Orderable, 
                            // but just in case we check each one.
                            int maxOrder = -1;
                            for (Object obj : dataObjList) {
                                if (obj instanceof Orderable) {
                                    maxOrder = Math.max(((Orderable) obj).getOrderIndex(), maxOrder);
                                }
                            }

                            ((Orderable) daObj).setOrderIndex(maxOrder + 1);

                            if (orderUpBtn == null) {
                                addOrderablePanel();
                            }

                        }
                        dataObjList.add(daObj);

                        if (dataObjList != null && dataObjList.size() > 0) {
                            if (dataObjList.get(0) instanceof Comparable<?>) {
                                Collections.sort((List) dataObjList);
                            }
                        }

                        if (origDataSet != null) {
                            origDataSet.add(daObj);
                        }
                        model.setValueAt(daObj, 0, dataObjList.size() - 1);
                    }
                    model.fireDataChanged();
                    table.invalidate();
                    table.repaint();

                    JComponent comp = mvParent.getTopLevel();
                    comp.validate();
                    comp.repaint();
                }

                if (doSpecialAdd && parentDataObj != null && isEditing && isNew) {
                    parentDataObj.addReference(dObj, dataSetFieldName);
                }

            } else if (dialog.isCancelled()) {
                // since it was added in before the dlg was shown we now need to remove.
                if (parentDataObj != null && isEditing && isNew) {
                    parentDataObj.removeReference(dObj, dataSetFieldName);
                }

                if (mvParent.getMultiViewParent() != null) {
                    if (mvParent.getMultiViewParent().getCurrentValidator() != null) {
                        // rods 04/28/11 - it shouldn't turn on the save btn on Cancel
                        //mvParent.getCurrentValidator().setHasChanged(true);
                        mvParent.getMultiViewParent().getCurrentValidator().validateForm();
                    }

                    multiView.getCurrentViewAsFormViewObj().doWasCacelled();
                }
            }
        }
        dialog.dispose();

    } else if (parentDataObj != null) {
        parentDataObj.removeReference(dObj, dataSetFieldName);
    }

    return dObj;
}

From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java

@SuppressWarnings("unchecked")
protected void removeCascadeRule(Class<?> cls, Method method) {

    try {// ww  w  .  j a v  a  2s . co  m
        File f = new File(srcCodeDir.getAbsoluteFile() + File.separator + cls.getSimpleName() + ".java");
        if (!f.exists()) {
            log.error("Can't locate source file[" + f.getAbsolutePath() + "]");
            return;
        }

        List<String> strLines = FileUtils.readLines(f);
        Vector<String> lines = new Vector<String>();

        String methodName = method.getName() + "(";
        int inx = 0;
        for (String line : strLines) {

            if (line.indexOf(methodName) > -1 && line.indexOf("public") > -1) {
                int i = inx;
                int stop = i - 10;
                System.out.println("[" + strLines.get(i) + "]");
                while (!StringUtils.contains(strLines.get(i), "@Cascade") && i > stop) {
                    i--;
                    System.out.println("[" + strLines.get(i) + "]");
                }

                if (i < stop || StringUtils.contains(strLines.get(i), "@Cascade")) {
                    lines.remove(i);
                }
            }
            lines.add(line);
            inx++;
        }

        FileUtils.writeLines(f, lines);

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DatamodelGenerator.class, ex);
        ex.printStackTrace();
    }
}

From source file:edu.ku.brc.dbsupport.MySQLDMBSUserMgr.java

@Override
public boolean verifyEngineAndCharSet(final String dbName) {
    errMsg = null;/*from   w w w  .  j a v a2 s. c o m*/
    Vector<Object[]> rows = BasicSQLUtils.query(connection,
            "select ENGINE,TABLE_COLLATION FROM information_schema.tables WHERE table_schema = '" + dbName
                    + "'");
    if (rows != null && rows.size() > 0) {
        Object[] row = rows.get(0);
        if (row[0] != null && !row[0].toString().equalsIgnoreCase("InnoDB")) {
            errMsg = "The engine is not InnoDB.";
        }
        if (row[1] != null && !StringUtils.contains(row[1].toString(), "utf8")) {
            errMsg = (errMsg == null ? "" : errMsg + "\n") + "The character set is not UTF-8.";
        }
    } else {
        errMsg = "Error checking the database engine and character set.";
    }
    return errMsg == null;
}

From source file:edu.ku.brc.specify.conversion.AgentConverter.java

/**
 * @param oldAgentId//from  ww  w .jav  a2  s . c o  m
 * @param agentIDMapper
 * @param tblWriter
 */
protected void copyAgentFromOldToNew(final Integer oldAgentId, final IdTableMapper agentIDMapper) {
    boolean doDebug = false;

    DBTableInfo agentTI = DBTableIdMgr.getInstance().getByShortClassName("Agent");
    DBFieldInfo lastNameField = agentTI.getFieldByColumnName("LastName");
    DBFieldInfo firstNameField = agentTI.getFieldByColumnName("FirstName");

    StringBuilder sql = new StringBuilder("SELECT ");
    if (BasicSQLUtils.myDestinationServerType != BasicSQLUtils.SERVERTYPE.MS_SQLServer) {
        BasicSQLUtils.removeForeignKeyConstraints(newDBConn, BasicSQLUtils.myDestinationServerType);
    }
    BasicSQLUtils.setIdentityInsertONCommandForSQLServer(newDBConn, "agent",
            BasicSQLUtils.myDestinationServerType);

    List<String> oldAgentFieldNames = getFieldNamesFromSchema(oldDBConn, "agent");

    String oldFieldListStr = buildSelectFieldList(oldAgentFieldNames, "agent");
    sql.append(oldFieldListStr);
    sql.append(" FROM agent WHERE AgentID = " + oldAgentId);

    //log.info(oldFieldListStr);

    List<String> newAgentFieldNames = getFieldNamesFromSchema(newDBConn, "agent");
    String newFieldListStr = buildSelectFieldList(newAgentFieldNames, "agent");

    //log.info(newFieldListStr);

    int lastNameLen = 120;

    HashMap<String, Integer> oldIndexFromNameMap = new HashMap<String, Integer>();
    int inx = 1;
    for (String fldName : oldAgentFieldNames) {
        oldIndexFromNameMap.put(fldName, inx++);
    }

    HashMap<String, Integer> newIndexFromNameMap = new HashMap<String, Integer>();
    inx = 1;
    for (String fldName : newAgentFieldNames) {
        newIndexFromNameMap.put(fldName, inx++);
    }

    try {
        // So first we hash each AddressID and the value is set to 0 (false)
        Statement stmtX = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        ResultSet rsX = stmtX.executeQuery(sql.toString());

        int agentIDInx = oldIndexFromNameMap.get("AgentID");
        int agentTypeInx = oldIndexFromNameMap.get("AgentType");
        int nameInx = oldIndexFromNameMap.get("Name");
        int lastNameInx = oldIndexFromNameMap.get("LastName");
        int firstNameInx = oldIndexFromNameMap.get("FirstName");

        // log.debug(sql.toString());

        int cnt = 0;
        while (rsX.next()) {
            int agentId = rsX.getInt(1);

            StringBuilder sqlStr = new StringBuilder();
            sqlStr.append("INSERT INTO agent ");
            sqlStr.append("(" + newFieldListStr);
            sqlStr.append(")");
            sqlStr.append(" VALUES (");

            int fCnt = 0;
            for (String fieldName : newAgentFieldNames) {
                if (fCnt > 0)
                    sqlStr.append(", ");

                if (StringUtils.contains(fieldName.toLowerCase(), "disciplineid")) {
                    sqlStr.append(conv.getDisciplineId());

                } else if (StringUtils.contains(fieldName, "FirstName")) {
                    String firstName = rsX.getString(firstNameInx);
                    if (firstName != null && firstName.length() > firstNameField.getLength()) {
                        String str = firstName.substring(0, firstNameField.getLength());
                        tblWriter.logError("Agent id: " + rsX.getString(agentIDInx)
                                + " - Concatinating First Name FROM [" + firstName + "] to [" + str + "]");
                        firstName = str;
                    }
                    sqlStr.append(BasicSQLUtils.getStrValue(firstName));

                } else if (StringUtils.contains(fieldName, "LastName")) {
                    int oldType = rsX.getInt(agentTypeInx);
                    int srcColInx = oldType != 1 ? nameInx : lastNameInx;
                    String lName = rsX.getString(srcColInx);

                    if (lName == null && oldType != 1) {
                        lName = rsX.getString(lastNameInx);
                    }

                    if (lName != null && lName.length() > lastNameField.getLength()) {
                        String str = lName.substring(0, firstNameField.getLength());
                        tblWriter.logError("Agent id: " + rsX.getString(agentIDInx)
                                + " - Concatinating Last Name FROM [" + lName + "] to [" + str + "]");
                        lName = str;
                    }

                    String lstName = lName;
                    lName = lstName == null ? null
                            : lstName.length() <= lastNameLen ? lstName : lstName.substring(0, lastNameLen);

                    sqlStr.append(BasicSQLUtils.getStrValue(lName));

                } else {
                    String value = "";
                    Integer index;

                    if (fieldName.equals("ModifiedByAgentID")) {
                        index = oldIndexFromNameMap.get("LastEditedBy");
                    } else {
                        index = oldIndexFromNameMap.get(fieldName);
                    }

                    if (index == null) {
                        // log.debug(fieldName);
                        value = "NULL";

                    } else if (fCnt == 0) {
                        value = agentIDMapper.get(agentId).toString();

                    } else {
                        value = BasicSQLUtils.getStrValue(rsX.getObject(index.intValue()));
                    }

                    BasicSQLUtilsMapValueIFace valueMapper = conv.getColumnValueMapper().get(fieldName);
                    if (valueMapper != null) {
                        value = valueMapper.mapValue(value);
                    }
                    sqlStr.append(value);
                }
                fCnt++;
            }
            sqlStr.append(")");
            // log.info(sqlStr.toString());

            Statement updateStatement = newDBConn.createStatement();
            // updateStatement.executeUpdate("SET FOREIGN_KEY_CHECKS = 0");
            if (doDebug) {
                log.info(sqlStr.toString());
            }
            updateStatement.executeUpdate(sqlStr.toString(), Statement.RETURN_GENERATED_KEYS);
            Integer newAgentId = BasicSQLUtils.getInsertedId(updateStatement);
            if (newAgentId == null) {
                throw new RuntimeException("Couldn't get the Agent's inserted ID");
            }
            updateStatement.clearBatch();
            updateStatement.close();
            updateStatement = null;

            //conv.addAgentDisciplineJoin(newAgentId, conv.getDisciplineId());

            cnt++;
            BasicSQLUtils.setIdentityInsertOFFCommandForSQLServer(newDBConn, "agent",
                    BasicSQLUtils.myDestinationServerType);

        }
    } catch (Exception ex) {
        log.error(ex);
        ex.printStackTrace();
        System.exit(0);
    }
}