Example usage for java.util Vector insertElementAt

List of usage examples for java.util Vector insertElementAt

Introduction

In this page you can find the example usage for java.util Vector insertElementAt.

Prototype

public synchronized void insertElementAt(E obj, int index) 

Source Link

Document

Inserts the specified object as a component in this vector at the specified index .

Usage

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

/**
 * Returns a list of aggregators that match the class, the default (if there is one) is at the beginning of the list.
 * @param clazz the class of the data that the aggregator is used for.
 * @return return a list of aggregators that match the class
 *///  w w w.  ja  v a  2s  .  c  om
public List<DataObjAggregator> getAggregatorList(final Class<?> clazz) {
    Vector<DataObjAggregator> list = new Vector<DataObjAggregator>();
    DataObjAggregator defFormatter = null;

    for (Enumeration<DataObjAggregator> e = aggHash.elements(); e.hasMoreElements();) {
        DataObjAggregator f = e.nextElement();
        if (clazz == f.getDataClass()) {
            if (f.isDefault() && defFormatter == null) {
                defFormatter = f;
            } else {
                list.add(f);
            }
        }
    }
    if (defFormatter != null) {
        list.insertElementAt(defFormatter, 0);
    }
    return list;
}

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

/**
 * Returns a list of formatters that match the class, the default (if there is one) is at the beginning of the list.
 * @param clazz the class of the data that the formatter is used for.
 * @return return a list of formatters that match the class
 *///w w w .j a va 2s  .  c om
public List<DataObjSwitchFormatter> getFormatterList(final Class<?> clazz) {
    Vector<DataObjSwitchFormatter> list = new Vector<DataObjSwitchFormatter>();
    DataObjSwitchFormatter defFormatter = null;

    for (Enumeration<DataObjSwitchFormatter> e = formatHash.elements(); e.hasMoreElements();) {
        DataObjSwitchFormatter f = e.nextElement();
        if (clazz == f.getDataClass()) {
            if (f.isDefault() && defFormatter == null) {
                defFormatter = f;
            } else {
                list.add(f);
            }
        }
    }
    if (defFormatter != null) {
        list.insertElementAt(defFormatter, 0);
    }
    return list;
}

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

/**
 * Returns a list of formatters that match the class, the default (if there
 * is one) is at the beginning of the list.
 * //  w  w w  .  ja v a 2 s  .co m
 * @param clazz the class of the data that the formatter is used for.
 * @return return a list of formatters that match the class
 */
public List<UIFieldFormatterIFace> getFormatterList(final Class<?> clazz, final String fieldName) {
    if (fieldName == null) {
        Vector<UIFieldFormatterIFace> list = classToListHash.get(clazz);
        if (list != null) {
            return list;
        }
    }

    Vector<UIFieldFormatterIFace> list = new Vector<UIFieldFormatterIFace>();

    UIFieldFormatterIFace defFormatter = null;
    for (Enumeration<UIFieldFormatterIFace> e = hash.elements(); e.hasMoreElements();) {
        UIFieldFormatterIFace fmt = e.nextElement();
        //log.debug(fmt.getTitle()+" - "+fmt.getDataClass().getSimpleName()+" - "+clazz.getSimpleName());
        if (clazz == fmt.getDataClass()
                && (fieldName == null || (fieldName.equals(fmt.getFieldName()) || fieldName.equals("*")))) {
            if (fmt.isDefault() && defFormatter == null) {
                defFormatter = fmt;
            } else {
                list.add(fmt);
            }
        }
    }

    if (defFormatter != null) {
        list.insertElementAt(defFormatter, 0);
    }

    if (fieldName == null) {
        classToListHash.put(clazz, list);
    }

    return list;
}

From source file:edu.ku.brc.specify.toycode.L18NStringResApp.java

/**
 * @param file//from   w w w.java  2s .c o  m
 */
