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:org.jbosson.plugins.amq.ArtemisMBeanDiscoveryComponent.java

protected static String formatMessage(String messageTemplate, Map<String, String> variableValues) {

    StringBuffer result = new StringBuffer();

    // collect keys and values to determine value size limit if needed
    final Map<String, String> replaceMap = new HashMap<String, String>();

    final Matcher matcher = PROPERTY_NAME_PATTERN.matcher(messageTemplate);
    int count = 0;
    while (matcher.find()) {
        final String key = matcher.group(1);
        final String value = variableValues.get(key);

        if (value != null) {
            replaceMap.put(key, value);/* w  ww  . ja  v a 2  s  . c om*/
            matcher.appendReplacement(result, Matcher.quoteReplacement(value));
        } else {
            matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group()));
        }

        count++;
    }
    matcher.appendTail(result);

    // check if the result exceeds MAX_LENGTH for formatted properties
    if (!replaceMap.isEmpty() && result.length() > MAX_LENGTH) {
        // sort values according to size
        final SortedSet<String> values = new TreeSet<String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        values.addAll(replaceMap.values());

        // find total value characters allowed
        int available = MAX_LENGTH - PROPERTY_NAME_PATTERN.matcher(messageTemplate).replaceAll("").length();

        // fit values from small to large in the allowed size to determine the maximum average
        int averageLength = available / count;
        for (String value : values) {
            final int length = value.length();
            if (length > averageLength) {
                break;
            }
            available -= length;
            count--;
            averageLength = available / count;
        }

        // replace values
        matcher.reset();
        result.delete(0, result.length());
        while (matcher.find()) {
            String value = replaceMap.get(matcher.group(1));
            if (value != null && value.length() > averageLength) {
                value = value.substring(0, averageLength);
            }
            matcher.appendReplacement(result, value != null ? value : matcher.group());
        }
        matcher.appendTail(result);
    }

    return result.toString();
}

From source file:org.wso2.msf4j.internal.router.TestMicroservice.java

@Path("/stream/upload")
@PUT/*w w w .  j a  va2s. c  o  m*/
public void streamUpload(@Context HttpStreamer httpStreamer) throws Exception {
    final StringBuffer sb = new StringBuffer();
    httpStreamer.callback(new HttpStreamHandler() {

        private org.wso2.msf4j.Response response;

        @Override
        public void init(org.wso2.msf4j.Response response) {

            this.response = response;
        }

        @Override
        public void chunk(ByteBuffer content) throws Exception {
            sb.append(Charset.defaultCharset().decode(content).toString());
        }

        @Override
        public void end() throws Exception {
            response.setStatus(Response.Status.OK.getStatusCode());
            response.setEntity(sb.toString());
            response.send();
        }

        @Override
        public void error(Throwable cause) {
            sb.delete(0, sb.length());
        }
    });
}

From source file:com.prasanna.android.stacknetwork.utils.MarkdownFormatter.java

/**
 * Format HTML text to fit into one or more vertically aligned text views.
 * Parses the given text and removes {@code <code> </code>} tags. If the code
 * text is of multiple lines a new {@link android.widget.TextView TextView} is
 * created and added to the view container else the code text is added to
 * already created {@link android.widget.TextView TextView}.
 * //  w w  w . ja v  a2s.com
 * @param context
 * @param markdownText
 * @return
 */
