Example usage for java.lang StringBuffer delete

List of usage examples for java.lang StringBuffer delete

Introduction

In this page you can find the example usage for java.lang StringBuffer delete.

Prototype

@Override
public synchronized StringBuffer delete(int start, int end) 

Source Link

Usage

From source file:CssCompressor.java

public void compress(Writer out, int linebreakpos) throws IOException {

    Pattern p;/* ww w .  j  av  a2 s. c  o m*/
    Matcher m;
    String css;
    StringBuffer sb;
    int startIndex, endIndex;

    // Remove all comment blocks...
    startIndex = 0;
    boolean iemac = false;
    boolean preserve = false;
    sb = new StringBuffer(srcsb.toString());
    while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
        preserve = sb.length() > startIndex + 2 && sb.charAt(startIndex + 2) == '!';
        endIndex = sb.indexOf("*/", startIndex + 2);
        if (endIndex < 0) {
            if (!preserve) {
                sb.delete(startIndex, sb.length());
            }
        } else if (endIndex >= startIndex + 2) {
            if (sb.charAt(endIndex - 1) == '\\') {
                // Looks like a comment to hide rules from IE Mac.
                // Leave this comment, and the following one, alone...
                startIndex = endIndex + 2;
                iemac = true;
            } else if (iemac) {
                startIndex = endIndex + 2;
                iemac = false;
            } else if (!preserve) {
                sb.delete(startIndex, endIndex + 2);
            } else {
                startIndex = endIndex + 2;
            }
        }
    }

    css = sb.toString();

    // Normalize all whitespace strings to single spaces. Easier to work
    // with that way.
    css = css.replaceAll("\\s+", " ");

    // Make a pseudo class for the Box Model Hack
    css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___");

    // ---------where zk modify it
    sb = new StringBuffer();
    p = Pattern.compile("\\$\\{([^\\}]+)\\}");
    Matcher m1 = p.matcher(css);
    while (m1.find()) {
        String s1 = m1.group();
        s1 = s1.replaceAll("\\$\\{", "__EL__");
        s1 = s1.replaceAll(":", "__ELSP__");
        s1 = s1.replaceAll("\\}", "__ELEND__");

        m1.appendReplacement(sb, s1);
    }
    m1.appendTail(sb);
    css = sb.toString();

    // ---------where zk modify it----end

    // Remove the spaces before the things that should not have spaces
    // before them.
    // But, be careful not to turn "p :link {...}" into "p:link{...}"
    // Swap out any pseudo-class colons with the token, and then swap back.
    sb = new StringBuffer();
    p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
    m = p.matcher(css);
    while (m.find()) {
        String s = m.group();
        s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
        m.appendReplacement(sb, s);
    }
    m.appendTail(sb);
    css = sb.toString();
    css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
    css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");

    // Remove the spaces after the things that should not have spaces after
    // them.
    css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");

    // Add the semicolon where it's missing.
    css = css.replaceAll("([^;\\}])}", "$1;}");

    // Replace 0(px,em,%) with 0.
    css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");

    // Replace 0 0 0 0; with 0.
    css = css.replaceAll(":0 0 0 0;", ":0;");
    css = css.replaceAll(":0 0 0;", ":0;");
    css = css.replaceAll(":0 0;", ":0;");
    // Replace background-position:0; with background-position:0 0;
    css = css.replaceAll("background-position:0;", "background-position:0 0;");

    // Replace 0.6 to .6, but only when preceded by : or a white-space
    css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");

    // Shorten colors from rgb(51,102,153) to #336699
    // This makes it more likely that it'll get further compressed in the
    // next step.
    p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
    m = p.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        String[] rgbcolors = m.group(1).split(",");
        StringBuffer hexcolor = new StringBuffer("#");
        for (int i = 0; i < rgbcolors.length; i++) {
            int val = Integer.parseInt(rgbcolors[i]);
            if (val < 16) {
                hexcolor.append("0");
            }
            hexcolor.append(Integer.toHexString(val));
        }
        m.appendReplacement(sb, hexcolor.toString());
    }
    m.appendTail(sb);
    css = sb.toString();

    // Shorten colors from #AABBCC to #ABC. Note that we want to make sure
    // the color is not preceded by either ", " or =. Indeed, the property
    // filter: chroma(color="#FFFFFF");
    // would become
    // filter: chroma(color="#FFF");
    // which makes the filter break in IE.
    p = Pattern.compile(
            "([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
    m = p.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        // Test for AABBCC pattern
        if (m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6))
                && m.group(7).equalsIgnoreCase(m.group(8))) {
            m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7));
        } else {
            m.appendReplacement(sb, m.group());
        }
    }
    m.appendTail(sb);
    css = sb.toString();

    // Remove empty rules.
    css = css.replaceAll("[^\\}]+\\{;\\}", "");

    if (linebreakpos >= 0) {
        // Some source control tools don't like it when files containing
        // lines longer
        // than, say 8000 characters, are checked in. The linebreak option
        // is used in
        // that case to split long lines after a specific column.
        int i = 0;
        int linestartpos = 0;
        sb = new StringBuffer(css);
        while (i < sb.length()) {
            char c = sb.charAt(i++);
            if (c == '}' && i - linestartpos > linebreakpos) {
                sb.insert(i, '\n');
                linestartpos = i;
            }
        }

        css = sb.toString();
    }

    // Replace the pseudo class for the Box Model Hack
    css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\"");

    // Replace multiple semi-colons in a row by a single one
    // See SF bug #1980989
    css = css.replaceAll(";;+", ";");

    // ---------where zk modify it
    css = css.replaceAll("__EL__", "\\$\\{");
    css = css.replaceAll("__ELSP__", ":");
    css = css.replaceAll("__ELEND__", "\\}");

    // ---------where zk modify it----end

    // Trim the final string (for any leading or trailing white spaces)
    css = css.trim();

    // Write the output...
    out.write(css);
}