protected void copyNewLines(final File file) {
    String dirName = RES_PATH + "values-" + destLocale.getLanguage();
    String dstPath = dirName + File.separator + file.getName();

    try {
        List<String> srcLines = (List<String>) FileUtils.readLines(file, "UTF8");
        Vector<String> dstLines = new Vector<String>(
                (List<String>) FileUtils.readLines(new File(dstPath), "UTF8"));

        int dstCnt = 0;
        for (int i = 0; i < srcLines.size(); i++) {

            String srcLine = srcLines.get(i);
            String dstLine = dstLines.get(dstCnt++);

            if (StringUtils.contains(srcLine, "<?xml") && StringUtils.contains(dstLine, "<?xml"))
                continue;
            if (StringUtils.contains(srcLine, "<res") && StringUtils.contains(dstLine, "<res"))
                continue;
            if (StringUtils.contains(srcLine, "</res") && StringUtils.contains(dstLine, "</res"))
                continue;

            srcLine = StringUtils.replace(srcLine, "\\ \'", "\\\'");
            srcLine = StringUtils.replace(srcLine, "s \\\'", "s\\\'");

            dstLine = StringUtils.replace(dstLine, "\\ \'", "\\\'");
            dstLine = StringUtils.replace(dstLine, "s \\ \'", "s\\\'");

            System.out.println("--- [" + srcLine + "][" + dstLine + "] -- ");

            if (srcLine.equals(dstLine))
                continue;

            boolean isSrcComment = StringUtils.contains(srcLine, "<!--");
            boolean isDstComment = StringUtils.contains(dstLine, "<!--");

            String srcKey = !isSrcComment ? getKey(srcLine) : "";
            String dstKey = !isDstComment ? getKey(dstLine) : "";

            if (srcKey != null && dstKey != null && srcKey.equals(dstKey) && srcKey.length() > 0)
                continue;

            dstLines.insertElementAt(srcLine, dstCnt++);
        }

        System.out.println("----------------------------");
        for (int i = 0; i < srcLines.size(); i++) {
            String srcLine = srcLines.get(i);
            String dstLine = dstLines.get(i);

            srcLine = StringUtils.replace(srcLine, "\\ \'", "\\\'");
            srcLine = StringUtils.replace(srcLine, "s \\\'", "s\\\'");

            dstLine = StringUtils.replace(dstLine, "\\ \'", "\\\'");
            dstLine = StringUtils.replace(dstLine, "s \\ \'", "s\\\'");

            System.out.println("--- [" + srcLine + "] " + srcLine.length() + "  [" + dstLine + "] "
                    + dstLine.length() + " -- ");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.ku.brc.specify.utilapps.RegisterApp.java

/**
 * // w  w  w  .j  av  a 2 s  .c om
 */
@SuppressWarnings("unchecked")
protected void doSetVersion() {
    CellConstraints cc = new CellConstraints();

    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,2px,f:p:g"));

    Vector<String> versionsList = new Vector<String>();
    Hashtable<String, String> verToDateHash = new Hashtable<String, String>();
    try {
        SimpleDateFormat mmddyyyy = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat yyyymmdd = new SimpleDateFormat("yyyy/MM/dd");
        List<String> lines = FileUtils.readLines(rp.getDataFromWeb(
                UIRegistry.getResourceString("CGI_BASE_URL") + "/specifydownloads/specify6/alpha/versions.txt",
                false));
        for (String line : lines) {
            String[] toks = line.split(",");
            if (toks.length > 2) {
                String ver = StringUtils.remove(toks[1].trim(), "Alpha ");

                versionsList.insertElementAt(ver, 0);

                String dateStr = toks[2].trim();
                dateStr = StringUtils.replace(dateStr, ".", "/");
                try {
                    Date date = mmddyyyy.parse(dateStr);
                    verToDateHash.put(ver, yyyymmdd.format(date));

                } catch (Exception ex) {
                }
            }
        }
        versionsList.insertElementAt("Clear", 0);

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

    final JList list = new JList(versionsList);
    final CustomDialog dlg = new CustomDialog(null, "Set Version", true, pb.getPanel());

    pb.add(UIHelper.createLabel("Versions", SwingConstants.CENTER), cc.xy(1, 1));
    pb.add(UIHelper.createScrollPane(list), cc.xy(1, 3));

    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                dlg.getOkBtn().setEnabled(list.getSelectedIndex() > -1);
            }
        }
    });
    list.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);
            if (e.getClickCount() == 2) {
                dlg.getOkBtn().doClick();
            }
        }

    });

    pb.setDefaultDialogBorder();

    dlg.createUI();
    dlg.getOkBtn().setEnabled(false);

    dlg.setVisible(true);
    if (!dlg.isCancelled()) {
        int inx = list.getSelectedIndex();
        String version = (String) list.getSelectedValue();

        if (version.equals("Clear")) {
            rp.setVersionDates(null, null, null);
            frame.setTitle(title);
        } else {
            String prevVersion = inx == list.getModel().getSize() - 1 ? null
                    : (String) list.getModel().getElementAt(inx + 1);
            rp.setVersionDates(version, prevVersion, verToDateHash);
            frame.setTitle(title + " for " + version);
        }

        /*try
        {
        rp.process(doLocal ? new File("reg.dat") : rp.getDataFromWeb("SpReg.REGISTER_URL", true));
        rp.processTracks(doLocal ? new File("track.dat") : rp.getDataFromWeb("StatsTrackerTask.URL", true));
        rp.mergeStats();
                
        } catch (IOException ex)
        {
        ex.printStackTrace();
        }*/

    }
}

From source file:edu.ku.brc.specify.ui.db.ResultSetTableModel.java