public static ArrayList<View> parse(Context context, String markdownText) {
    if (context != null && markdownText != null) {
        ArrayList<View> views = new ArrayList<View>();
        try {
            markdownText = clean(markdownText);

            XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = xmlPullParserFactory.newPullParser();
            xmlPullParser.setInput(new StringReader(markdownText));
            int eventType = xmlPullParser.getEventType();
            StringBuffer buffer = new StringBuffer();
            StringBuffer code = new StringBuffer();

            boolean codeFound = false;
            boolean oneLineCode = false;

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_DOCUMENT) {
                } else if (eventType == XmlPullParser.START_TAG) {
                    if (xmlPullParser.getName().equals(Tags.CODE))
                        codeFound = true;
                    else if (xmlPullParser.getName().equals(Tags.IMG)) {
                        addSimpleTextToView(context, views, buffer, params);

                        String attributeValue = xmlPullParser.getAttributeValue(null, Attributes.SRC);
                        addImgLinkText(context, views, attributeValue, params);
                    } else {
                        buffer.append("<" + xmlPullParser.getName());
                        for (int i = 0; i < xmlPullParser.getAttributeCount(); i++) {
                            buffer.append(" " + xmlPullParser.getAttributeName(i) + "=\""
                                    + xmlPullParser.getAttributeValue(i) + "\"");
                        }

                        buffer.append(">");
                    }
                } else if (eventType == XmlPullParser.END_TAG) {
                    if (xmlPullParser.getName().equals(Tags.CODE)) {
                        codeFound = false;

                        if (oneLineCode)
                            oneLineCode = false;
                        else {
                            addSimpleTextToView(context, views, buffer, params);
                            views.add(getTextViewForCode(context, code.toString()));
                            code.delete(0, code.length());
                        }
                    } else if (xmlPullParser.getName().equals(Tags.IMG)) {
                        LogWrapper.v(TAG, "Ignore img tag");
                    } else {
                        buffer.append("</" + xmlPullParser.getName() + ">");
                    }
                } else if (eventType == XmlPullParser.TEXT) {
                    String text = xmlPullParser.getText();

                    if (codeFound) {
                        if (!text.contains(NEW_LINE)) {
                            if (buffer.length() > 0 && buffer.lastIndexOf(NEW_LINE) == buffer.length() - 1)
                                buffer.setCharAt(buffer.length() - 1, ' ');

                            buffer.append(text);
                            oneLineCode = true;
                        } else {
                            code.append(text);
                        }
                    } else {
                        text = text.replace(NEW_LINE, " ").replace(CR, " ");
                        buffer.append(text);
                    }
                }

                eventType = xmlPullParser.next();
            }

            addSimpleTextToView(context, views, buffer, params);
        } catch (XmlPullParserException e) {
            LogWrapper.e(TAG, "Error parsing: " + e);
        } catch (IOException e) {
            LogWrapper.e(TAG, "Error parsing: " + e);
        }
        return views;
    }
    return null;

}

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

/**
 * Transcodes %XX symbols per RFC 2369 to normalized character format - adapted from apache commons
 * /* w  ww.  j a  va 2s  .  co m*/
 * @param buffer
 *            The stringBuffer object containing the request data
 * @param offset
 *            How far into the string buffer we should start processing from
 * @param length
 *            Number of chars in the buffer
 * @throws ServletException
 */
private void decode(final StringBuffer buffer, final int offset, final int length) throws ServletException {
    int index = offset;
    int count = length;
    int dig1, dig2;
    while (count > 0) {
        final char ch = buffer.charAt(index);
        if (ch != '%') {
            count--;
            index++;
            continue;
        }
        if (count < 3) {
            throw new ServletException(
                    Messages.getString("SPEPFilter.10") + buffer.substring(index, index + count)); //$NON-NLS-1$
        }

        dig1 = Character.digit(buffer.charAt(index + 1), 16);
        dig2 = Character.digit(buffer.charAt(index + 2), 16);
        if (dig1 == -1 || dig2 == -1) {
            throw new ServletException(
                    Messages.getString("SPEPFilter.11") + buffer.substring(index, index + count)); //$NON-NLS-1$
        }
        char value = (char) (dig1 << 4 | dig2);

        buffer.setCharAt(index, value);
        buffer.delete(index + 1, index + 3);
        count -= 3;
        index++;
    }
}

From source file:dao.PersonalinfoDaoDb.java