From source file:org.exoplatform.ecm.webui.utils.Utils.java

/**
 *
 * @param name//w  w w.j  a v  a 2s.  c  om
 * @param value_
 * @param arguments
 * @return
 */
private static String createCKEditorField(String name, String value_, HashMap<String, String> arguments) {
    String toolbar = arguments.get(TOOLBAR);
    String passedCSS = arguments.get(CSS);

    if (toolbar == null)
        toolbar = "BasicWCM";
    StringBuffer contentsCss = new StringBuffer();
    contentsCss.append("[");
    SkinService skinService = WCMCoreUtils.getService(SkinService.class);
    UserPortalConfig upc = Util.getPortalRequestContext().getUserPortalConfig();
    String skin = upc.getPortalConfig().getSkin();
    String portal = Util.getUIPortal().getName();
    Collection<SkinConfig> portalSkins = skinService.getPortalSkins(skin);
    SkinConfig customSkin = skinService.getSkin(portal, upc.getPortalConfig().getSkin());
    if (customSkin != null)
        portalSkins.add(customSkin);
    for (SkinConfig portalSkin : portalSkins) {
        contentsCss.append("'")
                .append(portalSkin.createURL(Util.getPortalRequestContext().getControllerContext()))
                .append("',");
    }
    contentsCss.delete(contentsCss.length() - 1, contentsCss.length());
    contentsCss.append("]");

    StringBuffer buffer = new StringBuffer();
    buffer.append("<div style=\"display:none\">" + "<textarea id='cssContent" + name + "' name='cssContent"
            + name + "'>" + passedCSS + "</textarea></div>\n");

    if (value_ != null) {
        buffer.append("<textarea id='" + name + "' name='" + name + "'>" + value_ + "</textarea>\n");
    } else {
        buffer.append("<textarea id='" + name + "' name='" + name + "'></textarea>\n");
    }
    buffer.append("<script type='text/javascript'>\n");
    buffer.append("  //<![CDATA[ \n");
    buffer.append("    require(['/eXoWCMResources/ckeditor/ckeditor.js'], function() {");
    buffer.append("    var instances = CKEDITOR.instances['" + name
            + "']; if (instances) instances.destroy(true);\n");
    buffer.append("    CKEDITOR.replace('" + name + "', {toolbar:'" + toolbar
            + "', width:'98%', height: 200, contentsCss:" + contentsCss + ", ignoreEmptyParagraph:true});\n");
    buffer.append("    CKEDITOR.instances['" + name + "'].on(\"instanceReady\", function(){  ");
    buffer.append("       eXo.ecm.CKEditor.insertCSS('" + name + "', 'cssContent" + name + "');\n");
    buffer.append("       });");
    buffer.append("       });");
    buffer.append("  //]]> \n");
    buffer.append("</script>\n");
    return buffer.toString();
}

