Example usage for java.lang StringBuilder charAt

List of usage examples for java.lang StringBuilder charAt

Introduction

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

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

From source file:davmail.caldav.CaldavConnection.java

protected void appendItemResponse(CaldavResponse response, CaldavRequest request, ExchangeSession.Item item)
        throws IOException {
    StringBuilder eventPath = new StringBuilder();
    eventPath.append(encodePath(request, request.getPath()));
    if (!(eventPath.charAt(eventPath.length() - 1) == '/')) {
        eventPath.append('/');
    }//w  ww . j  ava  2 s.c  o  m
    String itemName = StringUtil.xmlEncode(item.getName());
    eventPath.append(URIUtil.encodeWithinQuery(itemName));
    response.startResponse(eventPath.toString());
    response.startPropstat();
    if (request.hasProperty("calendar-data") && item instanceof ExchangeSession.Event) {
        response.appendCalendarData(item.getBody());
    }
    if (request.hasProperty("address-data") && item instanceof ExchangeSession.Contact) {
        response.appendContactData(item.getBody());
    }
    if (request.hasProperty("getcontenttype")) {
        if (item instanceof ExchangeSession.Event) {
            response.appendProperty("D:getcontenttype", "text/calendar; component=vevent");
        } else if (item instanceof ExchangeSession.Contact) {
            response.appendProperty("D:getcontenttype", "text/vcard");
        }
    }
    if (request.hasProperty("getetag")) {
        response.appendProperty("D:getetag", item.getEtag());
    }
    if (request.hasProperty("resourcetype")) {
        response.appendProperty("D:resourcetype");
    }
    if (request.hasProperty("displayname")) {
        response.appendProperty("D:displayname", itemName);
    }
    response.endPropStatOK();
    response.endResponse();
}

From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java

private void deSpace(StringBuilder builder) {
    // remove whitespace from front
    while (builder.length() > 0) {
        if (Character.isWhitespace(builder.charAt(0))) {
            builder.deleteCharAt(0);//from   w w w  .  ja v a  2  s .c om
        } else {
            break;
        }
    }

    // remove whitespace from back
    while (builder.length() > 0) {
        int j = builder.length() - 1;
        if (Character.isWhitespace(builder.charAt(j))) {
            builder.deleteCharAt(j);
        } else {
            break;
        }
    }

    // remove duplicate spaces
    // TODO - detect any whitespace type
    boolean previousWasSpace = false;
    for (int j = 0; j < builder.length();) {
        char c = builder.charAt(j);
        if (previousWasSpace && c == ' ') {
            builder.deleteCharAt(j);
        } else {
            ++j;
            previousWasSpace = c == ' ';
        }
    }
}

From source file:davmail.imap.ImapConnection.java

protected void appendEnvelopeHeader(StringBuilder buffer, String[] value) throws UnsupportedEncodingException {
    if (buffer.charAt(buffer.length() - 1) != '(') {
        buffer.append(' ');
    }/*  ww w. j  a  v  a  2 s .co m*/
    if (value != null && value.length > 0) {
        appendEnvelopeHeaderValue(buffer, MimeUtility.unfold(value[0]));
    } else {
        buffer.append("NIL");
    }
}

From source file:com.wabacus.WabacusFacade.java