/**
 * Given a login return the updated personal info page.
 * @param member/*ww w.  j a  va  2  s. c o  m*/
 * @param dob
 * @param title
 * @param ihave
 * @param iwant
 * @param industry
 * @param company
 * @param pwebsite
 * @param cwebsite
 * @param blogsite
 * @param education
 * @param city
 * @param state
 * @param country
 * @param description
 * @param interests
 * @param zipcode
 * @param pm
 * @param bb
 * @param fd
 * @param mykeywords
 * @param yourkeywords
 * @param fname
 * @param lname
 * @param mname
 * @param email
 * @param gender
 * @param nickname
 * @param designation
 * @param bcity
 * @param bstate
 * @param bcountry
 * @param bzipcode
 * @param hphone
 * @param cphone
 * @param bphone
 * @param blobStreamLabel 
 * @param docLabel - the documents label
 * @param password - password
 * @param street - street
 * @param bstreet - busstreet
 * @param zone - zone
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public void updatePersonalinfo(String member, String dob, String title, String ihave, String iwant,
        String industry, String company, String pwebsite, String cwebsite, String blogsite, String education,
        String city, String state, String country, String description, String interests, String zipcode, int pm,
        int bb, int fd, String mykeywords, String yourkeywords, String fname, String lname, String mname,
        String email, int gender, String nickname, String designation, String bcity, String bstate,
        String bcountry, String bzipcode, String hphone, String cphone, String bphone, String yim, String aim,
        String msn, String icq, String blobStreamLabel, String docLabel, String password, String street,
        String bstreet, String zone, String contact) throws BaseDaoException {

    Hdlogin hdlogin = getLoginid(member);
    if (hdlogin == null) {
        throw new BaseDaoException("hdlogin is null for member " + member);
    }

    String memberId = hdlogin.getValue(DbConstants.LOGIN_ID);
    if (RegexStrUtil.isNull(memberId)) {
        throw new BaseDaoException("memberId is null for member " + member);
    }

    Object[] params = { (Object) memberId };

    boolean myUsertabExists, myHdprofileExists, myKeywordsExists, yourKeywordExists;
    myUsertabExists = myHdprofileExists = myKeywordsExists = yourKeywordExists = false;

    myUsertabExists = doesMyUserTabExist(params);
    myHdprofileExists = doesMyHdprofileExist(params);
    myKeywordsExists = doesMyKeywordExist(params);
    yourKeywordExists = doesYourKeywordExist(params);

    /**
     *  Get scalability datasource for usertab/hdprofile/mykeywords/yourkeywords - not partitioned
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, updatePersonalInfo() " + sourceName);
    }

    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);

        /**
         *  hdlogin is not partitioned 
         */
        updateHdloginQuery.run(conn, memberId, fname, lname, mname, email, password, contact);

        // no entry? add entry 
        if (!myUsertabExists) {
            String[] myparams = new String[35];
            myparams[0] = dob;
            myparams[1] = title;
            myparams[2] = ihave;
            myparams[3] = iwant;
            myparams[4] = industry;
            myparams[5] = company;
            myparams[6] = pwebsite;
            myparams[7] = cwebsite;
            myparams[8] = blogsite;
            myparams[9] = education;
            myparams[10] = city;
            myparams[11] = state;
            myparams[12] = country;
            myparams[13] = description;
            myparams[14] = interests;
            myparams[15] = zipcode;
            myparams[16] = new Integer(gender).toString();
            myparams[17] = nickname;
            myparams[18] = designation;
            myparams[19] = bcity;
            myparams[20] = bstate;
            myparams[21] = bcountry;
            myparams[22] = bzipcode;
            myparams[23] = hphone;
            myparams[24] = cphone;
            myparams[25] = bphone;
            myparams[26] = yim;
            myparams[27] = aim;
            myparams[28] = msn;
            myparams[29] = icq;
            // memberid is the LAST_INSERT_ID
            myparams[30] = blobStreamLabel;
            myparams[31] = docLabel;
            myparams[32] = street;
            myparams[33] = bstreet;
            myparams[34] = zone;

            String queryName = scalabilityManager.getWriteZeroScalability("personalinfoaddquery");
            addUserQuery = getQueryMapper().getCommonQuery(queryName);
            addUserQuery.run(conn, myparams);
            //addUserQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite, education, city, state, country, description, interests, zipcode, gender, nickname, designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone,  yim, aim, msn,icq, memberId, blobStreamLabel, docLabel);
        } else {
            // exists! update entry
            updateQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite,
                    education, city, state, country, description, interests, zipcode, gender, nickname,
                    designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq,
                    memberId, blobStreamLabel, docLabel, street, bstreet, zone);
        }

        /**
         *  hdprofile - not partitioned
              *  no entry? add entry
           addUserQuery.run(conn, params);
           //addUserQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite, education, city, state, country, description, interests, zipcode, gender, nickname, designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone,  yim, aim, msn,icq, memberId, blobStreamLabel, docLabel);
             } else {
                // exists! update entry
           updateQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite, education, city, state, country, description, interests, zipcode, gender, nickname, designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq, memberId, blobStreamLabel, docLabel);
             }
                
        /**
         *  hdprofile - not partitioned
              *  no entry? add entry
         */
        if (!myHdprofileExists) {
            String pmStr = new Integer(pm).toString();
            String bbStr = new Integer(bb).toString();
            String fdStr = new Integer(fd).toString();
            String profileParams[] = { pmStr, bbStr, fdStr, memberId };

            String queryName = scalabilityManager.getWriteZeroScalability("addpreferencesquery");
            addPreferencesQuery = getQueryMapper().getCommonQuery(queryName);
            addPreferencesQuery.run(conn, profileParams);
        } else {
            /**
            *  add entry in hdprofile - not partitioned
             **/
            profileUpdateQuery.run(conn, pm, bb, fd, memberId);
        }

        /**
         *  mykeywords - not partitioned
         *  Add mykeywords
              *  exists! zap keywords
         */
        if (myKeywordsExists) {
            myKeywordsDeleteQuery.run(conn, memberId);
        }
        if (!RegexStrUtil.isNull(mykeywords)) {
            String[] mykeys = mykeywords.split(",");
            for (int i = 0; i < mykeys.length; i++) {
                myKeywordsAddQuery.run(conn, mykeys[i], memberId);
            }
        }

        /**
         *  Add yourkeywords
         *  yourkeywords - not partitioned
         */
        if (yourKeywordExists) {
            yourKeywordsDeleteQuery.run(conn, memberId);
        }
        if (!RegexStrUtil.isNull(yourkeywords)) {
            String[] yourkeys = yourkeywords.split(",");
            for (int i = 0; i < yourkeys.length; i++) {
                yourKeywordsAddQuery.run(conn, yourkeys[i], memberId);
            }
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "connection close exception for preferences/deleting/adding keywords", e2);
            }
            throw new BaseDaoException(
                    "error occured while rollingback entries updateing preferences/deleting/adding mykeywords/your keywords ",
                    e1);
        }
        throw new BaseDaoException(
                "error occured while updating preferences/deleting/adding mykeywords/yourkeywords", e);
    }

    // committing transaction
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("commit exception for preferences/deleting/adding keywords", e3);
    }
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("connection close exception", e1);
        }

        throw new BaseDaoException("connection close exception for preferences/deleting/adding keywords", e4);
    }

    // currently not used as it always updates it
    Fqn fqn = cacheUtil.fqn(DbConstants.ID_INFO);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.LOGIN_INFO);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHORS_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    Object dirs = null;
    fqn = cacheUtil.fqn(DbConstants.AUTHORS_DIRECTORIES);
    if (treeCache.exists(fqn, member)) {
        dirs = treeCache.get(fqn, member);
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHOR_BLOCKED_DIRS);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_COPY);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_MOVE);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    StringBuffer sb = new StringBuffer();
    if (dirs != null) {
        for (int i = 0; i < ((List) dirs).size(); i++) {
            String directoryId = ((Directory) ((List) dirs).get(i)).getValue(DbConstants.DIRECTORY_ID);
            sb.delete(0, sb.length());
            sb.append(directoryId);
            sb.append("-");
            sb.append(memberId);
            String key = sb.toString();
            fqn = cacheUtil.fqn(DbConstants.DIR_AUTHOR);
            if (treeCache.exists(fqn, key)) {
                treeCache.remove(fqn, key);
            }

            fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
            if (treeCache.exists(fqn, directoryId)) {
                treeCache.remove(fqn, directoryId);
            }
        }
    }
    /*
    fqn = cacheUtil.fqn(DbConstants.COLLABRUM_LIST);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }
    */

    // delete collabrum related cache
    Object collabrums = null;
    fqn = cacheUtil.fqn(DbConstants.MEM_AS_ORGANIZER_LIST);
    if (treeCache.exists(fqn, member)) {
        collabrums = treeCache.get(fqn, member);
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.MEM_AS_MODERATOR_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.BLOCKED_COLLABRUM_LIST);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    /** get authors related collabrums */
    if (collabrums != null) {
        for (int i = 0; i < ((List) collabrums).size(); i++) {
            String collabrumId = ((Collabrum) ((List) collabrums).get(i)).getValue(DbConstants.COLLABRUM_ID);

            /*
                       fqn = cacheUtil.fqn(DbConstants.COLLABRUM_EDIT);
                       if (treeCache.exists(fqn, collabrumId)) {
                           treeCache.remove(fqn, collabrumId);
                       } 
            */

            fqn = cacheUtil.fqn(DbConstants.COLLABRUM);
            if (treeCache.exists(fqn, collabrumId)) {
                treeCache.remove(fqn, collabrumId);
            }

            fqn = cacheUtil.fqn(DbConstants.ORGANIZERS);
            if (treeCache.exists(fqn, collabrumId)) {
                treeCache.remove(fqn, collabrumId);
            }

            sb.delete(0, sb.length());
            sb.append(collabrumId);
            sb.append("-");
            sb.append(memberId);
            fqn = cacheUtil.fqn(DbConstants.ORGANIZER);
            if (treeCache.exists(fqn, sb.toString())) {
                treeCache.remove(fqn, sb.toString());
            }
        }
    }
}