From source file:com.hexidec.ekit.action.ListAutomationAction.java

public void actionPerformed(ActionEvent ae) {
    try {/*from   w  ww.  j a  v a 2s  . c  om*/
        JEditorPane jepEditor = (JEditorPane) (parentEkit.getTextPane());
        String selTextBase = jepEditor.getSelectedText();
        int textLength = -1;
        if (selTextBase != null) {
            textLength = selTextBase.length();
        }
        if (selTextBase == null || textLength < 1) {
            int pos = parentEkit.getCaretPosition();
            parentEkit.setCaretPosition(pos);
            if (ae.getActionCommand() != "newListPoint") {
                if (htmlUtilities.checkParentsTag(HTML.Tag.OL) || htmlUtilities.checkParentsTag(HTML.Tag.UL)) {
                    revertList(htmlUtilities.getListItemContainer());
                    return;
                }
            }
            String sListType = (baseTag == HTML.Tag.OL ? "ol" : "ul");
            StringBuffer sbNew = new StringBuffer();
            if (htmlUtilities.checkParentsTag(baseTag)) {
                sbNew.append("<li></li>");
                insertHTML(parentEkit.getTextPane(), parentEkit.getExtendedHtmlDoc(),
                        parentEkit.getTextPane().getCaretPosition(), sbNew.toString(), 0, 0, HTML.Tag.LI);
            } else {
                boolean isLast = false;
                int caretPos = parentEkit.getCaretPosition();
                if (caretPos == parentEkit.getExtendedHtmlDoc().getLength()) {
                    isLast = true;
                }
                sbNew.append("<" + sListType + "><li></li></" + sListType + ">"
                        + (isLast ? "<p style=\"margin-top: 0\">&nbsp;</p>" : ""));
                insertHTML(parentEkit.getTextPane(), parentEkit.getExtendedHtmlDoc(),
                        parentEkit.getTextPane().getCaretPosition(), sbNew.toString(), 0, 0,
                        (sListType.equals("ol") ? HTML.Tag.OL : HTML.Tag.UL));
                if (true) {
                    parentEkit.setCaretPosition(caretPos + 1);
                }
            }
            parentEkit.refreshOnUpdate();
        } else {
            if (htmlUtilities.checkParentsTag(HTML.Tag.OL) || htmlUtilities.checkParentsTag(HTML.Tag.UL)) {
                revertList(htmlUtilities.getListItemContainer());
                return;
            } else {
                String sListType = (baseTag == HTML.Tag.OL ? "ol" : "ul");
                HTMLDocument htmlDoc = (HTMLDocument) (jepEditor.getDocument());
                int iStart = jepEditor.getSelectionStart();
                int iEnd = jepEditor.getSelectionEnd();
                String selText = htmlDoc.getText(iStart, iEnd - iStart);
                /*
                for(int ch = 0; ch < selText.length(); ch++)
                {
                   Element elem = htmlDoc.getCharacterElement(iStart + ch);
                   log.debug("elem " + ch + ": " + elem.getName());
                   log.debug("char " + ch + ": " + selText.charAt(ch) + " [" + Character.getNumericValue(selText.charAt(ch)) + "]");
                   if(Character.getNumericValue(selText.charAt(ch)) < 0)
                   {
                      log.debug("  is space?    " + ((selText.charAt(ch) == '\u0020') ? "YES" : "---"));
                      log.debug("  is return?   " + ((selText.charAt(ch) == '\r') ? "YES" : "---"));
                      log.debug("  is newline?  " + ((selText.charAt(ch) == '\n') ? "YES" : "---"));
                      log.debug("  is nextline? " + ((selText.charAt(ch) == '\u0085') ? "YES" : "---"));
                      log.debug("  is linesep?  " + ((selText.charAt(ch) == '\u2028') ? "YES" : "---"));
                      log.debug("  is parasep?  " + ((selText.charAt(ch) == '\u2029') ? "YES" : "---"));
                      log.debug("  is verttab?  " + ((selText.charAt(ch) == '\u000B') ? "YES" : "---"));
                      log.debug("  is formfeed? " + ((selText.charAt(ch) == '\u000C') ? "YES" : "---"));
                   }
                }
                */
                StringBuffer sbNew = new StringBuffer();
                sbNew.append("<" + sListType + ">");
                // tokenize on known linebreaks if present, otherwise manually parse on <br> break tags
                if ((selText.indexOf("\r") > -1) || (selText.indexOf("\n") > -1)) {
                    String sToken = ((selText.indexOf("\r") > -1) ? "\r" : "\n");
                    StringTokenizer stTokenizer = new StringTokenizer(selText, sToken);
                    while (stTokenizer.hasMoreTokens()) {
                        sbNew.append("<li>");
                        sbNew.append(stTokenizer.nextToken());
                        sbNew.append("</li>");
                    }
                } else {
                    StringBuffer sbItem = new StringBuffer();
                    for (int ch = 0; ch < selText.length(); ch++) {
                        String elem = (htmlDoc.getCharacterElement(iStart + ch) != null
                                ? htmlDoc.getCharacterElement(iStart + ch).getName().toLowerCase()
                                : "[null]");
                        if (elem.equals("br") && sbItem.length() > 0) {
                            sbNew.append("<li>");
                            sbNew.append(sbItem.toString());
                            sbNew.append("</li>");
                            sbItem.delete(0, sbItem.length());
                        } else {
                            sbItem.append(selText.charAt(ch));
                        }
                    }
                }
                sbNew.append("</" + sListType + ">");
                htmlDoc.remove(iStart, iEnd - iStart);
                insertHTML(jepEditor, htmlDoc, iStart, sbNew.toString(), 1, 1, null);
            }
        }
    } catch (BadLocationException ble) {
    }
}

