Example usage for java.lang StringBuffer charAt

List of usage examples for java.lang StringBuffer charAt

Introduction

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

Prototype

@Override
public synchronized char charAt(int index) 

Source Link

Usage

From source file:org.mortbay.jetty.webapp.WebAppContext.java

/**
 * Create a canonical name for a webapp tmp directory.
 * The form of the name is:/* w ww  .  j  a v a  2  s.  c  om*/
 *  "Jetty_"+host+"_"+port+"__"+resourceBase+"_"+context+"_"+virtualhost+base36 hashcode of whole string
 *  
 *  host and port uniquely identify the server
 *  context and virtual host uniquely identify the webapp
 * @return
 */
private String getCanonicalNameForWebAppTmpDir() {
    StringBuffer canonicalName = new StringBuffer();
    canonicalName.append("Jetty");

    //get the host and the port from the first connector 
    Connector[] connectors = getServer().getConnectors();

    //Get the host
    canonicalName.append("_");
    String host = (connectors == null || connectors[0] == null ? "" : connectors[0].getHost());
    if (host == null)
        host = "0.0.0.0";
    canonicalName.append(host.replace('.', '_'));

    //Get the port
    canonicalName.append("_");
    //try getting the real port being listened on
    int port = (connectors == null || connectors[0] == null ? 0 : connectors[0].getLocalPort());
    //if not available (eg no connectors or connector not started), 
    //try getting one that was configured.
    if (port < 0)
        port = connectors[0].getPort();
    canonicalName.append(port);

    //Resource  base
    canonicalName.append("_");
    try {
        Resource resource = super.getBaseResource();
        if (resource == null) {
            if (_war == null || _war.length() == 0)
                resource = Resource.newResource(getResourceBase());

            // Set dir or WAR
            resource = Resource.newResource(_war);
        }

        String tmp = URIUtil.decodePath(resource.getURL().getPath());
        if (tmp.endsWith("/"))
            tmp = tmp.substring(0, tmp.length() - 1);
        if (tmp.endsWith("!"))
            tmp = tmp.substring(0, tmp.length() - 1);
        //get just the last part which is the filename
        int i = tmp.lastIndexOf("/");

        canonicalName.append(tmp.substring(i + 1, tmp.length()));
    } catch (Exception e) {
        Log.warn("Can't generate resourceBase as part of webapp tmp dir name", e);
    }

    //Context name
    canonicalName.append("_");
    String contextPath = getContextPath();
    contextPath = contextPath.replace('/', '_');
    contextPath = contextPath.replace('\\', '_');
    canonicalName.append(contextPath);

    //Virtual host (if there is one)
    canonicalName.append("_");
    String[] vhosts = getVirtualHosts();
    canonicalName.append((vhosts == null || vhosts[0] == null ? "" : vhosts[0]));

    //base36 hash of the whole string for uniqueness
    String hash = Integer.toString(canonicalName.toString().hashCode(), 36);
    canonicalName.append("_");
    canonicalName.append(hash);

    // sanitize
    for (int i = 0; i < canonicalName.length(); i++) {
        char c = canonicalName.charAt(i);
        if (!Character.isJavaIdentifierPart(c))
            canonicalName.setCharAt(i, '.');
    }

    return canonicalName.toString();
}

From source file:com.wabacus.system.component.application.report.UltraListReportType.java