public static String doServerValidateOnBlur(HttpServletRequest request, HttpServletResponse response) {
    String inputboxid = request.getParameter("INPUTBOXID");
    if (inputboxid == null || inputboxid.trim().equals("")) {
        throw new WabacusRuntimeException("?ID");
    }/*from   w  w w . j  av  a2  s  .co m*/
    String boxvalue = request.getParameter("INPUTBOX_VALUE");
    String othervalues = request.getParameter("OTHER_VALUES");
    StringBuilder resultBuf = new StringBuilder();
    ReportRequest rrequest = null;
    try {
        rrequest = new ReportRequest(request, -1);
        WabacusResponse wresponse = new WabacusResponse(response);
        rrequest.setWResponse(wresponse);
        rrequest.initReportCommon();
        List<Map<String, String>> lstOthervalues = EditableReportAssistant.getInstance()
                .parseSaveDataStringToList(othervalues);
        Map<String, String> mOtherValues = null;
        if (lstOthervalues != null && lstOthervalues.size() > 0)
            mOtherValues = lstOthervalues.get(0);
        ReportBean rbean = rrequest.getLstAllReportBeans().get(0);
        ServerValidateBean svb = rbean.getServerValidateBean(inputboxid);
        if (svb == null || Tools.isEmpty(svb.getLstValidateMethods())) {
            throw new WabacusRuntimeException("" + rbean.getPath() + "" + inputboxid
                    + "????");
        }
        List<String> lstErrorMessages = new ArrayList<String>();
        StringBuilder errorPromptParamsBuf = new StringBuilder();
        boolean isSuccess = svb.validate(rrequest, boxvalue, mOtherValues, lstErrorMessages,
                errorPromptParamsBuf);
        resultBuf.append("<WX-SUCCESS-FLAG>").append(isSuccess).append("</WX-SUCCESS-FLAG>");
        if (lstErrorMessages.size() > 0) {
            resultBuf.append("<WX-ERROR-MESSAGE>");
            for (String errormsgTmp : lstErrorMessages) {
                resultBuf.append(errormsgTmp).append(";");
            }
            if (resultBuf.charAt(resultBuf.length() - 1) == ';')
                resultBuf.deleteCharAt(resultBuf.length() - 1);
            resultBuf.append("</WX-ERROR-MESSAGE>");
        }
        if (errorPromptParamsBuf.length() > 0) {
            resultBuf.append("<WX-ERRORPROMPT-PARAMS>");
            resultBuf.append(errorPromptParamsBuf.toString().trim());
            resultBuf.append("</WX-ERRORPROMPT-PARAMS>");
        }
        if (rrequest.getMServerValidateDatas() != null && rrequest.getMServerValidateDatas().size() > 0) {
            resultBuf.append("<WX-SERVER-DATA>{");
            for (Entry<String, String> entryTmp : rrequest.getMServerValidateDatas().entrySet()) {
                resultBuf.append(entryTmp.getKey() + ":\"" + entryTmp.getValue() + "\",");
            }
            if (resultBuf.charAt(resultBuf.length() - 1) == ',')
                resultBuf.deleteCharAt(resultBuf.length() - 1);
            resultBuf.append("}</WX-SERVER-DATA>");
        }
    } catch (Exception e) {
        log.error("" + inputboxid + "?", e);
        throw new WabacusRuntimeException("" + inputboxid + "?", e);
    } finally {
        if (rrequest != null)
            rrequest.destroy(false);
    }
    return resultBuf.toString();
}

From source file:com.nec.harvest.controller.PettyCashbookReportController.java

/**
 * ????PDF?//from  w  w w . j  av a 2  s .com
 * 
 * @param orgCode
 *            String
 * @param response
 *            HttpServletResponse
 * @param device      
 *            Device
 * @param model     
 *            Model
 * @param pettyCashBookForm
 *            PettyCashBookForm
 * @return JSONBean
 */