From source file:org.zywx.wbpalmstar.plugin.uexcontacts.PFConcactMan.java

public static /*JSONObject*/JSONArray search(Context context, SearchOptionVO searchOptionVO) {
    ContentResolver cr = context.getContentResolver();
    String inName = searchOptionVO.getSearchName();
    String searchContactId = searchOptionVO.getContactId();
    boolean isSearchContactWithId = false;
    /* 1.6 *//*from   www .  j a  v  a  2 s .c  o  m*/
    JSONArray jsonArray = new JSONArray();
    int sdkVersion = Build.VERSION.SDK_INT;
    if (sdkVersion < 8) {
        Cursor cur = cr.query(android.provider.Contacts.People.CONTENT_URI, null, null, null, null);
        StringBuffer sb = new StringBuffer();
        try {
            while (cur.moveToNext()) {
                JSONObject jsonObject = new JSONObject();
                sb.append(cur.getString(cur.getColumnIndex(android.provider.Contacts.People.DISPLAY_NAME)));
                String id = cur.getString(cur.getColumnIndex(android.provider.Contacts.People._ID));
                String contactName = sb.toString();// ??

                if (contactName != null && contactName.indexOf(" ") != -1) {// 
                    sb.delete(0, sb.length());
                    contactName = contactName.replaceAll(" ", "");
                    sb.append(contactName);
                }
                isSearchContactWithId = searchContactId.equals(id);
                if (isSearchContactWithId
                        || ((sb.length() > 0 && sb.toString().indexOf(inName) > -1) || inName.length() == 0)) {
                    if (isSearchContactWithId) {
                        jsonArray = new JSONArray();
                    }
                    // ??
                    jsonObject.put(EUExCallback.F_JK_NAME, sb.toString());
                    sb.delete(0, sb.length());
                    jsonObject.put(EUExContact.JK_KEY_CONTACT_ID, id);
                    // ?
                    Cursor pCur = cr.query(android.provider.Contacts.Phones.CONTENT_URI, null,
                            android.provider.Contacts.Phones.PERSON_ID + " = ?", new String[] { id }, null);
                    if (pCur.moveToNext())
                        sb.append(pCur.getString(pCur.getColumnIndex(android.provider.Contacts.Phones.NUMBER)));
                    pCur.close();
                    jsonObject.put(EUExCallback.F_JK_NUM, sb.toString());
                    sb.delete(0, sb.length());
                    // 
                    Cursor emailCur = cr.query(android.provider.Contacts.ContactMethods.CONTENT_EMAIL_URI, null,
                            android.provider.Contacts.ContactMethods.PERSON_ID + " = ?", new String[] { id },
                            null);
                    if (emailCur.moveToNext())
                        sb.append(emailCur.getString(
                                emailCur.getColumnIndex(android.provider.Contacts.ContactMethodsColumns.DATA)));
                    emailCur.close();
                    jsonObject.put(EUExCallback.F_JK_EMAIL, sb.toString());
                    sb.delete(0, sb.length());

                    sb.delete(0, sb.length());
                    getValueWithName(context, id, jsonObject, searchOptionVO);
                    ToastShow(context, finder.getString(context, "plugin_contact_find_succeed"));
                }
                sb.delete(0, sb.length());
                jsonArray.put(jsonObject);
                if (isSearchContactWithId) {
                    break;
                }
            }
            sb.delete(0, sb.length());
        } catch (Exception e) {
            ToastShow(context, finder.getString(context, "plugin_contact_find_fail"));
            return null;
        } finally {
            if (cur != null)
                cur.close();
        }
    } else {
        String selection = null;
        String[] selectionArgs = null;
        String orderBy = null;
        if (!TextUtils.isEmpty(searchContactId)) {
            selection = android.provider.ContactsContract.Contacts._ID + " = ? ";
            selectionArgs = new String[] { searchContactId };
            isSearchContactWithId = true;
        } else if (inName != null) {
            selection = ContactsContract.Contacts.DISPLAY_NAME + " like ? ";
            selectionArgs = new String[] { "%" + inName + "%" };
        }
        if (searchOptionVO.getResultNum() > 0) {
            //orderBy = android.provider.ContactsContract.Contacts._ID + " asc limit " + searchOptionVO.getResultNum();
        }
        Cursor cursor = cr.query(android.provider.ContactsContract.Contacts.CONTENT_URI, CONTACTOR_NAME_ION,
                selection, selectionArgs, orderBy);
        try {
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                do {
                    String name = cursor.getString(
                            cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));
                    String contactId = cursor
                            .getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));

                    String contactName = name;// ??
                    if (contactName != null && contactName.indexOf(" ") != -1) {// 
                        contactName = contactName.replaceAll(" ", "");
                        name = contactName;
                    }
                    if (isSearchContactWithId || (name != null
                            && (name.indexOf(inName) > -1/*equals(inName)*/ || inName.length() == 0))) {// ????
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(EUExCallback.F_JK_NAME, name);

                        jsonObject.put(EUExContact.JK_KEY_CONTACT_ID, contactId);
                        // ??
                        if (searchOptionVO.isSearchNum()) {
                            Cursor phones = ((Activity) context).getContentResolver().query(
                                    android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                    CONTACTOR_NUMBER_ION,
                                    android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                                            + contactId,
                                    null, null);
                            if (phones != null && phones.getCount() > 0) {
                                phones.moveToFirst();
                                String phoneNumber = phones.getString(phones.getColumnIndex(
                                        android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
                                jsonObject.put(EUExCallback.F_JK_NUM, phoneNumber);
                                phones.close();
                            }
                        }
                        // ?
                        if (searchOptionVO.isSearchEmail()) {
                            Cursor emails = ((Activity) context).getContentResolver().query(
                                    android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                    CONTACTOR_EMAILS_ION,
                                    android.provider.ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = "
                                            + contactId,
                                    null, null);
                            if (emails != null && emails.getCount() > 0) {
                                emails.moveToFirst();
                                String emailAddress = emails.getString(emails.getColumnIndex(
                                        android.provider.ContactsContract.CommonDataKinds.Email.DATA));
                                jsonObject.put(EUExCallback.F_JK_EMAIL, emailAddress);
                                emails.close();
                            }
                        }
                        getValueWithName(context, contactId, jsonObject, searchOptionVO);
                        jsonArray.put(jsonObject);
                    }
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            ToastShow(context, finder.getString(context, "plugin_contact_find_fail"));
            return null;
        } finally {
            if (cursor != null)
                cursor.close();
        }
    }
    return /*jsonObject*/jsonArray;
}