protected void loadGroupConfig(UltraListReportGroupBean groupBean, XmlElementBean eleGroupBean,
        DisplayBean disbean, UltraListReportGroupBean parentGroupBean) {
    String label = eleGroupBean.attributeValue("label");
    label = label == null ? "" : label.trim();
    String labelstyleproperty = eleGroupBean.attributeValue("labelstyleproperty");
    labelstyleproperty = labelstyleproperty == null ? "" : labelstyleproperty.trim();
    groupBean.setLabelstyleproperty(labelstyleproperty, false);
    labelstyleproperty = groupBean.getLabelstyleproperty(null, true);
    labelstyleproperty = Tools.addPropertyValueToStylePropertyIfNotExist(labelstyleproperty, "align", "center");
    labelstyleproperty = Tools.addPropertyValueToStylePropertyIfNotExist(labelstyleproperty, "valign",
            "middle");
    groupBean.setLabelstyleproperty(labelstyleproperty, true);
    if (label != null) {
        label = label.trim();//from  ww w  .j  ava2  s . c om
        label = Config.getInstance().getResourceString(null, disbean.getPageBean(), label, true);
    }
    groupBean.setLabel(label);
    String rowspan = Tools.getPropertyValueByName("rowspan", labelstyleproperty, true);
    if (rowspan != null && !rowspan.trim().equals("")) {
        try {
            groupBean.setRowspan(Integer.parseInt(rowspan));
        } catch (NumberFormatException e) {
            log.warn("" + disbean.getReportBean().getPath()
                    + "?<group/>labelstylepropertyrowspan??", e);
            groupBean.setRowspan(1);
        }
    }
    List<XmlElementBean> lstEleGroupBeans = new ArrayList<XmlElementBean>();
    lstEleGroupBeans.add(eleGroupBean);
    LoadExtendConfigManager.loadBeforeExtendConfigForReporttype(groupBean, lstEleGroupBeans);
    List lstGroupChildren = new ArrayList();
    groupBean.setLstChildren(lstGroupChildren);
    StringBuffer childIdsBuf = new StringBuffer();
    List<XmlElementBean> lstChildrenElements = eleGroupBean.getLstChildElements();
    if (lstChildrenElements == null || lstChildrenElements.size() == 0) {
        throw new WabacusConfigLoadingException("" + disbean.getReportBean().getPath() + "?group"
                + label + "??");
    }
    for (XmlElementBean eleChildBeanTmp : lstChildrenElements) {
        if (eleChildBeanTmp.getName().equalsIgnoreCase("col")) {
            ColBean colbean = ComponentConfigLoadManager.loadColConfig(eleChildBeanTmp, disbean);
            //                {//?
            //                    setAlwaysDisplayTypeToGroupBean(ulrdbean,groupBean);
            AbsListReportColBean alrcbean = (AbsListReportColBean) colbean
                    .getExtendConfigDataForReportType(AbsListReportType.KEY);
            AbsListReportDisplayBean alrdbeanTmp = (AbsListReportDisplayBean) disbean
                    .getExtendConfigDataForReportType(AbsListReportType.KEY);
            if (alrdbeanTmp != null && alrdbeanTmp.getRowgrouptype() == 2 && alrcbean != null
                    && alrcbean.isRowgroup()) {
                throw new WabacusConfigLoadingException("" + disbean.getReportBean().getPath()
                        + "<group/><col/>??");
            }
            UltraListReportColBean ulrcbeanTmp = (UltraListReportColBean) colbean
                    .getExtendConfigDataForReportType(KEY);
            if (ulrcbeanTmp == null) {
                ulrcbeanTmp = new UltraListReportColBean(colbean);
                colbean.setExtendConfigDataForReportType(KEY, ulrcbeanTmp);
            }
            ulrcbeanTmp.setParentGroupid(groupBean.getGroupid());
            disbean.getLstCols().add(colbean);
            lstGroupChildren.add(colbean);
            childIdsBuf.append(colbean.getColid()).append(",");
        } else if (eleChildBeanTmp.getName().equalsIgnoreCase("group")) {
            UltraListReportGroupBean groupBeanChild = new UltraListReportGroupBean(disbean);
            groupBeanChild.setParentGroupid(groupBean.getGroupid());
            lstGroupChildren.add(groupBeanChild);
            loadGroupConfig(groupBeanChild, eleChildBeanTmp, disbean, groupBean);
            childIdsBuf.append(groupBeanChild.getGroupid()).append(",");
        }
    }
    if (lstGroupChildren.size() == 0) {
        throw new WabacusConfigLoadingException("" + disbean.getReportBean().getPath() + ""
                + label + "??");
    }
    if (childIdsBuf.charAt(childIdsBuf.length() - 1) == ',')
        childIdsBuf.deleteCharAt(childIdsBuf.length() - 1);
    groupBean.setChildids(childIdsBuf.toString());
    LoadExtendConfigManager.loadAfterExtendConfigForReporttype(groupBean, lstEleGroupBeans);
}

From source file:org.etudes.mneme.impl.SubmissionServiceImpl.java

/**
 * Notifies students about the evaluation
 * /*from  w  ww. ja v  a  2s.c o m*/
 * @param assessment
 *        The assessment.
 */
protected void notifyStudentEvaluation(Assessment assessment) {
    if (!assessment.getFormalCourseEval() && !assessment.getNotifyEval())
        return;

    // to
    List<User> submitUsers = assessment.getSubmitUsers();
    StringBuffer toStrBuf = new StringBuffer();

    for (User user : submitUsers) {
        toStrBuf.append(user.getEmail());
        toStrBuf.append(",");
    }

    if (toStrBuf.length() > 0 && toStrBuf.charAt(toStrBuf.length() - 1) == ',')
        toStrBuf.deleteCharAt(toStrBuf.length() - 1);

    String to = toStrBuf.toString();

    // from
    String from = "\"" + this.serverConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@"
            + this.serverConfigurationService.getServerName() + ">";

    String siteTitle = "";
    try {
        Site site = this.siteService.getSite(assessment.getContext());
        siteTitle = site.getTitle();
    } catch (IdUnusedException e) {
    }

    // subject
    String subject = null;
    if (assessment.getFormalCourseEval())
        subject = "Course Evaluation Now Open: " + siteTitle;

    // for html
    List<String> headers = new ArrayList<String>();
    headers.add("content-type: text/html");

    String content = getEvalNotificationSample(assessment);

    this.emailService.send(from, to, subject, content, null, null, headers);

    // mark the assessment as having the results sent
    this.assessmentService.setEvaluationSent(assessment, new Date());
}