@RequestMapping(value = "/area", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody JSONBean getDistrictInformation(@RequestBody final PettyCashBookForm pettyCashBookForm,
        final HttpServletResponse response, final Device device, final Model model) {
    if (logger.isDebugEnabled()) {
        logger.debug("Trying to rendering report...");
    }

    PettyCashBookReport pettyCashBook = null;

    // ??
    try {
        pettyCashBook = organizationService.findDistrictByShop(pettyCashBookForm.getShopCode());
        if (pettyCashBook != null) {
            logger.info("There is a organization {} in the DB", pettyCashBook.getStrCode());
        }
    } catch (IllegalArgumentException | ObjectNotFoundException ex) {
        logger.warn(ex.getMessage());

        // Ignore this CASE. If the database is not exist then can be showed empty
        pettyCashBook = new PettyCashBookReport();
    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        return new JSONBean(Boolean.FALSE, -1, getSystemError());
    }

    List<PettyCashbookReportBean> pettyCashBookTmpLst = pettyCashBookForm.getPettyCashbookReportBean();
    Map<String, Object> parameterMap = new HashMap<String, Object>();
    response.setCharacterEncoding(HttpServletContentType.DEFAULT_ENCODING);

    // PDF generate UUID
    final String PDF_UUID = GenerateUUID.randomUUID();

    // ??DD/MM/YYYY????
    Locale locale = new Locale("en", "EN", "EN");
    parameterMap.put(JRParameter.REPORT_LOCALE, locale);

    // 
    List<PettyCashbookReportBean> pettyCashFlLst = new ArrayList<PettyCashbookReportBean>(
            pettyCashBookTmpLst.size());
    PettyCashbookReportBean ptRptBean;

    // ??
    Map<String, String> grpItem = new HashMap<String, String>();

    // ??
    Double tmpKingaku = 0.0;

    // x,xxx???
    DecimalFormat formatter = new DecimalFormat("#,###");
    for (PettyCashbookReportBean subPtCh : pettyCashBookTmpLst) {
        if (!grpItem.containsKey(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()))) {
            if (StringUtils.isEmpty(subPtCh.getCltAmount())) {
                grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), "0");
            } else {
                // Modified by SONDN 2014-08-22
                // Fixing bug CT-005: Allow end user input minus number
                //               grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()), 
                //                     formatter.format(Double.valueOf(subPtCh.getCltAmount().replaceAll("[^0-9]", StringUtils.EMPTY))));

                grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()),
                        formatter.format(Double.valueOf(StringUtil.removeCommaChar(subPtCh.getCltAmount()))));
            }
        } else {
            // Modified by SONDN 2014-08-22
            // Fixing bug CT-005: Allow end user input minus number
            //            tmpKingaku = Double.valueOf(grpItem.get(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName())).replaceAll("[^0-9]", StringUtils.EMPTY));
            //            if (!StringUtils.isEmpty(subPtCh.getCltAmount())) {
            //               tmpKingaku = tmpKingaku + Double.valueOf(subPtCh.getCltAmount().replaceAll("[^0-9]", StringUtils.EMPTY));
            //            }

            tmpKingaku = Double.valueOf(StringUtil.removeCommaChar(
                    grpItem.get(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()))));
            if (!StringUtils.isEmpty(subPtCh.getCltAmount())) {
                tmpKingaku = tmpKingaku + Double.valueOf(subPtCh.getCltAmount());
            }
            grpItem.put(subPtCh.getCltItemCode().concat(PDF_UUID).concat(subPtCh.getCltItemName()),
                    formatter.format(tmpKingaku));
        }
    }

    StringBuilder tmpStrDate;
    for (PettyCashbookReportBean childPtCh : pettyCashBookTmpLst) {
        ptRptBean = new PettyCashbookReportBean();

        // 
        ptRptBean.setKamokuCode(childPtCh.getCltItemCode());

        // ??
        String cltItemName = childPtCh.getCltItemName();
        if (StringUtils.isNotEmpty(cltItemName)) {
            ptRptBean.setKamokuName(SPACE_FULL.concat(cltItemName.substring(1)));
        } else {
            ptRptBean.setKamokuName(StringUtils.EMPTY);
        }

        // ?
        String cltAmount = childPtCh.getCltAmount();
        if (StringUtils.isNotEmpty(cltAmount)) {
            ptRptBean.setKingaku(formatter.format(Double.valueOf(cltAmount)));
        } else {
            ptRptBean.setKingaku(StringUtils.EMPTY);
        }

        // ??
        ptRptBean.setNaiyou(childPtCh.getCltContent());
        ptRptBean.setShito(childPtCh.getCltRemark());

        // 
        String cltDate = childPtCh.getCltDate();
        if (StringUtils.isNotEmpty(cltDate)) {
            tmpStrDate = new StringBuilder(cltDate.substring(5));
            if (ZERO_CHAR == tmpStrDate.charAt(0)) {
                tmpStrDate.deleteCharAt(0);
            }

            int zeroCharPos = tmpStrDate.length() - 2;
            if (ZERO_CHAR == tmpStrDate.charAt(zeroCharPos)) {
                tmpStrDate.deleteCharAt(zeroCharPos);
            }

            ptRptBean.setSrDate(tmpStrDate.toString());
        } else {
            ptRptBean.setSrDate(StringUtils.EMPTY);
        }

        // ?
        ptRptBean.setSumPrice(StringUtils.EMPTY);

        // 
        ptRptBean.setGrpFlg(Boolean.FALSE);
        ptRptBean.setGrpItemCode(StringUtils.EMPTY);
        ptRptBean.setGrpItemName(StringUtils.EMPTY);
        ptRptBean.setGrpCash(StringUtils.EMPTY);
        ptRptBean.setDetailLine(Boolean.FALSE);

        pettyCashFlLst.add(ptRptBean);
    }

    pettyCashFlLst.get(pettyCashFlLst.size() - 1).setDetailLine(Boolean.FALSE);

    // ? 
    ptRptBean = new PettyCashbookReportBean();
    ptRptBean.setSumPrice(pettyCashBookForm.getVerticalTotal());
    ptRptBean.setGrpFlg(Boolean.FALSE);
    ptRptBean.setDetailLine(Boolean.FALSE);
    pettyCashFlLst.add(ptRptBean);

    // 
    ptRptBean = new PettyCashbookReportBean();
    ptRptBean.setGrpFlg(Boolean.FALSE);
    //ptRptBean.setDetailLine(Boolean.TRUE);
    ptRptBean.setDetailLine(Boolean.FALSE);
    pettyCashFlLst.add(ptRptBean);

    // 
    ptRptBean = new PettyCashbookReportBean();
    ptRptBean.setGrpFlg(Boolean.TRUE);
    ptRptBean.setDetailLine(Boolean.TRUE);
    pettyCashFlLst.add(ptRptBean);

    // ????
    SortedSet<String> grpItemSorted = new TreeSet<String>(grpItem.keySet());
    for (String key : grpItemSorted) {
        ptRptBean = new PettyCashbookReportBean();
        ptRptBean.setGrpItemCode(key.split(PDF_UUID)[0]);
        ptRptBean.setGrpItemName(SPACE_FULL.concat(key.split(PDF_UUID)[1]));
        ptRptBean.setGrpCash(grpItem.get(key));
        ptRptBean.setGrpFlg(Boolean.FALSE);
        ptRptBean.setDetailLine(Boolean.FALSE);
        pettyCashFlLst.add(ptRptBean);
    }

    JRDataSource JRdataSource = new JRBeanCollectionDataSource(pettyCashFlLst);

    // ?
    parameterMap.put("screenTitle", REPORT_TITLE);

    // 
    try {
        // ??????
        Locale.setDefault(new Locale("ja", "JP", "JP"));
        Date gregorianDate = new SimpleDateFormat("yyyy", Locale.ENGLISH).parse(pettyCashBookForm.getYear());
        SimpleDateFormat format = new SimpleDateFormat("GGGGyyyy");

        // 
        String tmpYearOriginal = format.format(gregorianDate);
        if (tmpYearOriginal.length() > 2) {
            parameterMap.put("year", tmpYearOriginal.substring(0, tmpYearOriginal.length() - 2));
            parameterMap.put("yearName", tmpYearOriginal.substring(tmpYearOriginal.length() - 2));
        } else {
            parameterMap.put("year", StringUtils.EMPTY);
            parameterMap.put("yearName", StringUtils.EMPTY);

            // 
            logger.warn("Original year {} is null or empty", tmpYearOriginal);
        }

    } catch (ParseException ex) {
        logger.warn("There is error happend when convert to Japanese's calendar format" + ex.getMessage());

        // Reset the locale
        Locale.setDefault(new Locale("en", "EN", "EN"));
    } catch (Exception ex) {
        logger.warn(ex.getMessage());

        // Reset the locale
        Locale.setDefault(new Locale("en", "EN", "EN"));
        return new JSONBean(Boolean.FALSE, -1, getSystemError());
    }

    // 
    parameterMap.put("month", pettyCashBookForm.getMonth());
    parameterMap.put("jRdataSource", JRdataSource);

    // 
    parameterMap.put("districtCode", pettyCashBook.getStrCode());
    // ??
    if (pettyCashBook.getStrNameR() != null && !StringUtils.isEmpty(pettyCashBook.getStrNameR())) {
        parameterMap.put("districtName",
                pettyCashBook.getStrNameR().length() > 10 ? pettyCashBook.getStrNameR().subSequence(0, 10)
                        : pettyCashBook.getStrNameR());
    } else {
        parameterMap.put("districtName", StringUtils.EMPTY);
    }

    // 
    parameterMap.put("shopCode", pettyCashBookForm.getShopCode());
    // ??
    parameterMap.put("shopName", pettyCashBookForm.getShopName());
    // ???
    String totalDefault = pettyCashBookForm.getTotalDefault();
    parameterMap.put("settingAmount",
            StringUtils.isNotEmpty(totalDefault) ? totalDefault.substring(1) : StringUtils.EMPTY);
    // 
    parameterMap.put("Atotal", pettyCashBookForm.getVerticalTotal());
    // 
    String balance = pettyCashBookForm.getBalance();
    parameterMap.put("Abalance", StringUtils.isNotEmpty(balance) ? balance.substring(1) : StringUtils.EMPTY);
    Locale.setDefault(new Locale("en", "EN", "EN"));

    OutputStream output = null;

    try {

        JasperDesign jasperDesign = JRXmlLoader.load(getClass().getResourceAsStream(TEMPLATE_PATH));
        JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameterMap, JRdataSource);

        reportToPdfFile = new File(
                jasperReportResolver.getReportPath() + File.separator + PDF_UUID + PDF_EXTENSION);
        if (logger.isDebugEnabled()) {
            logger.debug("Absolute path {}", reportToPdfFile.getAbsolutePath());
        }
        output = new FileOutputStream(reportToPdfFile);

        // PDF??
        JasperExportManager.exportReportToPdfStream(jasperPrint, output);
    } catch (JRException | IOException ex) {
        logger.error("PDF file doesn't exist", ex.getMessage());
        // PDF????????
        return new JSONBean(Boolean.FALSE, -1,
                "PDF????????");
    } finally {
        try {
            if (output != null) {
                output.close();
            }
        } catch (IOException ex) {
            logger.warn("?????", ex.getMessage());
            // ?????
            return new JSONBean(Boolean.FALSE, -1, "?????");
        }
    }

    String kindOfDevice = device.isTablet() ? DEVICE_TABLET : DEVICE_DESKTOP;
    // Successfully created PDF
    return new JSONBean(Boolean.TRUE, kindOfDevice, PDF_UUID);
}