@Override
//@SuppressWarnings("null")
public synchronized void exectionDone(final SQLExecutionProcessor process, final ResultSet resultSet) {
    if (statusBar != null) {
        statusBar.incrementValue(getClass().getSimpleName());
    }//w  w w. jav  a  2  s  . c  o  m

    if (resultSet == null || results == null) {
        log.error("The " + (resultSet == null ? "resultSet" : "results") + " is null.");
        if (propertyListener != null) {
            propertyListener.propertyChange(new PropertyChangeEvent(this, "rowCount", null, 0));
        }
        return;
    }

    List<ERTICaptionInfo> captions = results.getVisibleCaptionInfo();

    // This can do one of two things:
    // 1) Take multiple columns and create an object and use a DataObjectFormatter to format the object.
    // 2) Table multiple objects that were derived from the columns and roll those up into a single column's value.
    //    This happens when you get back rows of info where part of the columns are duplicated because you really
    //    want those value to be put into a single column.
    //
    // Step One - Is to figure out what type of object needs to be created and what the Columns are 
    //            that need to be set into the object so the dataObjFormatter can do its job.
    //
    // Step Two - If the objects are being aggregated then the object created from the columns are added to a List
    //            and then last formatted as an "aggregation"

    try {
        if (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();

            // Composite
            boolean hasCompositeObj = false;
            DataObjSwitchFormatter dataObjFormatter = null;
            UIFieldFormatterIFace formatter = null;
            Object compObj = null;

            // Aggregates
            ERTICaptionInfo aggCaption = null;
            ERTICaptionInfo compositeCaption = null;
            Vector<Object> aggList = null;
            DataObjectSettable aggSetter = null;
            Stack<Object> aggListRecycler = null;

            DataObjectSettable dataSetter = null; // data getter for Aggregate or the Subclass

            // Loop through the caption to figure out what columns will be displayed.
            // Watch for Captions with an Aggregator or Composite 
            numColumns = captions.size();
            for (ERTICaptionInfo caption : captions) {
                colNames.addElement(caption.getColLabel());

                int inx = caption.getPosIndex() + 1;
                //log.debug(metaData.getColumnClassName(inx));
                Class<?> cls = null;
                try {
                    cls = Class.forName(metaData.getColumnClassName(inx));
                    if (cls == Calendar.class || cls == java.sql.Date.class || cls == Date.class) {
                        cls = String.class;
                    }
                } catch (SQLException ex) {
                    cls = String.class;
                }
                classNames.addElement(cls);
                caption.setColClass(cls);

                if (caption.getAggregatorName() != null) {
                    //log.debug("The Agg is ["+caption.getAggregatorName()+"] "+caption.getColName());

                    // Alright we have an aggregator
                    aggList = new Vector<Object>();
                    aggListRecycler = new Stack<Object>();
                    aggCaption = caption;
                    aggSetter = DataObjectSettableFactory.get(aggCaption.getAggClass().getName(),
                            FormHelper.DATA_OBJ_SETTER);

                    // Now check to see if we are aggregating the this type of object or a child object of this object
                    // For example Collectors use an Agent as part of the aggregation
                    if (aggCaption.getSubClass() != null) {
                        dataSetter = DataObjectSettableFactory.get(aggCaption.getSubClass().getName(),
                                FormHelper.DATA_OBJ_SETTER);
                    } else {
                        dataSetter = aggSetter;
                    }

                } else if (caption.getColInfoList() != null) {
                    formatter = caption.getUiFieldFormatter();
                    if (formatter != null) {
                        compositeCaption = caption;
                    } else {
                        // OK, now aggregation but we will be rolling up multiple columns into a single object for formatting
                        // We need to get the formatter to see what the Class is of the object
                        hasCompositeObj = true;
                        aggCaption = caption;
                        dataObjFormatter = caption.getDataObjFormatter();
                        if (dataObjFormatter != null) {
                            if (dataObjFormatter.getDataClass() != null) {
                                aggSetter = DataObjectSettableFactory.get(
                                        dataObjFormatter.getDataClass().getName(),
                                        "edu.ku.brc.af.ui.forms.DataSetterForObj");
                            } else {
                                log.error("formatterObj.getDataClass() was null for " + caption.getColName());
                            }
                        } else {
                            log.error("DataObjFormatter was null for " + caption.getColName());
                        }
                    }

                }
                //colNames.addElement(metaData.getColumnName(i));
                //System.out.println("**************** " + caption.getColLabel()+ " "+inx+ " " + caption.getColClass().getSimpleName());
            }

            // aggCaption will be non-null for both a Aggregate AND a Composite
            if (aggCaption != null) {
                // Here we need to dynamically discover what the column indexes are that we to grab
                // in order to set them into the created data object
                for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) {
                    for (int i = 0; i < metaData.getColumnCount(); i++) {
                        String colName = StringUtils.substringAfterLast(colInfo.getColumnName(), ".");
                        if (colName.equalsIgnoreCase(metaData.getColumnName(i + 1))) {
                            colInfo.setPosition(i);
                            break;
                        }
                    }
                }

                // Now check to see if there is an Order Column because the Aggregator 
                // might need it for sorting the Aggregation
                String ordColName = aggCaption.getOrderCol();
                if (StringUtils.isNotEmpty(ordColName)) {
                    String colName = StringUtils.substringAfterLast(ordColName, ".");
                    //log.debug("colName ["+colName+"]");
                    for (int i = 0; i < metaData.getColumnCount(); i++) {
                        //log.debug("["+colName+"]["+metaData.getColumnName(i+1)+"]");
                        if (colName.equalsIgnoreCase(metaData.getColumnName(i + 1))) {
                            aggCaption.setOrderColIndex(i);
                            break;
                        }
                    }
                    if (aggCaption.getOrderColIndex() == -1) {
                        log.error("Agg Order Column Index wasn't found [" + ordColName + "]");
                    }
                }
            }

            if (ids == null) {
                ids = new Vector<Integer>();
            } else {
                ids.clear();
            }

            // Here is the tricky part.
            // When we are doing a Composite we are just taking multiple columns and 
            // essentially replace them with a single value from the DataObjFormatter
            //
            // But when doing an Aggregation we taking several rows and rolling them up into a single value.
            // so this code knows when it is doing an aggregation, so it knows to only add a new row to the display-able
            // results when primary id changes.

            DataObjFieldFormatMgr dataObjMgr = DataObjFieldFormatMgr.getInstance();
            Vector<Object> row = null;
            boolean firstTime = true;
            int prevId = Integer.MAX_VALUE; // really can't assume any value but will choose Max

            int numCols = resultSet.getMetaData().getColumnCount();
            do {
                int id = resultSet.getInt(1);
                //log.debug("id: "+id+"  prevId: "+prevId);

                // Remember aggCaption is used by both a Aggregation and a Composite
                if (aggCaption != null && !hasCompositeObj) {
                    if (firstTime) {
                        prevId = id;
                        row = new Vector<Object>();
                        firstTime = false;
                        cache.add(row);
                        ids.add(id);

                    } else if (id != prevId) {
                        //log.debug("Agg List len: "+aggList.size());

                        if (row != null && aggList != null) {
                            int aggInx = captions.indexOf(aggCaption);
                            row.remove(aggInx);
                            row.insertElementAt(dataObjMgr.aggregate(aggList, aggCaption.getAggClass()),
                                    aggInx);

                            if (aggListRecycler != null) {
                                aggListRecycler.addAll(aggList);
                            }
                            aggList.clear();

                            row = new Vector<Object>();
                            cache.add(row);
                            ids.add(id);
                        }
                        prevId = id;

                    } else if (row == null) {
                        row = new Vector<Object>();
                        cache.add(row);
                        ids.add(id);
                    }
                } else {
                    row = new Vector<Object>();
                    cache.add(row);
                    ids.add(id);
                }

                // Now for each Caption column get a value
                for (ERTICaptionInfo caption : captions) {
                    int posIndex = caption.getPosIndex();
                    if (caption == aggCaption) // Checks to see if we need to take multiple columns and make one column
                    {
                        if (hasCompositeObj) // just doing a Composite
                        {
                            if (aggSetter != null && row != null && dataObjFormatter != null) {
                                if (compObj == null) {
                                    compObj = aggCaption.getAggClass().newInstance();
                                }

                                for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) {
                                    setField(aggSetter, compObj, colInfo.getFieldName(),
                                            colInfo.getFieldClass(), resultSet, colInfo.getPosition());
                                }
                                row.add(DataObjFieldFormatMgr.getInstance().format(compObj,
                                        compObj.getClass()));

                            } else if (formatter != null) {
                                int len = compositeCaption.getColInfoList().size();
                                Object[] val = new Object[len];
                                int i = 0;
                                for (ERTICaptionInfo.ColInfo colInfo : compositeCaption.getColInfoList()) {
                                    int colInx = colInfo.getPosition() + posIndex + 1;
                                    if (colInx < numCols) {
                                        val[i++] = resultSet.getObject(colInx);
                                    } else {
                                        //val[i++] = resultSet.getObject(posIndex+1);
                                        val[i++] = "(Missing Data)";
                                    }
                                }
                                row.add(formatter.formatToUI(val));

                            } else {
                                log.error("Aggregator is null! [" + aggCaption.getAggregatorName()
                                        + "] or row or aggList");
                            }
                        } else if (aggSetter != null && row != null && aggList != null) // Doing an Aggregation
                        {
                            Object aggObj;
                            if (aggListRecycler.size() == 0) {
                                aggObj = aggCaption.getAggClass().newInstance();
                            } else {
                                aggObj = aggListRecycler.pop();
                            }
                            Object aggSubObj = aggCaption.getSubClass() != null
                                    ? aggCaption.getSubClass().newInstance()
                                    : null;
                            aggList.add(aggObj);

                            //@SuppressWarnings("unused")
                            //DataObjAggregator aggregator = DataObjFieldFormatMgr.getInstance().getAggregator(aggCaption.getAggregatorName());
                            //log.debug(" aggCaption.getOrderColIndex() "+ aggCaption.getOrderColIndex());

                            //aggSetter.setFieldValue(aggObj, aggregator.getOrderFieldName(), resultSet.getObject(aggCaption.getOrderColIndex() + 1));

                            Object dataObj;
                            if (aggSubObj != null) {
                                aggSetter.setFieldValue(aggObj, aggCaption.getSubClassFieldName(), aggSubObj);
                                dataObj = aggSubObj;
                            } else {
                                dataObj = aggObj;
                            }

                            for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) {
                                setField(dataSetter, dataObj, colInfo.getFieldName(), colInfo.getFieldClass(),
                                        resultSet, colInfo.getPosition());
                            }
                            row.add("PlaceHolder");

                        } else if (aggSetter == null || aggList == null) {
                            log.error("Aggregator is null! [" + aggCaption.getAggregatorName() + "] or aggList["
                                    + aggList + "]");
                        }

                    } else if (row != null) {
                        if (caption.getColName() == null && caption.getColInfoList().size() > 0) {
                            int len = caption.getColInfoList().size();
                            Object[] val = new Object[len];
                            for (int i = 0; i < caption.getColInfoList().size(); i++) {
                                int inx = posIndex + 1 + i;
                                val[i] = caption.processValue(resultSet.getObject(inx));
                            }
                            row.add(caption.getUiFieldFormatter().formatToUI(val));
                            //col += caption.getColInfoList().size() - 1;

                        } else {
                            Object obj = caption.processValue(resultSet.getObject(posIndex + 1));
                            row.add(obj);
                        }
                    }
                }

            } while (resultSet.next());

            // We were always setting the rolled up data when the ID changed
            // but on the last row we need to do it here manually (so to speak)
            if (aggCaption != null && aggList != null && aggList.size() > 0 && row != null) {
                int aggInx = captions.indexOf(aggCaption);
                row.remove(aggInx);
                String colStr;
                if (StringUtils.isNotEmpty(aggCaption.getAggregatorName())) {
                    colStr = DataObjFieldFormatMgr.getInstance().aggregate(aggList,
                            aggCaption.getAggregatorName());

                } else {
                    colStr = DataObjFieldFormatMgr.getInstance().aggregate(aggList, aggCaption.getAggClass());
                }
                row.insertElementAt(colStr, aggInx);
                aggList.clear();
                aggListRecycler.clear();
            }

            fireTableStructureChanged();
            fireTableDataChanged();
        }

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

    if (propertyListener != null) {
        propertyListener
                .propertyChange(new PropertyChangeEvent(this, "rowCount", null, new Integer(cache.size())));
    }
}