From source file:de.rrze.idmone.utils.jpwgen.PwGenerator.java

/**
 * The real password generation is performed in this method
 * //from   ww  w .j a va2s  . c o m
 * @param size
 *            the length of the password
 * @param pw_flags
 *            the settings for the password
 * @return the newly created password
 */
private synchronized static String phonemes(int size, int pw_flags, Random random) {
    int c, i, len, flags, feature_flags;
    int prev, should_be;
    boolean first;
    String str;
    char ch;
    StringBuffer buf = new StringBuffer();

    do {
        buf.delete(0, buf.length());
        feature_flags = pw_flags;
        c = 0;
        prev = 0;
        should_be = 0;
        first = true;
        should_be = random.nextBoolean() ? VOWEL : CONSONANT;

        while (c < size) {

            i = random.nextInt(PW_ELEMENTS.length);
            str = PW_ELEMENTS[i].getValue();
            len = str.length();
            flags = PW_ELEMENTS[i].getType();
            /* Filter on the basic type of the next element */
            if ((flags & should_be) == 0) {
                continue;
            }
            /* Handle the NOT_FIRST flag */
            if (first && ((flags & NOT_FIRST) != 0))
                continue;
            /* Don't allow VOWEL followed a Vowel/Dipthong pair */
            if (((prev & VOWEL) != 0) && ((flags & VOWEL) != 0) && ((flags & DIPTHONG) != 0))
                continue;
            /* Don't allow us to overflow the buffer */
            if (len > size - c)
                continue;
            /*
             * OK, we found an element which matches our criteria, let's do
             * it!
             */
            buf.append(str);

            c += len;
            /* Handle the AMBIGUOUS flag */
            if ((pw_flags & PW_AMBIGUOUS) != 0) {
                int k = -1;
                for (int j = 0; j < PW_AMBIGUOUS_SYMBOLS.length(); j++) {
                    k = buf.indexOf(String.valueOf(PW_AMBIGUOUS_SYMBOLS.charAt(j)));
                    if (k != -1)
                        break;
                }
                if (k != -1) {
                    buf.delete(k, buf.length());
                    c = buf.length();
                }
            }

            /* Time to stop? */
            if (c >= size) {
                // System.out.println("BREAK 1: "+c + " - "+size);
                break;
            }
            /*
             * Handle PW_DIGITS
             */
            if ((pw_flags & PW_DIGITS) != 0) {
                if (!first && (random.nextInt(10) < 3)) {
                    do {
                        ch = (new Integer(random.nextInt(10))).toString().charAt(0);
                    } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1));
                    c++;
                    buf = buf.append(ch);
                    feature_flags &= ~PW_DIGITS;

                    first = true;
                    prev = 0;
                    should_be = random.nextBoolean() ? VOWEL : CONSONANT;
                    continue;
                }
            }

            /* Handle PW_SYMBOLS */
            if ((pw_flags & PW_SYMBOLS) != 0) {
                if (!first && (random.nextInt(10) < 2)) {
                    do {
                        ch = PW_SPECIAL_SYMBOLS.charAt(random.nextInt(PW_SPECIAL_SYMBOLS.length()));
                    } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1));
                    c++;
                    buf = buf.append(ch);
                    feature_flags &= ~PW_SYMBOLS;
                }
            } else if ((pw_flags & PW_SYMBOLS_REDUCED) != 0) {
                if (!first && (random.nextInt(10) < 2)) {
                    do {
                        ch = PW_SPECIAL_SYMBOLS_REDUCED
                                .charAt(random.nextInt(PW_SPECIAL_SYMBOLS_REDUCED.length()));
                    } while (((pw_flags & PW_AMBIGUOUS) != 0) && (PW_AMBIGUOUS_SYMBOLS.indexOf(ch) != -1));
                    c++;
                    buf = buf.append(ch);
                    feature_flags &= ~PW_SYMBOLS_REDUCED;
                }
            }

            /* Handle PW_UPPERS */
            if ((pw_flags & PW_UPPERS) != 0) {
                if ((first || ((flags & CONSONANT) != 0)) && (random.nextInt(10) < 2)) {
                    int lastChar = buf.length() - 1;
                    buf.setCharAt(lastChar, Character.toUpperCase(buf.charAt(lastChar)));
                    feature_flags &= ~PW_UPPERS;
                }
            }

            /*
             * OK, figure out what the next element should be
             */
            if (should_be == CONSONANT) {
                should_be = VOWEL;
            } else { /* should_be == VOWEL */
                if (((prev & VOWEL) != 0) || ((flags & DIPTHONG) != 0) || (random.nextInt(10) > 3))
                    should_be = CONSONANT;
                else
                    should_be = VOWEL;
            }
            prev = flags;
            first = false;

        }
    } while ((feature_flags & (PW_UPPERS | PW_DIGITS | PW_SYMBOLS | PW_SYMBOLS_REDUCED)) != 0);

    return buf.toString();
}