From source file:org.ejbca.util.CertTools.java

private static String getUnescapedPlus(final String value) {
    final StringBuilder buf = new StringBuilder(value);
    int index = 0;
    int end = buf.length();
    while (index < end) {
        if (buf.charAt(index) == '\\' && index + 1 != end) {
            char c = buf.charAt(index + 1);
            if (c == '+') {
                buf.deleteCharAt(index);
                end--;/*from w w w  .  ja va2 s .  c o m*/
            }
        }
        index++;
    }
    return buf.toString();
}

From source file:org.ejbca.util.CertTools.java

/**
 *  Check if the String contains any unescaped '+'. RFC 2253, section 2.2
 *  states that '+' is used for multi-valued RelativeDistinguishedName. BC (version 1.45)
 *  currently does not support multi-valued RelativeDistinguishedName, and automatically
 *  escapes it instead. We want to detect unescaped '+' chars and warn that this might not
 *  be supported in the future if support for multi-valued RDNs is implemented.
 *//*from ww w.  j  av a  2  s .  c  o  m*/
private static void detectUnescapedPlus(String dn) {
    if (dn == null) {
        return;
    }
    final StringBuilder buf = new StringBuilder(dn);
    int index = 0;
    int end = buf.length();
    while (index < end) {
        if (buf.charAt(index) == '+') {
            // Found an unescaped '+' character.
            log.warn("DN \"" + dn
                    + "\" contains an unescaped '+'-character that will be automatically escaped. RFC 2253 reservs this "
                    + "for multi-valued RelativeDistinguishedNames. Encourage clients to use '\\+' instead, since future behaviour might change.");
        } else if (buf.charAt(index) == '\\') {
            // Found an escape character.
            index++;
        }
        index++;
    }
}