From source file:edu.umd.cs.submitServer.servlets.ReportTestOutcomes.java

/**
 * Compares two testOutcomeCollections that were run against the same
 * testSetupPK and produces a String suitable for entry in a log4j log
 * summarizing the differences between the two collections. Used by the
 * background retesting mechanism. TODO It's ugly that this returns a String!
 * /*from  www.  ja  v a 2 s  . c  o  m*/
 * @param oldCollection
 *          The collection currently in the database.
 * @param newCollection
 *          The collection returned after a background re-test.
 * @param submissionPK
 *          The submissionPK of the submission being retested.
 * @param testSetupPK
 *          The testSetupPK of the testSetup used for the re-test.
 * @return null if the two testOutcomeCollections are the same; a String
 *         suitable for writing in a log if there are differences
 */
private static String compareCardinalOutcomes(TestOutcomeCollection oldCollection,
        TestOutcomeCollection newCollection, @Submission.PK Integer submissionPK, Integer testSetupPK,
        String testMachine) {
    for (TestOutcome newOutcome : newCollection) {
        // If any of the tests were marked "COULD_NOT_RUN" then don't record
        // anything
        // into the DB
        if (newOutcome.getOutcome().equals(TestOutcome.COULD_NOT_RUN)) {
            getFailedBackgroundRetestLog().warn(newOutcome.getOutcome() + " result for submissionPK "
                    + submissionPK + ", testSetupPK " + testSetupPK + " and test " + newOutcome.getTestType()
                    + newOutcome.getTestNumber() + " : " + newOutcome.getTestName());
            return null;
        }
    }
    // TODO Handle when one compiles and the next doesn't compile.
    // NOTE: We're ignoring a lot of other info here like md5sums, clover
    // info, etc.
    StringBuffer buf = new StringBuffer();
    for (TestOutcome oldOutcome : oldCollection.getIterableForCardinalTestTypes()) {
        TestOutcome newOutcome = newCollection.getTest(oldOutcome.getTestName());

        if (oldOutcome.getOutcome().equals(TestOutcome.COULD_NOT_RUN)) {
            getFailedBackgroundRetestLog().warn("Not currently able to compare could not runs");
            return "skip";
        }
        if (newOutcome == null) {
            // We're in trouble here
            throw new IllegalStateException("Can't find " + oldOutcome.getTestName()
                    + " in new testOutcomeCollection after background retest for " + " submissionPK "
                    + submissionPK + " and testSetupPK " + testSetupPK);
        }
        if (!oldOutcome.getOutcome().equals(newOutcome.getOutcome())) {
            buf.append("\t" + oldOutcome.getTestName() + ": outcome in database is " + oldOutcome.getOutcome()
                    + "; background retest produced " + newOutcome.getOutcome() + "\n");
        }
    }
    if (buf.length() > 0) {
        buf.insert(0, "submissionPK = " + submissionPK + ", testSetupPK = " + testSetupPK + " on " + testMachine
                + ":\n");
        // Strip off last newline
        buf.delete(buf.length() - 1, buf.length());
        return buf.toString();
    }
    return null;
}