From source file:org.openhealthtools.mdht.uml.cda.core.util.CDAModelUtil.java

public static String computeConformanceMessage(Constraint constraint, boolean markup) {
    StringBuffer message = new StringBuffer();
    String strucTextBody = null;//from  ww  w .  j  a  va 2 s .  c  om
    String analysisBody = null;
    Map<String, String> langBodyMap = new HashMap<String, String>();

    ValueSpecification spec = constraint.getSpecification();
    if (spec instanceof OpaqueExpression) {
        for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
            String lang = ((OpaqueExpression) spec).getLanguages().get(i);
            String body = ((OpaqueExpression) spec).getBodies().get(i);

            if ("StrucText".equals(lang)) {
                strucTextBody = body;
            } else if ("Analysis".equals(lang)) {
                analysisBody = body;
            } else {
                langBodyMap.put(lang, body);
            }
        }
    }

    String displayBody = null;
    if (strucTextBody != null && strucTextBody.trim().length() > 0) {
        // TODO if markup, parse strucTextBody and insert DITA markup
        displayBody = strucTextBody;
    } else if (analysisBody != null && analysisBody.trim().length() > 0) {
        if (markup) {
            // escape non-dita markup in analysis text
            displayBody = escapeMarkupCharacters(analysisBody);
            // change severity words to bold text
            displayBody = replaceSeverityWithBold(displayBody);
        } else {
            displayBody = analysisBody;
        }
    }

    if (!markup) {
        message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
    }

    if (displayBody == null || !containsSeverityWord(displayBody)) {
        String keyword = getValidationKeyword(constraint);
        if (keyword == null) {
            keyword = "SHALL";
        }

        message.append(markup ? "<b>" : "");
        message.append(keyword);
        message.append(markup ? "</b>" : "");
        message.append(" satisfy: ");
    }

    if (displayBody == null) {
        message.append(constraint.getName());
    } else {
        message.append(displayBody);
    }
    appendConformanceRuleIds(constraint, message, markup);

    // include comment text only in markup output
    if (false && markup && constraint.getOwnedComments().size() > 0) {
        message.append("<ul>");
        for (Comment comment : constraint.getOwnedComments()) {
            message.append("<li>");
            message.append(fixNonXMLCharacters(comment.getBody()));
            message.append("</li>");
        }
        message.append("</ul>");
    }

    // Include other constraint languages, e.g. OCL or XPath
    if (false && langBodyMap.size() > 0) {
        message.append("<ul>");
        for (String lang : langBodyMap.keySet()) {
            message.append("<li>");
            message.append("<codeblock>[" + lang + "]: ");
            message.append(escapeMarkupCharacters(langBodyMap.get(lang)));
            message.append("</codeblock>");
            message.append("</li>");
        }
        message.append("</ul>");
    }

    if (!markup) {
        // remove line feeds
        int index;
        while ((index = message.indexOf("\r")) >= 0) {
            message.deleteCharAt(index);
        }
        while ((index = message.indexOf("\n")) >= 0) {
            message.deleteCharAt(index);
            if (message.charAt(index) != ' ') {
                message.insert(index, " ");
            }
        }
    }

    return message.toString();
}

From source file:com.orientechnologies.orient.jdbc.H2.java