From source file:org.apache.fop.fonts.type1.PostscriptParser.java

/**
 * Parses the postscript document and returns a list of elements
 * @param segment The byte array containing the postscript data
 * @return A list of found Postscript elements
 * @throws IOException//from  w  w w  .  ja  v a 2s .c  o  m
 */
public List<PSElement> parse(byte[] segment) throws IOException {
    List<PSElement> parsedElements = new ArrayList<PSElement>();
    /* Currently only scan and store the top level element. For deeper
     * Postscript parsing you can push and pop elements from a stack */
    PSElement foundElement = null;
    String operator = null;
    StringBuilder token = new StringBuilder();
    List<String> tokens = new ArrayList<String>();
    int startPoint = -1;
    boolean specialDelimiter = false;
    boolean lastWasSpecial = false;
    for (int i = 0; i < segment.length; i++) {
        byte cur = segment[i];
        if (foundElement != null && foundElement.hasMore()) {
            foundElement.parse(cur, i);
            continue;
        } else {
            char c = (char) cur;
            if (!lastWasSpecial) {
                specialDelimiter = (c == '{' || c == '}' || c == '[' || c == ']'
                        || (!token.toString().equals("") && c == '/'));
                boolean isNotBreak = !(c == ' ' || c == '\r' || cur == 15 || cur == 12 || cur == 10);
                if (isNotBreak && !specialDelimiter) {
                    token.append(c);
                    continue;
                }
            } else {
                lastWasSpecial = false;
                token.append(c);
                if (token.toString().equals("/")) {
                    continue;
                }
            }
        }
        try {
            boolean setOp = false;
            if ((foundElement == null || !foundElement.hasMore()) && token.length() > 1
                    && token.charAt(0) == '/' && tokens.size() != 1 || hasEndToken(token.toString())) {
                operator = token.toString();
                setOp = true;
                if (tokens.size() > 2 && tokens.get(tokens.size() - 1).equals("def")) {
                    PSVariable newVar = new PSVariable(tokens.get(0), startPoint);
                    newVar.setValue(tokens.get(1));
                    newVar.setEndPoint(i - operator.length());
                    parsedElements.add(newVar);
                }
                tokens.clear();
                startPoint = i - token.length();
            }
            if (operator != null) {
                if (foundElement instanceof PSSubroutine) {
                    PSSubroutine sub = (PSSubroutine) foundElement;
                    subroutines.put(sub.getOperator(), sub);
                    parsedElements.add(sub);
                    if (!setOp) {
                        operator = "";
                    }
                } else {
                    if (foundElement != null) {
                        if (!hasMatch(foundElement.getOperator(), parsedElements)) {
                            parsedElements.add(foundElement);
                        } else {
                            LOG.warn("Duplicate " + foundElement.getOperator() + " in font file, Ignoring.");
                        }
                    }
                }
                //Compare token against patterns and create an element if matched
                foundElement = createElement(operator, token.toString(), startPoint);
            }
        } finally {
            tokens.add(token.toString());
            token = new StringBuilder();
            if (specialDelimiter) {
                specialDelimiter = false;
                lastWasSpecial = true;
                //Retrace special postscript character so it can be processed separately
                i--;
            }
        }
    }
    return parsedElements;
}