From source file:com.almarsoft.GroundhogReader.lib.MessageTextProcessor.java

public static Vector<HashMap<String, String>> saveUUEncodedAttachments(BufferedReader bodyTextReader,
        String group) throws IOException {

    Vector<HashMap<String, String>> bodyAttachments = new Vector<HashMap<String, String>>(1);
    String newBody = null;/*  ww w .j  a  v a2  s  .c  o m*/
    Vector<HashMap<String, String>> attachDatas = null;

    StringBuilder newBodyBuilder = new StringBuilder();
    StringBuilder attachment = new StringBuilder();

    boolean inAttach = false;
    boolean firstOfTheEnd = false;

    String line, sline, filename = null;
    HashMap<String, String> attachData = null;

    attachDatas = new Vector<HashMap<String, String>>();

    while ((line = bodyTextReader.readLine()) != null) {

        // XXX: Probar a quitar esto (optimizacion)
        sline = line.trim();

        if (sline.equals("`")) {
            firstOfTheEnd = true;
            attachment.append(line + "\n");
        }

        else if (firstOfTheEnd && inAttach && sline.equals("end")) {

            attachment.append(line + "\n");
            if (attachDatas == null)
                attachDatas = new Vector<HashMap<String, String>>();

            try {
                attachData = FSUtils.saveUUencodedAttachment(attachment.toString(), filename, group);
                attachDatas.add(attachData);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (UsenetReaderException e) {
                e.printStackTrace();
            }
            attachment = null;
            inAttach = false;
            firstOfTheEnd = false;
        }

        else if (firstOfTheEnd && inAttach && !sline.equals("end")) {
            firstOfTheEnd = false; // False alarm?
        }

        // XXX: ESTO NO SOPORTA UUENCODED SIN PERMISOS!!!
        else if (sline.length() >= 11 && sline.substring(0, 6).equals("begin ")
                && Character.isDigit(sline.charAt(6)) && Character.isDigit(sline.charAt(7))
                && Character.isDigit(sline.charAt(8)) && Character.isWhitespace(sline.charAt(9))
                && !Character.isWhitespace(sline.charAt(10))) {

            filename = sline.substring(10);
            inAttach = true;
            attachment.append(line + "\n");
        }

        else if (inAttach) {
            attachment.append(line + "\n");
        }

        else {
            newBodyBuilder.append(line + "\n");
        }

    }
    newBody = newBodyBuilder.toString();

    // Add the new body as first element
    HashMap<String, String> bodyMap = new HashMap<String, String>(1);
    bodyMap.put("body", newBody);
    bodyAttachments.add(bodyMap);

    if (attachDatas != null) {
        for (HashMap<String, String> attData : attachDatas) {
            bodyAttachments.insertElementAt(attData, 1);
        }
    }

    return bodyAttachments;
}

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

/**
 * If the colInfo Vector is null then all the templates are added to the list to be displayed.<br>
 * If not, then it checks all the column in the file against the columns in each Template to see if there is a match
 * and then uses that./*from w w w.  j a va2s .  co  m*/
 * show a Dialog and returns null if there are not templates or none match.
 * @param colInfo the column info
 * @param helpContext the help context
 * 
 * @return a List. The first element in the pair is false then the selection was cancelled. 
 * Otherwise, the second element will be the selected WorkbenchTemplate or null if a new template should be created,
 * and the third element will be a list of columns that are not used in the selected template
 */
public List<?> selectExistingTemplate(final Vector<ImportColumnInfo> colInfo, final String helpContext) {
    WorkbenchTemplate selection = null;

    if (colInfo != null) {
        Collections.sort(colInfo);
    }

    Vector<WorkbenchTemplate> matchingTemplates = new Vector<WorkbenchTemplate>();
    HashMap<WorkbenchTemplate, Vector<?>> unMappedCols = new HashMap<WorkbenchTemplate, Vector<?>>();

    // Check for any matches with existing templates
    DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
    try {
        //List<?> list = session.getDataList("From WorkbenchTemplate where SpecifyUserID = " + AppContextMgr.getInstance().getClassObject(SpecifyUser.class).getSpecifyUserId());
        List<?> list = session.getDataList("From WorkbenchTemplate");
        for (Object obj : list) {
            WorkbenchTemplate template = (WorkbenchTemplate) obj;
            if (colInfo == null) {
                template.forceLoad();
                matchingTemplates.add(template);

                //} else if (colInfo.size() <= template.getWorkbenchTemplateMappingItems().size())
            } else if (colInfo.size() == template.getWorkbenchTemplateMappingItems().size()) {
                boolean match = true;
                Vector<WorkbenchTemplateMappingItem> items = new Vector<WorkbenchTemplateMappingItem>(
                        template.getWorkbenchTemplateMappingItems());
                Vector<ImportColumnInfo> mapped = new Vector<ImportColumnInfo>();
                for (ImportColumnInfo col : colInfo) {
                    int idx = indexOfName(items, col.getColName());
                    if (idx != -1) {
                        mapped.add(col);
                        items.get(idx).setViewOrder(Short.valueOf(col.getColInx().toString()));
                        items.get(idx).setOrigImportColumnIndex(Short.valueOf(col.getColInx().toString()));
                    } else {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    Vector<WorkbenchTemplateMappingItem> unmapped = new Vector<WorkbenchTemplateMappingItem>();
                    for (WorkbenchTemplateMappingItem item : items) {
                        if (indexOfName(mapped, item.getImportedColName()) == -1) {
                            unmapped.add(item);
                            //item.setViewOrder(c++);
                        }
                    }
                    if (unmapped.size() == 0) {
                        matchingTemplates.insertElementAt(template, 0); //put full matches at head of list
                    } else {
                        matchingTemplates.add(template);
                    }
                    unMappedCols.put(template, unmapped);
                    //for (WorkbenchTemplateMappingItem unmappedItem : unmapped)
                    //{
                    //   template.getWorkbenchTemplateMappingItems().remove(unmappedItem);
                    //}
                }
            }
            //                else if (colInfo.size() > template.getWorkbenchTemplateMappingItems().size())
            //                {
            //                    boolean match = true;
            //                    Vector<WorkbenchTemplateMappingItem> items = new Vector<WorkbenchTemplateMappingItem>(template.getWorkbenchTemplateMappingItems());
            //                    Vector<ImportColumnInfo> mapped = new Vector<ImportColumnInfo>();
            //                    for (WorkbenchTemplateMappingItem item : items)
            //                    {
            //                       int idx = indexOfName(colInfo, item.getImportedColName());
            //                       if (idx != -1)
            //                       {
            //                          mapped.add(colInfo.get(idx));
            //                          item.setViewOrder(Short.valueOf(colInfo.get(idx).getColInx().toString()));
            //                          item.setOrigImportColumnIndex(Short.valueOf(colInfo.get(idx).getColInx().toString()));
            //                       }
            //                    }
            //                    for (int i=0; i<items.size(); i++)
            //                    {
            //                        WorkbenchTemplateMappingItem wbItem = items.get(i);
            //                        int origIdx = wbItem.getOrigImportColumnIndex().intValue();
            //                        if (origIdx == -1)
            //                        {
            //                           //try the viewOrder
            //                           origIdx = wbItem.getViewOrder().intValue();
            //                        }
            //                        ImportColumnInfo fileItem = origIdx > -1 && origIdx < colInfo.size() ? colInfo.get(origIdx) : null;
            //                        // Check to see if there is an exact match by name
            //                        if (colsMatchByName(wbItem, fileItem))
            //                        {
            //                           //might do additional type checking
            //                           mapped.add(fileItem);
            //                        }
            //                        else
            //                        {
            //                            //log.error("["+wbItem.getImportedColName()+"]["+fileItem.getColName()+"]");
            //                            match = false;
            //                            break;
            //                        }
            //                    }
            //                    // All columns match with their order etc.
            //                    if (match)
            //                    {
            //                        matchingTemplates.add(template);
            //                        Vector<ImportColumnInfo> unmapped = new Vector<ImportColumnInfo>();
            //                        for (ImportColumnInfo fileItem : colInfo)
            //                        {
            //                           if (mapped.indexOf(fileItem) == -1)
            //                           {
            //                              unmapped.add(fileItem);
            //                           }
            //                        }
            //                        unMappedCols.put(template, unmapped);
            //                    }
            //                }
        }

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

    } finally {
        session.close();
    }

    Vector<Object> result = new Vector<Object>();
    // Ask the user to choose an existing template.
    if (matchingTemplates.size() > 0) {
        SelectNewOrExistingDlg<WorkbenchTemplate> dlg = new SelectNewOrExistingDlg<WorkbenchTemplate>(
                (Frame) UIRegistry.get(UIRegistry.FRAME), "WB_CHOOSE_DATASET_REUSE_TITLE",
                "WB_CREATE_NEW_MAPPING", "WB_USE_EXISTING_MAPPING", helpContext, matchingTemplates);

        UIHelper.centerAndShow(dlg);

        if (dlg.getBtnPressed() == ChooseFromListDlg.OK_BTN) {
            if (!dlg.isCreateNew()) {
                selection = dlg.getSelectedObject();
                Vector<?> unmapped = unMappedCols.get(selection);
                if (unmapped != null && unmapped.size() > 0) {
                    StringBuilder flds = new StringBuilder();
                    for (Object info : unmapped) //if there are a lot of these the message will be ugly
                    {
                        if (flds.length() != 0) {
                            flds.append(", ");
                        }
                        flds.append(info.toString());
                    }
                    String msg = unmapped.get(0) instanceof ImportColumnInfo
                            ? String.format(UIRegistry.getResourceString("WB_UNMAPPED_NOT_IMPORTED"),
                                    flds.toString())
                            : String.format(UIRegistry.getResourceString("WB_UNUSED_NOT_INCLUDED"),
                                    flds.toString());
                    if (!UIRegistry.displayConfirm(UIRegistry.getResourceString("WB_INCOMPLETE_MAP_TITLE"), msg,
                            UIRegistry.getResourceString("YES"), UIRegistry.getResourceString("NO"),
                            JOptionPane.WARNING_MESSAGE)) {
                        result.add(true);
                        return result; // means create a new one
                    }
                }

                //                    for (WorkbenchTemplateMappingItem mi : selection.getWorkbenchTemplateMappingItems())
                //                    {
                //                       System.out.println(mi.getImportedColName() + " - " + mi.getViewOrder());
                //                    }
                result.add(true);
                result.add(selection);
                result.add(unMappedCols.get(selection));
                return result; // means reuse an existing one
            }
            result.add(true);
            return result; // means create a new one
        }
        result.add(false);
        return result; //cancelled
    }
    result.add(true);
    return result; // means create a new one
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * @return//w  ww  . j av a  2s . com
 */
protected Pair<WorkbenchTemplateMappingItem, List<WorkbenchTemplateMappingItem>> selectColumnName() {
    WorkbenchTemplateMappingItem genus = null;
    WorkbenchTemplateMappingItem species = null;
    WorkbenchTemplateMappingItem subspecies = null;
    WorkbenchTemplateMappingItem variety1 = null;

    Comparator<WorkbenchTemplateMappingItem> wbmtiComp = new Comparator<WorkbenchTemplateMappingItem>() {
        public int compare(WorkbenchTemplateMappingItem wbmti1, WorkbenchTemplateMappingItem wbmti2) {
            return wbmti1.getTitle().compareTo(wbmti2.getTitle());
        }

    };

    Vector<WorkbenchTemplateMappingItem> list = new Vector<WorkbenchTemplateMappingItem>();
    for (WorkbenchTemplateMappingItem item : workbench.getWorkbenchTemplate()
            .getWorkbenchTemplateMappingItems()) {
        //item.setUseCaptionForText(true);
        list.add(item);
        if (item.getFieldName().equals("genus1")) {
            genus = item;

        } else if (item.getFieldName().equals("species1")) {
            species = item;

        } else if (item.getFieldName().equals("subspecies1")) {
            subspecies = item;

        } else if (item.getFieldName().equals("variety1")) {
            variety1 = item;
        }
    }

    Collections.sort(list, wbmtiComp);

    if (genus != null && species != null) {
        WorkbenchTemplateMappingItem genusSpecies = new WorkbenchTemplateMappingItem();
        genusSpecies.setCaption(genus.getTitle() + " " + species.getTitle()
                + (subspecies != null ? (" " + subspecies.getTitle()) : "")
                + (variety1 != null ? (" " + variety1.getTitle()) : ""));
        genusSpecies.setViewOrder((short) -1);
        genusSpecies.setWorkbenchTemplateMappingItemId((int) genus.getViewOrder());
        genusSpecies.setVersion(species.getViewOrder());

        if (subspecies != null) {
            genusSpecies.setOrigImportColumnIndex(subspecies.getViewOrder());
        }
        if (variety1 != null) {
            genusSpecies.setSrcTableId((int) variety1.getViewOrder());
        }
        list.insertElementAt(genusSpecies, 0);
    }

    WorkbenchTemplateMappingItem rowItem = new WorkbenchTemplateMappingItem();
    rowItem.setCaption("Row Number"); // I18N
    rowItem.setViewOrder((short) -2);
    list.insertElementAt(rowItem, 0);

    final ToggleButtonChooserPanel<WorkbenchTemplateMappingItem> titlePanel = new ToggleButtonChooserPanel<WorkbenchTemplateMappingItem>(
            list, "GE_CHOOSE_FIELD_FOR_TITLE_EXPORT", ToggleButtonChooserPanel.Type.RadioButton);
    titlePanel.setUseScrollPane(true);
    titlePanel.createUI();

    Vector<WorkbenchTemplateMappingItem> includeList = new Vector<WorkbenchTemplateMappingItem>();
    for (WorkbenchTemplateMappingItem item : workbench.getWorkbenchTemplate()
            .getWorkbenchTemplateMappingItems()) {
        includeList.add(item);
    }

    Collections.sort(includeList, wbmtiComp);

    final ToggleButtonChooserPanel<WorkbenchTemplateMappingItem> inclPanel = new ToggleButtonChooserPanel<WorkbenchTemplateMappingItem>(
            includeList, "GE_CHOOSE_FIELDS_EXPORT", ToggleButtonChooserPanel.Type.Checkbox);
    inclPanel.setUseScrollPane(true);
    inclPanel.setAddSelectAll(true);
    inclPanel.createUI();

    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g,10px,f:p:g", "f:p:g,6px"));
    CellConstraints cc = new CellConstraints();
    pb.add(titlePanel, cc.xy(1, 1));
    pb.add(inclPanel, cc.xy(3, 1));

    CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(),
            getResourceString("GE_CHOOSE_FIELD_FOR_EXPORT_TITLE"), true, pb.getPanel()) {

        /* (non-Javadoc)
         * @see edu.ku.brc.ui.CustomDialog#okButtonPressed()
         */
        @Override
        protected void okButtonPressed() {
            if (titlePanel.getSelectedObject() != null && inclPanel.getSelectedObjects() != null
                    && inclPanel.getSelectedObjects().size() > 0) {
                super.okButtonPressed();
            } else {
                UIRegistry.showLocalizedError("WB_GOOGLE_SETTINGS_INCOMPLETE");
            }
        }

    };
    dlg.setVisible(true);
    //        for (WorkbenchTemplateMappingItem item : workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems())
    //        {
    //            item.setUseCaptionForText(false);
    //        }

    if (!dlg.isCancelled()) {
        return new Pair<WorkbenchTemplateMappingItem, List<WorkbenchTemplateMappingItem>>(
                titlePanel.getSelectedObject(), inclPanel.getSelectedObjects());
    }
    return null;
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java

/**
 * @param rootTable/*from   w  ww.  ja va2  s  . c  o  m*/
 * @param distinct
 * @param qfps
 * @param tblTree
 * @param keysToRetrieve
 * @return HQLSpecs for the current fields and settings.
 */
public static HQLSpecs buildHQL(final TableQRI rootTable, final boolean distinct,
        final Vector<QueryFieldPanel> qfps, final TableTree tblTree, final RecordSetIFace keysToRetrieve,
        final boolean searchSynonymy, final boolean isSchemaExport, final Timestamp lastExportTime,
        final boolean disjunct) throws ParseException {
    if (qfps.size() == 0)
        return null;

    if (keysToRetrieve != null && keysToRetrieve.getNumItems() == 0)
        return null;

    StringBuilder fieldsStr = new StringBuilder();
    Vector<BaseQRI> list = new Vector<BaseQRI>();
    StringBuilder criteriaStr = new StringBuilder();
    StringBuilder orderStr = new StringBuilder();
    LinkedList<SortElement> sortElements = new LinkedList<SortElement>();
    boolean postSortPresent = false;
    boolean debug = false;
    ProcessNode root = new ProcessNode();
    int fldPosition = distinct ? 0 : 1;

    for (QueryFieldPanel qfi : qfps) {
        if (qfi.getFieldQRI() == null) {
            continue;
        }

        qfi.updateQueryField();

        if (qfi.isForDisplay()) {
            fldPosition++;
        }

        if (debug) {
            log.debug("\nNode: " + qfi.getFieldName());
        }

        SortElement orderSpec = qfi.getOrderSpec(distinct ? fldPosition - 1 : fldPosition - 2);
        if (orderSpec != null) {
            boolean isPostSortSpec = qfi.getFieldQRI() instanceof TreeLevelQRI
                    || qfi.getFieldQRI() instanceof RelQRI;
            //dis regard post sorts that may have been saved before
            //fix for bug #9407
            if (!isSchemaExport) {
                postSortPresent |= isPostSortSpec;
            }
            if (!isPostSortSpec || !isSchemaExport) {
                sortElements.add(orderSpec);
            }
        }

        // Create a Stack (list) of parent from
        // the current node up to the top
        // basically we are creating a path of nodes
        // to determine if we need to create a new node in the tree
        list.clear();
        FieldQRI pqri = qfi.getFieldQRI();
        TableTree parent = pqri.getTableTree();
        if (qfi.isForDisplay() || qfi.hasCriteria() || orderSpec != null || pqri instanceof RelQRI) {
            boolean addToList = true;
            if (pqri instanceof RelQRI) {
                RelQRI relQRI = (RelQRI) pqri;
                RelationshipType relType = relQRI.getRelationshipInfo().getType();

                // XXX Formatter.getSingleField() checks for ZeroOrOne and
                // OneToOne rels.

                if (!relType.equals(RelationshipType.ManyToOne)
                        && !relType.equals(RelationshipType.ManyToMany)/*
                                                                       * treat
                                                                       * manytomany
                                                                       * as
                                                                       * onetomany
                                                                       */) // Maybe
                                                                                                                            // need
                                                                                                                            // to
                                                                                                                            // consider
                                                                                                                            // some
                                                                                                                            // types
                                                                                                                            // of
                                                                                                                            // OneToOne
                                                                                                                            // also?????????
                {
                    parent = parent.getParent();
                    if (isSchemaExport && lastExportTime != null) {
                        addToList = true;
                    } else {
                        // parent will initially point to the related table
                        // and don't need to add related table unless it has
                        // children displayed/queried,
                        addToList = false;
                    }
                } else {
                    DataObjDataFieldFormatIFace formatter = relQRI.getDataObjFormatter(qfi.getFormatName());
                    if (formatter != null) {
                        boolean isSingleSimpleFormat = formatter.getSingleField() != null
                                && formatter.getFields()[0].getSep() == null;
                        addToList = isSingleSimpleFormat || (isSchemaExport && lastExportTime != null);
                    } else {
                        addToList = false;
                    }
                }
            }
            if (addToList) {
                list.insertElementAt(pqri, 0);
            }
            while (parent != tblTree) {
                list.insertElementAt(parent.getTableQRI(), 0);
                parent = parent.getParent();
            }

            if (debug) {
                log.debug("Path From Top Down:");
                for (BaseQRI qri : list) {
                    log.debug("  " + qri.getTitle());
                }
            }

            // Now walk the stack top (the top most parent)
            // down and if the path form the top down doesn't
            // exist then add a new node
            ProcessNode parentNode = root;
            int q = 0;
            for (BaseQRI qri : list) {
                if (debug) {
                    log.debug("ProcessNode[" + qri.getTitle() + "]");
                }
                q++;
                if (!parentNode.contains(qri) && (qri instanceof TableQRI || q == list.size())) {
                    ProcessNode newNode = new ProcessNode(qri);
                    parentNode.getKids().add(newNode);
                    if (debug) {
                        log.debug("Adding new node[" + newNode.getQri().getTitle() + "] to Node["
                                + (parentNode.getQri() == null ? "root" : parentNode.getQri().getTitle())
                                + "]");
                    }
                    parentNode = newNode;
                } else {
                    for (ProcessNode kidNode : parentNode.getKids()) {
                        if (kidNode.getQri().equals(qri)) {
                            parentNode = kidNode;
                            break;
                        }
                    }
                }
            }

            if (debug) {
                log.debug("Current Tree:");
                printTree(root, 0);
            }
        }
    }

    if (debug) {
        printTree(root, 0);
    }

    StringBuilder fromStr = new StringBuilder();
    TableAbbreviator tableAbbreviator = new TableAbbreviator();
    List<Pair<DBTableInfo, String>> fromTbls = new LinkedList<Pair<DBTableInfo, String>>();
    boolean hqlHasSynJoins = processTree(root, fromStr, fromTbls, 0, tableAbbreviator, tblTree, qfps,
            searchSynonymy, isSchemaExport, lastExportTime);

    StringBuilder sqlStr = new StringBuilder();
    sqlStr.append("select ");
    //if (distinct /*|| hqlHasSynJoins*/)
    {
        sqlStr.append("distinct ");
    }
    if (!distinct) {
        fieldsStr.append(tableAbbreviator.getAbbreviation(rootTable.getTableTree()));
        fieldsStr.append(".");
        fieldsStr.append(rootTable.getTableInfo().getIdFieldName());
    }

    List<Pair<String, Object>> paramsToSet = new LinkedList<Pair<String, Object>>();
    boolean visibleFldExists = false;
    for (QueryFieldPanel qfi : qfps) {
        if (qfi.getFieldQRI() == null) {
            continue;
        }

        if (qfi.isForDisplay()) {
            visibleFldExists = true;
            String fldSpec = qfi.getFieldQRI().getSQLFldSpec(tableAbbreviator, false, isSchemaExport,
                    qfi.getFormatName());
            if (StringUtils.isNotEmpty(fldSpec)) {
                if (fieldsStr.length() > 0) {
                    fieldsStr.append(", ");
                }
                fieldsStr.append(fldSpec);
            }
        }
        if (keysToRetrieve == null || qfi.isEnforced()) {
            String criteria = qfi.getCriteriaFormula(tableAbbreviator, paramsToSet);
            boolean isDisplayOnly = StringUtils.isEmpty(criteria);
            if (!isDisplayOnly) {
                if (criteria.equals("2+2=2") && qfi.isNegated()) {
                    criteria = "";
                }
                if (criteria.length() > 0 && hqlHasSynJoins && isSynSearchable(qfi.getFieldQRI())
                        && !qfi.isEmptyCriterion()) {
                    criteria = adjustForSynSearch(
                            tableAbbreviator.getAbbreviation(qfi.getFieldQRI().getTable().getTableTree()),
                            criteria, qfi.isNegated());
                }
                if (!isDisplayOnly && criteriaStr.length() > 0 && criteria.length() > 0) {
                    criteriaStr.append(disjunct ? " OR " : " AND ");
                }
                criteriaStr.append(criteria);
            }
        }
    }
    if (!visibleFldExists) {
        throw new ParseException(getResourceString("QueryBldrPane.NoVisibleColumns"), -1);
    }

    sqlStr.append(fieldsStr);

    sqlStr.append(" from ");
    sqlStr.append(fromStr);

    if (keysToRetrieve != null) {
        if (!StringUtils.isEmpty(criteriaStr.toString())) {
            criteriaStr.append(" and ");
        }
        criteriaStr.append("(");
        criteriaStr.append(tableAbbreviator.getAbbreviation(rootTable.getTableTree()) + "."
                + rootTable.getTableInfo().getIdFieldName() + " in(");
        boolean comma = false;
        int maxInClauseLen = 2500;
        int inClauseLen = 0;
        for (RecordSetItemIFace item : keysToRetrieve.getOrderedItems()) {
            if (inClauseLen == maxInClauseLen) {
                criteriaStr.append(") or ");
                criteriaStr.append(tableAbbreviator.getAbbreviation(rootTable.getTableTree()) + "."
                        + rootTable.getTableInfo().getIdFieldName() + " in(");
                inClauseLen = 0;
            } else if (comma) {
                criteriaStr.append(",");
            } else {
                comma = true;
            }
            criteriaStr.append(item.getRecordId());
            inClauseLen++;
        }
        criteriaStr.append("))");
    } else {
        //Assuming that this not necessary when keysToRetrieve is non-null because
        //the keys will already been filtered properly. (???)

        // Add extra where's for system fields for root table only, see notes below at end of for block
        boolean isRootTbl = true;
        for (Pair<DBTableInfo, String> fromTbl : fromTbls) {
            String specialColumnWhere = null;
            if (fromTbl.getFirst().getTableId() == Attachment.getClassTableId()) {
                String prefix = fromTbl.getSecond() + ".";
                specialColumnWhere = "((" + prefix + "scopeType = 0 and " + prefix + "scopeID = "
                        + AppContextMgr.getInstance()
                                .getClassObject(edu.ku.brc.specify.datamodel.Collection.class).getCollectionId()
                        + ") or" + "(" + prefix + "scopeType = 1 and " + prefix + "scopeID = "
                        + AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId()
                        + ") or" + "(" + prefix + "scopeType = 2 and " + prefix + "scopeID = "
                        + AppContextMgr.getInstance().getClassObject(Division.class).getDivisionId() + ") or"
                        + "(" + prefix + "scopeType = 3 and " + prefix + "scopeID = "
                        + AppContextMgr.getInstance().getClassObject(Institution.class).getInstitutionId()
                        + "))";
            } else {
                specialColumnWhere = QueryAdjusterForDomain.getInstance().getSpecialColumns(fromTbl.getFirst(),
                        true, !isRootTbl && true/* XXX should only use left join when necessary */,
                        fromTbl.getSecond());
            }
            isRootTbl = false;
            if (StringUtils.isNotEmpty(specialColumnWhere)) {
                if (criteriaStr.length() > 0) {
                    criteriaStr.append(" AND ");
                }
                criteriaStr.append(specialColumnWhere);
            }
            //Actually, assuming data is valid, it should only be necessary to add the Adjustments for the root table?
            //XXX if this works, fix this loop. Also, join parameter code in getSpecialColumns will probably be irrelevant.
            break;
        }
        //...done adding system whereses

        //get only records modified/added since last export of the schema...
        if (isSchemaExport && lastExportTime != null) {
            if (criteriaStr.length() > 0) {
                criteriaStr.append(" AND (");
            }
            String timestampParam = "spparam" + paramsToSet.size();
            paramsToSet.add(new Pair<String, Object>(timestampParam, lastExportTime));
            criteriaStr.append(getTimestampWhere(fromTbls, timestampParam, lastExportTime));
            criteriaStr.append(") ");
        }
    }

    if (criteriaStr.length() > 0) {
        sqlStr.append(" where ");
        sqlStr.append(criteriaStr);
    }

    if (sortElements.size() > 0 && !postSortPresent) {
        for (SortElement se : sortElements) {
            if (!StringUtils.isEmpty(orderStr.toString())) {
                orderStr.append(", ");
            }
            orderStr.append(distinct ? se.getColumn() + 1 : se.getColumn() + 2);
            if (se.getDirection() == SortElement.DESCENDING) {
                orderStr.append(" DESC");
            }
        }
        sortElements.clear();
    }

    if (orderStr.length() > 0) {
        sqlStr.append(" order by ");
        sqlStr.append(orderStr);
    }

    if (debug) {
        log.debug(sqlStr.toString());
        log.debug("sort:");
        for (SortElement s : sortElements) {
            log.debug("  " + s.getColumn() + " - " + s.getDirection());
        }
    }

    String result = sqlStr.toString();
    if (!checkHQL(result))
        return null;

    log.info(result);
    return new HQLSpecs(result, paramsToSet, sortElements, hqlHasSynJoins);
}