From source file:org.ensembl.healthcheck.util.DBUtils.java

/**
 * Execute SQL and writes results to ReportManager.info().
 * /*from  ww  w .j a v  a2  s.  c  om*/
 * @param testCase
 *            testCase which created the sql statement
 * @param con
 *            connection to execute sql on.
 * @param sql
 *            sql statement to execute.
 */
public static void printRows(EnsTestCase testCase, Connection con, String sql) {

    ResultSet rs = null;
    try {
        rs = con.createStatement().executeQuery(sql);
        if (rs.next()) {
            int nCols = rs.getMetaData().getColumnCount();
            StringBuffer line = new StringBuffer();
            do {
                line.delete(0, line.length());
                for (int i = 1; i <= nCols; ++i) {
                    line.append(rs.getString(i));
                    if (i < nCols) {
                        line.append("\t");
                    }

                }
                ReportManager.info(testCase, con, line.toString());
            } while (rs.next());
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(rs);
    }
}

From source file:com.glaf.dts.web.springmvc.MxDtsTableController.java

@RequestMapping("/edit")
public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) {
    String jx_view = request.getParameter("jx_view");
    RequestUtils.setRequestParameterToAttribute(request);

    String tableName = request.getParameter("tableName");
    String tableName_enc = request.getParameter("tableName_enc");
    if (StringUtils.isNotEmpty(tableName_enc)) {
        tableName = RequestUtils.decodeString(tableName_enc);
    }//from  w ww.j  a  v  a2s.c  om

    if (StringUtils.isNotEmpty(tableName)) {
        TableDefinition table = tableDefinitionService.getTableDefinition(tableName);
        if (table != null && StringUtils.isNotEmpty(table.getQueryIds())) {
            QueryDefinitionQuery query = new QueryDefinitionQuery();
            List<String> queryIds = StringTools.split(table.getQueryIds());
            query.queryIds(queryIds);
            List<QueryDefinition> list = queryDefinitionService.list(query);
            StringBuffer sb01 = new StringBuffer();
            StringBuffer sb02 = new StringBuffer();
            for (QueryDefinition queryDefinition : list) {
                if (queryDefinition != null) {
                    sb01.append(queryDefinition.getId()).append(",");
                    sb02.append(queryDefinition.getTitle()).append("[").append(queryDefinition.getId())
                            .append("],");
                }
            }
            if (sb01.toString().endsWith(",")) {
                sb01.delete(sb01.length() - 1, sb01.length());
            }
            if (sb02.toString().endsWith(",")) {
                sb02.delete(sb02.length() - 1, sb02.length());
            }
            request.setAttribute("queryIds", sb01.toString());
            request.setAttribute("queryNames", sb02.toString());
        }

        if (table != null && StringUtils.isNotEmpty(table.getAggregationQueryIds())) {
            QueryDefinitionQuery query = new QueryDefinitionQuery();
            List<String> queryIds = StringTools.split(table.getAggregationQueryIds());
            query.queryIds(queryIds);
            List<QueryDefinition> list = queryDefinitionService.list(query);
            StringBuffer sb01 = new StringBuffer();
            StringBuffer sb02 = new StringBuffer();
            for (QueryDefinition queryDefinition : list) {
                if (queryDefinition != null) {
                    sb01.append(queryDefinition.getId()).append(",");
                    sb02.append(queryDefinition.getTitle()).append("[").append(queryDefinition.getId())
                            .append("],");
                }
            }
            if (sb01.toString().endsWith(",")) {
                sb01.delete(sb01.length() - 1, sb01.length());
            }
            if (sb02.toString().endsWith(",")) {
                sb02.delete(sb02.length() - 1, sb02.length());
            }
            request.setAttribute("aggregationQueryIds", sb01.toString());
            request.setAttribute("queryNames2", sb02.toString());
        }

        if (table != null) {
            request.setAttribute("table", table);
            request.setAttribute("nodeId", table.getNodeId());
        }
    }

    if (StringUtils.isNotEmpty(jx_view)) {
        return new ModelAndView(jx_view, modelMap);
    }

    String x_view = ViewProperties.getString("dts_table.edit");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view, modelMap);
    }
    return new ModelAndView("/bi/dts/table/edit", modelMap);
}