From source file:net.yacy.cora.language.phonetic.Metaphone.java

/**
 * Find the metaphone value of a String. This is similar to the
 * soundex algorithm, but better at finding similar sounding words.
 * All input is converted to upper case.
 * Limitations: Input format is expected to be a single ASCII word
 * with only characters in the A - Z range, no punctuation or numbers.
 *
 * @param txt String to find the metaphone code for
 * @return A metaphone code corresponding to the String supplied
 *///from ww w  . j  a v a2 s.  co  m
public String metaphone(String txt) {
    boolean hard = false;
    if ((txt == null) || (txt.isEmpty())) {
        return "";
    }
    // single character is itself
    if (txt.length() == 1) {
        return txt.toUpperCase(java.util.Locale.ENGLISH);
    }

    char[] inwd = txt.toUpperCase(java.util.Locale.ENGLISH).toCharArray();

    StringBuilder local = new StringBuilder(40); // manipulate
    StringBuilder code = new StringBuilder(10); //   output
    // handle initial 2 characters exceptions
    switch (inwd[0]) {
    case 'K':
    case 'G':
    case 'P': /* looking for KN, etc*/
        if (inwd[1] == 'N') {
            local.append(inwd, 1, inwd.length - 1);
        } else {
            local.append(inwd);
        }
        break;
    case 'A': /* looking for AE */
        if (inwd[1] == 'E') {
            local.append(inwd, 1, inwd.length - 1);
        } else {
            local.append(inwd);
        }
        break;
    case 'W': /* looking for WR or WH */
        if (inwd[1] == 'R') { // WR -> R
            local.append(inwd, 1, inwd.length - 1);
            break;
        }
        if (inwd[1] == 'H') {
            local.append(inwd, 1, inwd.length - 1);
            local.setCharAt(0, 'W'); // WH -> W
        } else {
            local.append(inwd);
        }
        break;
    case 'X': /* initial X becomes S */
        inwd[0] = 'S';
        local.append(inwd);
        break;
    default:
        local.append(inwd);
    } // now local has working string with initials fixed

    int wdsz = local.length();
    int n = 0;

    while ((code.length() < this.getMaxCodeLen()) && (n < wdsz)) { // max code size of 4 works well
        char symb = local.charAt(n);
        // remove duplicate letters except C
        if ((symb != 'C') && (isPreviousChar(local, n, symb))) {
            n++;
        } else { // not dup
            switch (symb) {
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U':
                if (n == 0) {
                    code.append(symb);
                }
                break; // only use vowel if leading char
            case 'B':
                if (isPreviousChar(local, n, 'M') && isLastChar(wdsz, n)) { // B is silent if word ends in MB
                    break;
                }
                code.append(symb);
                break;
            case 'C': // lots of C special cases
                /* discard if SCI, SCE or SCY */
                if (isPreviousChar(local, n, 'S') && !isLastChar(wdsz, n)
                        && (FRONTV.indexOf(local.charAt(n + 1)) >= 0)) {
                    break;
                }
                if (regionMatch(local, n, "CIA")) { // "CIA" -> X
                    code.append('X');
                    break;
                }
                if (!isLastChar(wdsz, n) && (FRONTV.indexOf(local.charAt(n + 1)) >= 0)) {
                    code.append('S');
                    break; // CI,CE,CY -> S
                }
                if (isPreviousChar(local, n, 'S') && isNextChar(local, n, 'H')) { // SCH->sk
                    code.append('K');
                    break;
                }
                if (isNextChar(local, n, 'H')) { // detect CH
                    if ((n == 0) && (wdsz >= 3) && isVowel(local, 2)) { // CH consonant -> K consonant
                        code.append('K');
                    } else {
                        code.append('X'); // CHvowel -> X
                    }
                } else {
                    code.append('K');
                }
                break;
            case 'D':
                if (!isLastChar(wdsz, n + 1) && isNextChar(local, n, 'G')
                        && (FRONTV.indexOf(local.charAt(n + 2)) >= 0)) { // DGE DGI DGY -> J 
                    code.append('J');
                    n += 2;
                } else {
                    code.append('T');
                }
                break;
            case 'G': // GH silent at end or before consonant
                if (isLastChar(wdsz, n + 1) && isNextChar(local, n, 'H')) {
                    break;
                }
                if (!isLastChar(wdsz, n + 1) && isNextChar(local, n, 'H') && !isVowel(local, n + 2)) {
                    break;
                }
                if ((n > 0) && (regionMatch(local, n, "GN") || regionMatch(local, n, "GNED"))) {
                    break; // silent G
                }
                if (isPreviousChar(local, n, 'G')) {
                    // NOTE: Given that duplicated chars are removed, I don't see how this can ever be true
                    hard = true;
                } else {
                    hard = false;
                }
                if (!isLastChar(wdsz, n) && (FRONTV.indexOf(local.charAt(n + 1)) >= 0) && (!hard)) {
                    code.append('J');
                } else {
                    code.append('K');
                }
                break;
            case 'H':
                if (isLastChar(wdsz, n)) {
                    break; // terminal H
                }
                if ((n > 0) && (VARSON.indexOf(local.charAt(n - 1)) >= 0)) {
                    break;
                }
                if (isVowel(local, n + 1)) {
                    code.append('H'); // Hvowel
                }
                break;
            case 'F':
            case 'J':
            case 'L':
            case 'M':
            case 'N':
            case 'R':
                code.append(symb);
                break;
            case 'K':
                if (n > 0) { // not initial
                    if (!isPreviousChar(local, n, 'C')) {
                        code.append(symb);
                    }
                } else {
                    code.append(symb); // initial K
                }
                break;
            case 'P':
                if (isNextChar(local, n, 'H')) {
                    // PH -> F
                    code.append('F');
                } else {
                    code.append(symb);
                }
                break;
            case 'Q':
                code.append('K');
                break;
            case 'S':
                if (regionMatch(local, n, "SH") || regionMatch(local, n, "SIO")
                        || regionMatch(local, n, "SIA")) {
                    code.append('X');
                } else {
                    code.append('S');
                }
                break;
            case 'T':
                if (regionMatch(local, n, "TIA") || regionMatch(local, n, "TIO")) {
                    code.append('X');
                    break;
                }
                if (regionMatch(local, n, "TCH")) {
                    // Silent if in "TCH"
                    break;
                }
                // substitute numeral 0 for TH (resembles theta after all)
                if (regionMatch(local, n, "TH")) {
                    code.append('0');
                } else {
                    code.append('T');
                }
                break;
            case 'V':
                code.append('F');
                break;
            case 'W':
            case 'Y': // silent if not followed by vowel
                if (!isLastChar(wdsz, n) && isVowel(local, n + 1)) {
                    code.append(symb);
                }
                break;
            case 'X':
                code.append('K');
                code.append('S');
                break;
            case 'Z':
                code.append('S');
                break;
            } // end switch
            n++;
        } // end else from symb != 'C'
        if (code.length() > this.getMaxCodeLen()) {
            code.setLength(this.getMaxCodeLen());
        }
    }
    return code.toString();
}