From source file:com.espertech.esperio.csv.CSVReader.java

private String matchUnquotedValue() throws IOException {
    boolean doConsume = false;
    StringBuffer value = new StringBuffer();
    int trailingSpaces = 0;

    while (true) {
        // Break on newline or comma without consuming
        if (atNewline(doConsume) || atEOF(doConsume) || atComma(doConsume)) {
            break;
        }//from w  w  w  . j a  v a 2s.c o m

        // Unquoted values cannot contain quotes
        if (atChar('"', doConsume)) {
            if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) {
                log.debug(".matchUnquotedValue matched unexpected double-quote while matching " + value);
                log.debug(".matchUnquotedValue values==" + values);
            }
            throw unexpectedCharacterException('"');
        }

        char currentChar = (char) source.read();

        // Update the count of trailing spaces
        trailingSpaces = (isWhiteSpace(currentChar)) ? trailingSpaces + 1 : 0;

        value.append(currentChar);
    }

    // Remove the trailing spaces
    int end = value.length();
    value.delete(end - trailingSpaces, end);

    // An empty string means that this value was just whitespace,
    // so nothing was matched
    return value.length() == 0 ? null : value.toString();
}

From source file:dao.CollModeratorDaoDb.java

/**
 * This deletes the member from the collabrum organizers/moderators list 
 * @param idList collabrum ids list /*from  w ww  .j  a v a 2s .  c  om*/
 * @param member member who is to be deleted. 
 * @param userId administrator of collabrum
 * @param userLogin administrator's login of collabrum
 * @param isAdmin true if this user is the administrator
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public void deleteModerator(ArrayList idList, String member, String userId, String userLogin, boolean isAdmin)
        throws BaseDaoException {

    if ((idList == null) || RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(member)
            || RegexStrUtil.isNull(userLogin)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  check if the userLogin is diaryAdmin or userId an organizer for each of the collabrum's
     */
    if (!isAdmin) {
        for (int i = 0; i < idList.size(); i++) {
            if (!isOrganizer((String) idList.get(i), userLogin, userId)) {
                throw new BaseDaoException("User does not have permission to deleteModerators(), "
                        + idList.get(i) + " userId = " + userId);
            }
        }
    }

    /**
     *  get the member id
     */
    Hdlogin hdlogin = getLoginid(member);
    String memberId = hdlogin.getValue(DbConstants.LOGIN_ID);
    if (RegexStrUtil.isNull(memberId)) {
        throw new BaseDaoException("memberId is null");
    }

    /**
     *  Get scalability datasource for collabrum, colladmin (not partitioned)
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, in deleteModerators() " + sourceName + " userId = " + userId);
    }

    /**
     * Delete the moderator from colladmin
     */
    Connection conn = null;
    try {
        conn = ds.getConnection();
        for (int i = 0; i < idList.size(); i++) {
            deleteModeratorQuery.run(conn, (String) idList.get(i), memberId);
        }
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("conn.close() error, deleteModerator, " + memberId, e1);
        }
        throw new BaseDaoException("error occured while deleteModertor, " + memberId, e);
    }
    try {
        if (conn != null) {
            conn.close();
        }
    } catch (Exception e1) {
        throw new BaseDaoException("conn.close() error, deleteModerator, " + memberId, e1);
    }

    Fqn fqn = cacheUtil.fqn(DbConstants.MEM_AS_MODERATOR_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.MEM_AS_ORGANIZER_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    /**
     * remove this from the userlogin also
     */
    fqn = cacheUtil.fqn(DbConstants.MEM_AS_MODERATOR_LIST);
    if (treeCache.exists(fqn, userLogin)) {
        treeCache.remove(fqn, userLogin);
    }

    StringBuffer sb = new StringBuffer();
    String key = null;
    for (int i = 0; i < idList.size(); i++) {
        sb.append(idList.get(i));
        sb.append("-");
        sb.append(memberId);
        key = sb.toString();
        fqn = cacheUtil.fqn(DbConstants.ORGANIZER);
        if (treeCache.exists(fqn, key)) {
            treeCache.remove(fqn, key);
        }
        fqn = cacheUtil.fqn(DbConstants.IS_ORGANIZER);
        if (treeCache.exists(fqn, key)) {
            treeCache.remove(fqn, key);
        }
        sb.delete(0, sb.length());

        fqn = cacheUtil.fqn(DbConstants.COLLABRUM);
        if (treeCache.exists(fqn, idList.get(i))) {
            treeCache.remove(fqn, idList.get(i));
        }
    }

    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.BLOCKED_COLLABRUM_LIST);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }
}