From source file:com.m2a.struts.M2ALoginAction.java

protected void catchException(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*from  w  w  w .j  a  v  a  2 s. com*/
    Exception exception = getException(request);
    exception.printStackTrace();
    ActionErrors errors = getErrors(request, true);
    //errors.add("org.apache.struts.action.GLOBAL_ERROR",new ActionError("error.general"));     20120528:1
    StringBuffer sb = new StringBuffer();
    if (exception instanceof BaseException) {
        BaseException e = (BaseException) exception;
        e.getMessage(sb);
        sb.delete(0, 74);
    } else {
        sb.append('\r');
        //sb.append("ERROR: ");         20120528:1
        //sb.append(exception.toString());
        String message = exception.getMessage();
        if (null != message) {
            //sb.append('\r');
            //sb.append(" DETAILS: ");
            sb.append(message);
            //sb.append('\r');
        } // if (null
    } // if (exception
    errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError("error.detail", sb.toString()));
}

From source file:com.qmetry.qaf.automation.step.client.text.BDDFileParser.java

@Override
protected Collection<Object[]> parseFile(String strFile) {
    ArrayList<Object[]> rows = new ArrayList<Object[]>();
    ArrayList<Object[]> background = new ArrayList<Object[]>();

    File textFile;//from  w w w.  java  2 s  .  co m
    int lineNo = 0;
    int lastScenarioIndex = -1;

    BufferedReader br = null;
    try {

        logger.info("loading BDD file: " + strFile);
        textFile = new File(strFile);
        br = new BufferedReader(new FileReader(textFile));
        String strLine = "";
        boolean bIsBackground = false;
        // file line by line
        // exclude blank lines and comments
        StringBuffer currLineBuffer = new StringBuffer();
        while ((strLine = br.readLine()) != null) {
            // record line number
            lineNo++;
            /**
             * ignore if line is empty or comment line
             */
            if (!("".equalsIgnoreCase(strLine.trim())
                    || COMMENT_CHARS.contains("" + strLine.trim().charAt(0)))) {
                currLineBuffer.append((strLine.trim()));

                if (strLine.endsWith(LINE_BREAK)) {
                    /*
                     * Statement not completed. Remove line break character
                     * and continue statement reading from next line
                     */
                    currLineBuffer.delete(currLineBuffer.length() - LINE_BREAK.length(),
                            currLineBuffer.length());

                } else {
                    // process single statement
                    Object[] cols = new Object[] { "", "", "", lineNo };
                    String currLine = currLineBuffer.toString();
                    if ((StringUtil.indexOfIgnoreCase(currLine, SCENARIO) == 0)
                            || (StringUtil.indexOfIgnoreCase(currLine, BACKGROUND) == 0)
                            || (StringUtil.indexOfIgnoreCase(currLine, STEP_DEF) == 0)
                            || (StringUtil.indexOfIgnoreCase(currLine, "META") == 0)) {

                        System.arraycopy(currLine.split(":", 2), 0, cols, 0, 2);

                        // append meta-data in last/scenario statement
                        if (StringUtil.indexOfIgnoreCase(((String) cols[0]).trim(), "META") == 0) {
                            //                        Object[] row = new Object[4];
                            //                        int prevIndex = rows.size() - 1;

                            Object[] prevRow = rows.get(lastScenarioIndex);

                            //System.arraycopy(prevRow, 0, row, 0, 2);
                            prevRow[2] = ((String) cols[1]).trim();
                            //row[3] = prevRow[3];
                            //rows.add(row);
                            currLineBuffer = new StringBuffer();
                            continue;
                        } else if (StringUtil.indexOfIgnoreCase(currLine, BACKGROUND) == 0) {
                            bIsBackground = true;
                            currLineBuffer = new StringBuffer();
                            continue;
                        } else {
                            lastScenarioIndex = rows.size();//step or scenario
                            bIsBackground = false;
                        }
                    } else {
                        // this is a statement
                        cols[0] = currLine;
                    }
                    if (bIsBackground) {
                        background.add(cols);
                    } else {
                        if (lastScenarioIndex >= 0)
                            rows.add(cols);
                        if (StringUtil.indexOfIgnoreCase((String) cols[0], SCENARIO) == 0) {
                            rows.addAll(background);
                        }
                    }

                    currLineBuffer = new StringBuffer();

                }
            }
        }
    } catch (Exception e) {
        String strMsg = "Exception while reading BDD file: " + strFile + "#" + lineNo;
        logger.error(strMsg + e);
        throw new AutomationError(strMsg, e);

    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return rows;
}

From source file:playground.andreas.bln.ana.events2counts.PtCountCountComparisonKMLWriter.java

/**
 * Creates a placemark//from  w w w.ja  v  a 2s.  c om
 *
 * @param stopid
 * @param csc
 * @param relativeError
 * @param timestep
 * @return the Placemark instance with description and name set
 */
private PlacemarkType createPlacemark(final String stopid, final CountSimComparison csc,
        final double relativeError, final int timestep, String countsType) {
    StringBuffer stringBuffer = new StringBuffer();
    PlacemarkType placemark = kmlObjectFactory.createPlacemarkType();
    stringBuffer.delete(0, stringBuffer.length());
    stringBuffer.append(STOP);
    stringBuffer.append(stopid);
    placemark.setDescription(createPlacemarkDescription(stopid, csc, relativeError, timestep, countsType));

    //      if(this.stopIDMap.get(stopid) == null){
    //         log.warn("Stop " + stopid + " has no name!?");
    //      } else {
    //         placemark.setName(this.stopIDMap.get(stopid));
    //      }

    StringBuffer name = new StringBuffer();
    if (countsType.equals("board")) {
        name.append("B: ");
    } else {
        name.append("A: ");
    }
    if (this.stopID2lineIdMap.get(stopid) != null) {
        for (String line : this.stopID2lineIdMap.get(stopid)) {
            name.append(line + " ");
        }
    } else {
        log.warn(stopid + " is not served by any line!?");
    }
    if (this.writePlacemarkName == true) {
        placemark.setName(name.toString());
    }

    return placemark;
}