public static Collection<String> translate(String sql) throws SQLException {
    List<String> sections = new ArrayList<String>();
    if (StringUtils.isNotEmpty(sql)) {
        boolean quoted = false;
        int bracesOpen = 0;
        boolean create = false;
        boolean type = false;
        boolean typeLen = false;
        boolean not = false;
        int max = 0;
        String lastWord = null;/*from  ww w  .j a va2s .  c  om*/
        String className = null;
        String fieldName = null;
        boolean classNameAppended = false;
        StringBuffer section = new StringBuffer();

        for (final StringTokenizer splitter = new StringTokenizer(sql, " ();,'`\r\n\t", true); splitter
                .hasMoreTokens();) {
            String w = splitter.nextToken();
            if (w.length() == 0)
                continue;

            if (!quoted) {
                w = w.toUpperCase();
                if (stripWords.contains(w) || (SPACE.equals(w)))
                    section.append(SPACE_CHAR);
                else if (QUOTE.equals(w) || QUOTE_ALT.equals(w)) {
                    section.append(w);
                    if (QUOTE_ALT.equals(w) && !quoted)
                        w = QUOTE;
                    if (QUOTE.equals(w) && !QUOTE.equals(lastWord))
                        quoted = !quoted;
                } else if (BRACE_OPEN.equals(w)) {
                    bracesOpen++;
                    if (create) {
                        trim(section);
                        if (!type) {
                            sections.add(section.toString());
                            section = new StringBuffer("CREATE PROPERTY ");
                            section.append(className).append('.');
                        } else {
                            sections.add(section.toString());
                            section = new StringBuffer("ALTER PROPERTY ");
                            section.append(className).append('.');
                            section.append(fieldName).append(" MAX ");
                            typeLen = true;
                        }
                    } else
                        section.append(w);

                } else if (BRACE_CLOSED.equals(w)) {
                    bracesOpen--;
                    if (create) {
                        if (typeLen) {
                            trim(section);
                            section.append(SPACE_CHAR).append(max);
                            typeLen = false;
                            max = 0;
                            section.append(SPACE_CHAR);
                            continue;
                        } else if (type) {
                            type = false;
                            classNameAppended = false;
                        } else
                            create = false;
                    }
                    section.append(w);
                } else if (COMMA.equals(w)) {
                    if (create) {
                        if (type) {
                            if (!typeLen) {
                                trim(section);
                                sections.add(section.toString());
                                section = new StringBuffer("CREATE PROPERTY ");
                                section.append(className).append('.');
                                type = false;
                                classNameAppended = true;
                                fieldName = null;
                            } else
                                max++;
                        } else
                            section.append(w);
                    }
                } else if (create) {
                    if (type) {
                        boolean suppw = supportedWords.contains(w);
                        if (typeLen || suppw) {
                            if (suppw) {
                                if (NOT.equals(w)) {
                                    not = true;
                                    continue;
                                } else {
                                    trim(section);
                                    sections.add(section.toString());
                                    section = new StringBuffer("ALTER PROPERTY ");
                                    section.append(className).append('.');
                                    section.append(fieldName);
                                    if (not) {
                                        section.append(" NOT");
                                        not = false;
                                    }
                                    if (NULL.equals(w)) {
                                        if (section.lastIndexOf(NOT) == section.length() - 3)
                                            section.append(w).append("=TRUE");
                                        else
                                            section.append(SPACE_CHAR).append(NOT).append(w).append("=FALSE");
                                    } else
                                        section.append(w);
                                }
                            } else
                                max += Integer.parseInt(w);
                        } else {
                            final String mtype = typeMap.get(w);
                            if (StringUtils.isEmpty(mtype))
                                throw new SQLException(String
                                        .format("Sorry, type %s is not supported by Orient at the moment.", w));
                            section.append(mtype);
                        }

                    } else if (!classNameAppended) {
                        className = w;
                        section.append(className);
                        classNameAppended = true;
                    } else {
                        if (section.charAt(section.length() - 1) == SPACE_CHAR)
                            section.deleteCharAt(section.length() - 1);
                        section.append(w);
                        fieldName = w;
                        type = true;
                    }
                } else if (supportedWords.contains(w))
                    section.append(w);
                else if (SEMICOLON.equals(w)) {
                    trim(section);
                    sections.add(section.toString());
                    section = new StringBuffer();
                } else if (TABLE.equals(w)) {
                    section.append(CLASS);
                    create = true;
                } else
                    section.append(w);
            } else
                section.append(w);
        }
    }
    return sections;
}

From source file:com.arksoft.epamms.ZGlobal1_Operation.java

public int SetStringUpperLowerCase(StringBuilder sbName) {
    String string;/*from  ww w .j  av  a 2s .  c  o  m*/
    boolean bSuffix = false;
    int nBlankFound = 0;
    @SuppressWarnings("unused")
    int nLth;
    int k;
    int j;

    // Eliminate leading and trailing blanks.
    string = sbName.toString();
    string = string.trim();

    // Force first character to be upper case
    StringBuffer sb = new StringBuffer(string.toLowerCase()); // force string to lower case
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));

    for (k = 1; k < sb.length(); k++) {
        // Eliminate multiple consecutive blanks.
        if (sb.charAt(k) == ' ') {
            j = k;
            while (sb.charAt(j + 1) == ' ')
                j++;

            if (j > k)
                sb.delete(k + 1, j);
        } else
        // if ( sb.charAt( k ) != ' ' )
        {
            if (sb.charAt(k - 1) == ' ') {
                nBlankFound++;
                char ch = Character.toUpperCase(sb.charAt(k));
                sb.setCharAt(k, ch);

                if (ch == 'I' || ch == 'V')
                    bSuffix = true;
                else
                    bSuffix = false;
            } else {
                if (nBlankFound > 1 && bSuffix) // checking for II or III or IV or V or VI or VII or VIII
                {
                    if ((sb.charAt(k) == 'i' || sb.charAt(k) == 'v') && (sb.charAt(k + 1) == '\0'
                            || sb.charAt(k + 1) == 'i' || sb.charAt(k + 1) == 'v')) {
                        sb.setCharAt(k, Character.toUpperCase(sb.charAt(k)));
                    } else
                        bSuffix = false;
                } else {
                    bSuffix = false; // can't start with suffix
                }
            }
        }
    }

    zstrcpy(sbName, sb.toString());
    return sbName.length();

}