From source file:gate.creole.tokeniser.SimpleTokeniser.java

/**
 * Initialises this tokeniser by reading the rules from an external source (provided through an URL) and building
 * the finite state machine at the core of the tokeniser.
 *
 * @exception ResourceInstantiationException
 *//*from   w ww .  j a  va 2  s.c om*/
@Override
public Resource init() throws ResourceInstantiationException {
    BufferedReader bRulesReader = null;
    try {
        if (rulesURL != null) {
            bRulesReader = new BufferedReader(
                    new BomStrippingInputStreamReader(rulesURL.openStream(), encoding));
        } else {
            //no init data, Scream!
            throw new ResourceInstantiationException("No URL provided for the rules!");
        }
        initialState = new FSMState(this);
        String line = bRulesReader.readLine();
        ///String toParse = "";
        StringBuffer toParse = new StringBuffer(Gate.STRINGBUFFER_SIZE);

        while (line != null) {
            if (line.endsWith("\\")) {
                ///toParse += line.substring(0,line.length()-1);
                toParse.append(line.substring(0, line.length() - 1));
            } else {
                /*toParse += line;
                parseRule(toParse);
                toParse = "";
                */
                toParse.append(line);
                parseRule(toParse.toString());
                toParse.delete(0, toParse.length());
            }
            line = bRulesReader.readLine();
        }
        eliminateVoidTransitions();
    } catch (java.io.IOException ioe) {
        throw new ResourceInstantiationException(ioe);
    } catch (TokeniserException te) {
        throw new ResourceInstantiationException(te);
    } finally {
        IOUtils.closeQuietly(bRulesReader);
    }
    return this;
}