From source file:ca.mcgill.cs.swevo.qualyzer.editors.RTFDocumentProvider2.java

/**
 * Goes through the editor text and all the annotations to build the string that will be written to the disk.
 * Converts any special characters to their RTF tags as well.
 * //w  w w  .  j ava2s.  c om
 * @param contents
 * @param model
 * @return
 */
private StringBuilder buildRTFString(StringBuilder contents, IAnnotationModel model) {
    StringBuilder output = new StringBuilder(HEADER);
    ArrayList<Position> positions = new ArrayList<Position>();
    ArrayList<Annotation> annotations = new ArrayList<Annotation>();
    prepareAnnotationLists(model, positions, annotations);

    Position position = null;
    Annotation annotation = null;

    for (int i = 0; i < contents.length(); i++) {
        if (position == null) {
            for (int j = 0; j < positions.size(); j++) {
                if (positions.get(j).offset == i) {
                    position = positions.remove(j);
                    annotation = annotations.remove(j);
                    break;
                } else if (positions.get(j).offset > i) {
                    break;
                }
            }
            if (position != null) {
                output.append(getStartTagFromAnnotation(annotation));
            }
        }

        char c = contents.charAt(i);
        output.append(getMiddleChar(c));

        if (position != null && i == position.offset + position.length - 1) {
            output.append(getEndTagFromAnnotation(annotation));

            position = null;
            annotation = null;
        }

        output.append(getEndChar(c));
    }

    return output.append(FOOTER);
}