From source file:org.eclipse.mdht.uml.cda.core.util.CDAModelUtil.java

private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) {
    StringBuffer message = new StringBuffer();
    String strucTextBody = null;// w w w  . j a  v a 2  s.  c om
    String analysisBody = null;
    Map<String, String> langBodyMap = new HashMap<String, String>();

    CDAProfileUtil.getLogicalConstraint(constraint);

    ValueSpecification spec = constraint.getSpecification();
    if (spec instanceof OpaqueExpression) {
        for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) {
            String lang = ((OpaqueExpression) spec).getLanguages().get(i);
            String body = ((OpaqueExpression) spec).getBodies().get(i);

            if ("StrucText".equals(lang)) {
                strucTextBody = body;
            } else if ("Analysis".equals(lang)) {
                analysisBody = body;
            } else {
                langBodyMap.put(lang, body);
            }
        }
    }

    String displayBody = null;
    if (strucTextBody != null && strucTextBody.trim().length() > 0) {
        // TODO if markup, parse strucTextBody and insert DITA markup
        displayBody = strucTextBody;
    } else if (analysisBody != null && analysisBody.trim().length() > 0) {
        Boolean ditaEnabled = false;
        try {
            Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(constraint,
                    ICDAProfileConstants.CONSTRAINT_VALIDATION);
            ditaEnabled = (Boolean) constraint.getValue(stereotype,
                    ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);
        } catch (IllegalArgumentException e) { /* Swallow this */
        }
        if (markup && !ditaEnabled) {
            // escape non-dita markup in analysis text
            displayBody = escapeMarkupCharacters(analysisBody);
            // change severity words to bold text
            displayBody = replaceSeverityWithBold(displayBody);
        } else {
            displayBody = analysisBody;
        }
    }

    if (displayBody == null) {
        List<Stereotype> stereotypes = constraint.getAppliedStereotypes();
        if (stereotypes.isEmpty()) {
            // This should never happen but in case it does we deal with it appropriately
            // by bypassing custom constraint message additions
            return "";
        }
    }

    if (!markup) {
        message.append(getPrefixedSplitName(constraint.getContext())).append(" ");
    }

    if (displayBody == null || !containsSeverityWord(displayBody)) {
        String keyword = getValidationKeyword(constraint);
        if (keyword == null) {
            keyword = "SHALL";
        }

        message.append(markup ? "<b>" : "");
        message.append(keyword);
        message.append(markup ? "</b>" : "");
        message.append(" satisfy: ");
    }

    if (displayBody == null) {
        message.append(constraint.getName());
    } else {
        message.append(displayBody);
    }
    appendConformanceRuleIds(constraint, message, markup);

    if (!markup) {
        // remove line feeds
        int index;
        while ((index = message.indexOf("\r")) >= 0) {
            message.deleteCharAt(index);
        }
        while ((index = message.indexOf("\n")) >= 0) {
            message.deleteCharAt(index);
            if (message.charAt(index) != ' ') {
                message.insert(index, " ");
            }
        }
    }

    return message.toString();
}

From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java

/**
 * Iterates through all question types, captures responses and creates export summary spreadsheet
 * @param workbook Workbook object//from   ww w  .  j ava2s  .  c  o  m
 * @param assessment Assessment object
 * @return Spreadsheet with Export summary
 */