From source file:de.marcelkapfer.morseconverter.MainActivity.java

public void mll(View view) {
    EditText editText = (EditText) findViewById(R.id.edit_message);
    StringBuffer message = new StringBuffer(editText.getText());
    if (message.toString().endsWith(" ")) {
        message = message.deleteCharAt(message.length() - 1);
    }//from www.  j a v a 2  s.co  m
    String input;
    StringBuffer output = new StringBuffer();
    input = message.toString().toUpperCase() + "#";
    StringBuffer inputToSign = new StringBuffer(input);
    while (!message.toString().equals("   ")) {
        int d = 0;
        boolean signFull = true;
        StringBuffer sign = new StringBuffer();
        while (signFull) {
            if (inputToSign.toString().startsWith("       ")) {
                output.append(" ");
                inputToSign.delete(d, d + 9);
            } else if (inputToSign.toString().substring(d, d + 3).equals("   ")) {
                if (d == 0) {
                    inputToSign.delete(0, 3);
                } else {
                    sign.replace(0, sign.length(), inputToSign.toString().substring(0, d));
                    inputToSign.delete(0, d);
                    signFull = false;
                }
            } else {
                d++;
            }
        }
        if (sign.toString().equals(".-")) {
            output.append("A");
        } else if (sign.toString().equals("-...")) {
            output.append("B");
        } else if (sign.toString().equals("-.-.")) {
            output.append("C");
        } else if (sign.toString().equals("-..")) {
            output.append("D");
        } else if (sign.toString().equals(".")) {
            output.append("E");
        } else if (sign.toString().equals("..-.")) {
            output.append("F");
        } else if (sign.toString().equals("--.")) {
            output.append("G");
        } else if (sign.toString().equals("....")) {
            output.append("H");
        } else if (sign.toString().equals("..")) {
            output.append("I");
        } else if (sign.toString().equals(".---")) {
            output.append("J");
        } else if (sign.toString().equals("-.-")) {
            output.append("K");
        } else if (sign.toString().equals(".-..")) {
            output.append("L");
        } else if (sign.toString().equals("--")) {
            output.append("M");
        } else if (sign.toString().equals("-.")) {
            output.append("N");
        } else if (sign.toString().equals("---")) {
            output.append("O");
        } else if (sign.toString().equals(".--.")) {
            output.append("P");
        } else if (sign.toString().equals("--.-")) {
            output.append("Q");
        } else if (sign.toString().equals(".-.")) {
            output.append("R");
        } else if (sign.toString().equals("...")) {
            output.append("S");
        } else if (sign.toString().equals("-")) {
            output.append("T");
        } else if (sign.toString().equals("..-")) {
            output.append("U");
        } else if (sign.toString().equals("...-")) {
            output.append("V");
        } else if (sign.toString().equals(".--")) {
            output.append("W");
        } else if (sign.toString().equals("-..-")) {
            output.append("X");
        } else if (sign.toString().equals("-.--")) {
            output.append("Y");
        } else if (sign.toString().equals("--..")) {
            output.append("Z");
        } else if (sign.toString().equals("-----")) {
            output.append(". (zero)");
        } else if (sign.toString().equals(".----")) {
            output.append("-");
        } else if (sign.toString().equals("..---")) {
            output.append("2");
        } else if (sign.toString().equals("...--")) {
            output.append("3");
        } else if (sign.toString().equals("....-")) {
            output.append("4");
        } else if (sign.toString().equals(".....")) {
            output.append("5");
        } else if (sign.toString().equals("-....")) {
            output.append("6");
        } else if (sign.toString().equals("--...")) {
            output.append("7");
        } else if (sign.toString().equals("---..")) {
            output.append("8");
        } else if (sign.toString().equals("----.")) {
            output.append("9");
        } else if (sign.toString().equals(".-.-")) {
            output.append("");
        } else if (sign.toString().equals("---.")) {
            output.append("");
        } else if (sign.toString().equals("..--")) {
            output.append("");
        } else if (sign.toString().equals("...--...")) {
            output.append("");
        } else if (sign.toString().equals("----")) {
            output.append("CH");
        } else if (sign.toString().equals(".-.-.-")) {
            output.append(".");
        } else if (sign.toString().equals("--..--")) {
            output.append(",");
        } else if (sign.toString().equals("---...")) {
            output.append(":");
        } else if (sign.toString().equals("-.-.-.")) {
            output.append(";");
        } else if (sign.toString().equals("..--..")) {
            output.append("?");
        } else if (sign.toString().equals("-.-.--")) {
            output.append("!");
        } else if (sign.toString().equals("-....-")) {
            output.append("-");
        } else if (sign.toString().equals("..--.-")) {
            output.append("_");
        } else if (sign.toString().equals("-.--.")) {
            output.append("(");
        } else if (sign.toString().equals("-.--.-")) {
            output.append(")");
        } else if (sign.toString().equals(".----.")) {
            output.append("'");
        } else if (sign.toString().equals("-...-")) {
            output.append("=");
        } else if (sign.toString().equals(".-.-.")) {
            output.append("+ or End of the signal");
        } else if (sign.toString().equals("-..-.")) {
            output.append("/");
        } else if (sign.toString().equals(".--.-.")) {
            output.append("@");
        } else if (sign.toString().equals("-.-.-")) {
            output.append("Begin of the signal");
        } else if (sign.toString().equals("-...-")) {
            output.append("Wait");
        } else if (sign.toString().equals("...-.")) {
            output.append("Understood");
        } else if (sign.toString().equals("...-.-")) {
            output.append("End of work");
        } else if (sign.toString().equals("...---...")) {
            output.append("SOS");
        } else if (sign.toString().equals("........")) {
            output.append("Error");
        } else {
            tfOutput = "Code not listed or wrong.";
        }
    }
    tfOutput = output.toString();
    lastFragment = 1;
    After(view);
}