HSSFSheet createResponsesSheet(HSSFWorkbook workbook, Assessment assessment) {
    boolean isSurvey;
    if (assessment.getType() == AssessmentType.survey)
        isSurvey = true;
    else
        isSurvey = false;

    Map<String, Integer> userRowMap = new HashMap();
    HSSFSheet sheet = workbook.createSheet("Submission responses");

    HSSFRow headerRow = sheet.createRow((short) 0);
    AssessmentParts part = assessment.getParts();

    List<Part> parts = part.getParts();
    if (parts == null || parts.size() == 0)
        return null;

    List<Question> questions = new ArrayList();
    for (Iterator partIt = parts.iterator(); partIt.hasNext();) {
        Part partObj = (Part) partIt.next();
        List<Question> questionsUsed = partObj.getQuestionsUsed();
        questions.addAll(questionsUsed);
    }

    HSSFCellStyle style = workbook.createCellStyle();
    HSSFFont font = workbook.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    style.setFont(font);
    // Printing header row and question text
    if (!isSurvey) {
        HSSFCell cell0 = headerRow.createCell((short) (0));
        cell0.setCellStyle(style);
        cell0.setCellValue(this.messages.getFormattedMessage("export_lastname", null));
        HSSFCell cell1 = headerRow.createCell((short) (1));
        cell1.setCellStyle(style);
        cell1.setCellValue(this.messages.getFormattedMessage("export_firstname", null));
        HSSFCell cell2 = headerRow.createCell((short) (2));
        cell2.setCellStyle(style);
        cell2.setCellValue(this.messages.getFormattedMessage("export_username", null));

        HSSFCell cell3 = headerRow.createCell((short) (3));
        cell3.setCellStyle(style);
        cell3.setCellValue(this.messages.getFormattedMessage("export_score", null));
    } else {
        HSSFCell cell0 = headerRow.createCell((short) (0));
        cell0.setCellStyle(style);
        cell0.setCellValue(this.messages.getFormattedMessage("export_user", null));
    }

    int i;
    if (isSurvey)
        i = 1;
    else
        i = 4;
    for (Iterator it = questions.iterator(); it.hasNext();) {
        Question q = (Question) it.next();
        String quest_desc = null;

        TypeSpecificQuestion tsq = q.getTypeSpecificQuestion();
        if (tsq instanceof FillBlanksQuestionImpl) {
            quest_desc = stripHtml(((FillBlanksQuestionImpl) tsq).getText());
        } else {
            if (tsq instanceof EssayQuestionImpl || tsq instanceof TaskQuestionImpl) {
                if (tsq instanceof EssayQuestionImpl) {
                    EssayQuestionImpl eqi = (EssayQuestionImpl) tsq;
                    if (eqi.getSubmissionType() == SubmissionType.inline)
                        quest_desc = stripHtml(q.getDescription());
                }
                if (tsq instanceof TaskQuestionImpl) {
                    TaskQuestionImpl tqi = (TaskQuestionImpl) tsq;
                    if (tqi.getSubmissionType() == SubmissionType.inline)
                        quest_desc = stripHtml(q.getDescription());
                }
            } else {
                quest_desc = stripHtml(q.getDescription());
            }
        }
        if (quest_desc != null) {
            HSSFCell cell = headerRow.createCell((short) (i++));
            cell.setCellStyle(style);
            cell.setCellValue(quest_desc);
        }
    }

    int j;
    if (isSurvey)
        j = 1;
    else
        j = 4;
    boolean answersExist = false;
    for (Iterator it = questions.iterator(); it.hasNext();) {
        Question q = (Question) it.next();
        TypeSpecificQuestion tsq = q.getTypeSpecificQuestion();
        //Only captures inline submissions for essays and tasks
        if (tsq instanceof EssayQuestionImpl || tsq instanceof TaskQuestionImpl) {
            if (tsq instanceof EssayQuestionImpl) {
                EssayQuestionImpl eqi = (EssayQuestionImpl) tsq;
                if (eqi.getSubmissionType() != SubmissionType.inline) {
                    continue;
                }
            }
            if (tsq instanceof TaskQuestionImpl) {
                TaskQuestionImpl tqi = (TaskQuestionImpl) tsq;
                if (tqi.getSubmissionType() != SubmissionType.inline) {
                    continue;
                }
            }
        }
        List<Answer> answers = this.submissionService.findSubmissionAnswers(assessment, q, Boolean.TRUE,
                FindAssessmentSubmissionsSort.userName_a, null, null);
        if (answers == null || answers.size() == 0)
            continue;
        else
            answersExist = true;
        for (Answer answer : answers) {
            HSSFRow row;
            try {
                String userId = answer.getSubmission().getUserId();
                String subId = answer.getSubmission().getId();
                if (userRowMap == null || userRowMap.size() == 0 || (userRowMap.get(userId + subId) == null)) {
                    int rowNum = sheet.getLastRowNum() + 1;
                    row = sheet.createRow(rowNum);
                    if (!isSurvey) {
                        User user = this.userDirectoryService.getUser(userId);
                        row.createCell((short) 0).setCellValue(user.getLastName());
                        row.createCell((short) 1).setCellValue(user.getFirstName());
                        row.createCell((short) 2).setCellValue(user.getDisplayId());
                        row.createCell((short) 3).setCellValue(
                                roundTwoDecimals(answer.getSubmission().getTotalScore().floatValue()));
                    } else {
                        row.createCell((short) 0)
                                .setCellValue(this.messages.getFormattedMessage("export_user", null));
                    }
                    userRowMap.put(userId + subId, new Integer(rowNum));
                } else {
                    row = sheet.getRow(userRowMap.get(userId + subId).intValue());
                }

                TypeSpecificAnswer a = answer.getTypeSpecificAnswer();
                if (a instanceof EssayAnswerImpl) {
                    EssayAnswerImpl essay = (EssayAnswerImpl) a;
                    row.createCell((short) j).setCellValue(stripHtml(essay.getAnswerData()));
                }
                if (a instanceof TrueFalseAnswerImpl) {
                    TrueFalseAnswerImpl tf = (TrueFalseAnswerImpl) a;
                    if (!isSurvey && tf.getCompletelyCorrect().booleanValue())
                        row.createCell((short) j).setCellValue("*" + tf.getAnswer() + "*");
                    else
                        row.createCell((short) j).setCellValue(tf.getAnswer());
                }
                if (a instanceof MultipleChoiceAnswerImpl) {
                    MultipleChoiceAnswerImpl mc = (MultipleChoiceAnswerImpl) a;
                    List<MultipleChoiceQuestionImpl.MultipleChoiceQuestionChoice> choiceList = ((MultipleChoiceQuestionImpl) mc
                            .getAnswerObject().getQuestion().getTypeSpecificQuestion()).getChoicesAsAuthored();
                    String[] ansArray = mc.getAnswers();
                    String[] choiceArray = new String[mc.getAnswers().length];
                    Set<Integer> correctAnswers = ((MultipleChoiceQuestionImpl) mc.getAnswerObject()
                            .getQuestion().getTypeSpecificQuestion()).getCorrectAnswerSet();

                    int l = 0;
                    for (Iterator chIt = choiceList.iterator(); chIt.hasNext();) {
                        MultipleChoiceQuestionImpl.MultipleChoiceQuestionChoice mq = (MultipleChoiceQuestionImpl.MultipleChoiceQuestionChoice) chIt
                                .next();

                        if (Arrays.asList(ansArray).contains(mq.getId())) {
                            if (!isSurvey && correctAnswers.contains(Integer.parseInt(mq.getId()))) {
                                choiceArray[l] = "*" + stripHtml(mq.getText().trim()) + "*";
                            } else {
                                choiceArray[l] = stripHtml(mq.getText().trim());
                            }
                            l++;
                        }
                    }

                    row.createCell((short) j).setCellValue(getCommaAnswers(choiceArray));
                }
                if (a instanceof FillBlanksAnswerImpl) {
                    FillBlanksAnswerImpl fb = (FillBlanksAnswerImpl) a;
                    row.createCell((short) j).setCellValue(stripHtml(getCommaAnswers(checkCorrectFill(fb))));
                }
                if (a instanceof LikertScaleAnswerImpl) {
                    LikertScaleAnswerImpl ls = (LikertScaleAnswerImpl) a;
                    LikertScaleQuestionImpl lsq = (LikertScaleQuestionImpl) ls.getAnswerObject().getQuestion()
                            .getTypeSpecificQuestion();
                    List<LikertScaleQuestionImpl.LikertScaleQuestionChoice> choiceList = lsq.getChoices();
                    for (Iterator chIt = choiceList.iterator(); chIt.hasNext();) {
                        LikertScaleQuestionImpl.LikertScaleQuestionChoice lqc = (LikertScaleQuestionImpl.LikertScaleQuestionChoice) chIt
                                .next();
                        if (lqc.getId().equals(ls.getAnswer())) {
                            row.createCell((short) j).setCellValue(stripHtml(lqc.getText()));
                            break;
                        }
                    }
                }
                if (a instanceof MatchAnswerImpl) {
                    MatchAnswerImpl ma = (MatchAnswerImpl) a;
                    Map matchMap = (LinkedHashMap) ma.getAnswer();
                    Iterator it2 = matchMap.entrySet().iterator();
                    StringBuffer matchStrBuf = new StringBuffer();

                    List choiceList = ((MatchQuestionImpl) ma.getAnswerObject().getQuestion()
                            .getTypeSpecificQuestion()).getPairsForDelivery();
                    while (it2.hasNext()) {
                        Map.Entry entry = (Map.Entry) it2.next();
                        String key = (String) entry.getKey();
                        String value = (String) ((Value) entry.getValue()).getValue();
                        String matchVal = fetchName(choiceList, key, true);
                        boolean correctMatch = checkCorrectMatch(choiceList, key, value);
                        if (!isSurvey && correctMatch)
                            matchStrBuf.append("*");
                        matchStrBuf.append(stripHtml(matchVal.trim()));
                        matchStrBuf.append("->");
                        String choiceVal = fetchName(choiceList, value, false);
                        if (choiceVal == null)
                            matchStrBuf.append(this.messages.getFormattedMessage("nosel_made", null));
                        else
                            matchStrBuf.append(stripHtml(choiceVal.trim()));

                        if (!isSurvey && correctMatch)
                            matchStrBuf.append("*");
                        matchStrBuf.append(", ");
                    }
                    if (matchStrBuf.length() > 0 && matchStrBuf.charAt(matchStrBuf.length() - 2) == ',') {
                        String matchStrBufTrim = matchStrBuf.substring(0, matchStrBuf.length() - 2);
                        row.createCell((short) j).setCellValue(stripHtml(matchStrBufTrim));
                    }
                }
                if (a instanceof TaskAnswerImpl) {
                    TaskAnswerImpl ta = (TaskAnswerImpl) a;
                    row.createCell((short) j).setCellValue(stripHtml(ta.getAnswerData()));
                }
            } catch (UserNotDefinedException e) {
                M_log.warn("createResponsesSheet: " + e.toString());
            }
        }
        j = j + 1;
    }
    if (!answersExist)
        return null;
    return sheet;
}