From source file:com.chalmers.schmaps.CheckInActivity.java

/*******************************************************************
 * Method parses through in parameter jsonObject and creates an array of geopoints
 * each geopoint representing an checked-in person
 * @param jsonObject/*from  w  w  w.  ja v a2 s. c o m*/
 * @return arraylist of geopoints
 **********************************************************************/
public void parseJsonAndDraw(JSONObject jsonObject) {
    //greates an geopoint with our location
    OverlayItem overlayitem;
    GeoPoint geopoint;
    int lat, lng;
    String name, time;
    StringBuffer timebuffer = new StringBuffer();
    List<Overlay> overlayList;
    MapItemizedOverlay mapItemizedCheckIn;
    Drawable checkInDot;

    overlayList = mapview.getOverlays();
    //drawable
    checkInDot = this.getResources().getDrawable(R.drawable.chalmersandroid);
    //mapitemizedoverlay with drawable
    mapItemizedCheckIn = new MapItemizedOverlay(checkInDot, this);

    result = null;

    try {
        result = jsonObject.getJSONArray("result");
        JSONObject checkedInPerson;

        //loop through the jsonarray and extract all checked-in points
        //collect data, create geopoint and add to list of overlays that will be drawn on map
        for (int count = 0; count < result.length(); count++) {
            checkedInPerson = result.getJSONObject(count);
            //extract time
            time = checkedInPerson.getString("time");
            //insert in stringbuffer
            timebuffer.insert(0, time);
            //delete seconds
            timebuffer.delete(VALUEOFSECONDS, timebuffer.length());
            //delete date
            timebuffer.delete(0, VALUEOFDATE);
            //convert back to string
            time = timebuffer.toString();
            //clear buffer
            timebuffer.delete(0, timebuffer.length());
            name = checkedInPerson.getString("name");
            lat = (int) checkedInPerson.getInt("lat");
            lng = (int) checkedInPerson.getInt("lng");
            geopoint = new GeoPoint(lat, lng);
            overlayitem = new OverlayItem(geopoint, name, "Checked in at " + time);
            mapItemizedCheckIn.addOverlay(overlayitem);
            overlayList.add(mapItemizedCheckIn);
        }
    } catch (JSONException e) {
    }

    mapview.postInvalidate();
}