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:com.vmware.bdd.cli.rest.RestClient.java

private String buildQueryStrings(Map<String, String> queryStrings) {
    StringBuilder stringBuilder = new StringBuilder("?");

    Set<Entry<String, String>> entryset = queryStrings.entrySet();
    for (Entry<String, String> entry : entryset) {
        stringBuilder.append(entry.getKey() + "=" + entry.getValue() + "&");
    }/* w ww .java 2  s.c o  m*/
    int length = stringBuilder.length();
    if (stringBuilder.charAt(length - 1) == '&') {
        return stringBuilder.substring(0, length - 1);
    } else {
        return stringBuilder.toString();
    }
}

From source file:Gpw.java

public static String generate(int pwl) {
    int c1, c2, c3;
    long sum = 0;
    int nchar;/*from w ww.  ja  v  a2s  . c  o m*/
    long ranno;
    double pik;
    StringBuilder password;
    Random ran = new Random(); // new random source seeded by clock

    password = new StringBuilder(pwl);
    pik = ran.nextDouble(); // random number [0,1]
    ranno = (long) (pik * data.getSigma()); // weight by sum of frequencies
    sum = 0;
    for (c1 = 0; c1 < 26; c1++) {
        for (c2 = 0; c2 < 26; c2++) {
            for (c3 = 0; c3 < 26; c3++) {
                sum += data.get(c1, c2, c3);
                if (sum > ranno) {
                    password.append(alphabet.charAt(c1));
                    password.append(alphabet.charAt(c2));
                    password.append(alphabet.charAt(c3));
                    c1 = 26; // Found start. Break all 3 loops.
                    c2 = 26;
                    c3 = 26;
                } // if sum
            } // for c3
        } // for c2
    } // for c1

    // Now do a random walk.
    nchar = 3;
    while (nchar < pwl) {
        c1 = alphabet.indexOf(password.charAt(nchar - 2));
        c2 = alphabet.indexOf(password.charAt(nchar - 1));
        sum = 0;
        for (c3 = 0; c3 < 26; c3++)
            sum += data.get(c1, c2, c3);
        if (sum == 0) {
            break; // exit while loop
        }
        pik = ran.nextDouble();
        ranno = (long) (pik * sum);
        sum = 0;
        for (c3 = 0; c3 < 26; c3++) {
            sum += data.get(c1, c2, c3);
            if (sum > ranno) {
                password.append(alphabet.charAt(c3));
                c3 = 26; // break for loop
            } // if sum
        } // for c3
        nchar++;
    } // while nchar
    return password.toString();
}

From source file:com.btisystems.pronx.ems.AbstractMibCompiler.java

/**
 * Capitalise first character of the specified name.
 *
 * @param name the name/*from   w  ww.j  a  va  2  s . co m*/
 * @return the string
 */
protected final String capitalizeFirstCharacter(final String name) {
    final StringBuilder sb = new StringBuilder(name);
    final char firstChar = sb.charAt(0);
    sb.setCharAt(0, Character.toUpperCase(firstChar));
    return sb.toString();
}

From source file:cn.webwheel.DefaultMain.java

/**
 * Wrap exception to a json object and return it to client.
 * <p>/*from ww  w.  j a va2  s.c o m*/
 * <b>json object format:</b><br/>
 * <p><blockquote><pre>
 *     {
 *         "msg": "the exception's message",
 *         "stackTrace":[
 *             "exception's stack trace1",
 *             "exception's stack trace2",
 *             "exception's stack trace3",
 *             ....
 *         ]
 *     }
 * </pre></blockquote></p>
 */
public Object executeActionError(WebContext ctx, ActionInfo ai, Object action, Throwable e) throws Throwable {
    if (e instanceof LogicException) {
        return ((LogicException) e).getResult();
    }
    Logger.getLogger(DefaultMain.class.getName()).log(Level.SEVERE, "action execution error", e);
    StringBuilder sb = new StringBuilder();
    sb.append("{\n");
    String s;
    try {
        s = JsonResult.objectMapper.writeValueAsString(e.toString());
    } catch (IOException e1) {
        s = "\"" + e.toString().replace("\"", "'") + "\"";
    }
    sb.append("    \"msg\" : " + s + ",\n");
    sb.append("    \"stackTrace\" : [");
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String[] ss = sw.toString().split("\r\n");
    for (int i = 1; i < ss.length; i++) {
        if (sb.charAt(sb.length() - 1) != '[') {
            sb.append(',');
        }
        sb.append("\n        ").append(JsonResult.objectMapper.writeValueAsString(ss[i]));
    }
    sb.append("\n    ]\n");
    sb.append("}");
    HttpServletResponse response = ctx.getResponse();
    if (JsonResult.defWrapMultipart && ServletFileUpload.isMultipartContent(ctx.getRequest())
            && !"XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))) {
        response.setContentType("text/html");
        sb.insert(0, "<textarea>\n");
        sb.append("\n</textarea>");
    } else {
        response.setContentType("application/json");
    }
    response.setCharacterEncoding("utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().write(sb.toString());
    return EmptyResult.inst;
}

From source file:github.madmarty.madsonic.util.Util.java

public static String getRestUrl(Context context, String method, SharedPreferences prefs, int instance) {
    StringBuilder builder = new StringBuilder();

    String serverUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_URL + instance, null);
    String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
    String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);

    // Slightly obfuscate password
    password = "enc:" + Util.utf8HexEncode(password);

    builder.append(serverUrl);//w w  w .jav  a  2s .  c  o  m
    if (builder.charAt(builder.length() - 1) != '/') {
        builder.append("/");
    }
    builder.append("rest/").append(method).append(".view");
    builder.append("?u=").append(username);
    builder.append("&p=").append(password);
    builder.append("&v=").append(Constants.REST_PROTOCOL_VERSION);
    builder.append("&c=").append(Constants.REST_CLIENT_ID);

    return builder.toString();
}

From source file:net.sf.jabref.importer.fileformat.BibtexParser.java

/**
 * returns a new <code>StringBuilder</code> which corresponds to <code>toRemove</code> without whitespaces
 *
 * @param toRemove/*from w  ww.ja  v  a 2 s .c om*/
 * @return
 */
private StringBuilder removeWhitespaces(StringBuilder toRemove) {
    StringBuilder result = new StringBuilder();
    char current;
    for (int i = 0; i < toRemove.length(); ++i) {
        current = toRemove.charAt(i);
        if (!Character.isWhitespace(current)) {
            result.append(current);
        }
    }
    return result;
}

From source file:org.apache.olingo.client.core.uri.URIBuilderImpl.java

@Override
public URI build() {
    final StringBuilder segmentsBuilder = new StringBuilder();

    for (Segment seg : segments) {
        if (segmentsBuilder.length() > 0 && seg.getType() != SegmentType.KEY) {
            switch (seg.getType()) {
            case BOUND_OPERATION:
                segmentsBuilder.append(getBoundOperationSeparator());
                break;
            case BOUND_ACTION:
                segmentsBuilder.append(getBoundOperationSeparator());
                break;
            default:
                if (segmentsBuilder.length() > 0
                        && segmentsBuilder.charAt(segmentsBuilder.length() - 1) != '/') {
                    segmentsBuilder.append('/');
                }//from w  w  w.  j  ava2  s. com
            }
        }

        if (seg.getType() == SegmentType.ENTITY) {
            segmentsBuilder.append(seg.getType().getValue());
        } else {
            segmentsBuilder.append(seg.getValue());
        }
        if (seg.getType() == SegmentType.BOUND_OPERATION || seg.getType() == SegmentType.UNBOUND_OPERATION) {
            segmentsBuilder.append(getOperationInvokeMarker());
        }
    }

    try {
        if ((queryOptions.size() + parameters.size()) > 0) {
            segmentsBuilder.append("?");
            List<NameValuePair> list1 = new LinkedList<NameValuePair>();
            for (Map.Entry<String, String> option : queryOptions.entrySet()) {
                list1.add(new BasicNameValuePair("$" + option.getKey(), option.getValue()));
            }
            for (Map.Entry<String, String> parameter : parameters.entrySet()) {
                list1.add(new BasicNameValuePair("@" + parameter.getKey(), parameter.getValue()));
            }

            // don't use UriBuilder.build():
            // it will try to call URLEncodedUtils.format(Iterable<>,Charset) method,
            // which works in desktop java application, however, throws NoSuchMethodError in android OS,
            // so here manually construct the URL by its overload URLEncodedUtils.format(List<>,String).
            final String queryStr = encodeQueryParameter(list1);
            segmentsBuilder.append(queryStr);
        }

        return URI.create(segmentsBuilder.toString());
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Could not build valid URI", e);
    }
}

From source file:net.yacy.search.query.QueryParams.java

/**
 * Remove from the URL builder any query modifiers with the same name that the new modifier 
 * @param sb/*from   w  ww  .  ja  va 2  s.  c o  m*/
 *            a StringBuilder holding the search URL navigation being built.
 *            Must not be null and contain the URL base and the query string
 *            with its eventual modifiers
 * @param newModifier
 *            a new modifier of form key:value. Must not be null.
 */
protected static void removeOldModifiersFromNavUrl(final StringBuilder sb, final String newModifier) {
    int nmpi = newModifier.indexOf(":");
    if (nmpi > 0) {
        final String newModifierKey = newModifier.substring(0, nmpi) + ":";
        int sameModifierIndex = sb.indexOf(newModifierKey);
        while (sameModifierIndex > 0) {
            final int spaceModifierIndex = sb.indexOf(" ", sameModifierIndex);
            if (spaceModifierIndex > sameModifierIndex) {
                /* There are other modifiers after the matching one : we only remove the old matching modifier */
                sb.delete(sameModifierIndex, spaceModifierIndex + 1);
            } else {
                /* The matching modifier is the last : we truncate the builder */
                sb.setLength(sameModifierIndex);
            }
            sameModifierIndex = sb.indexOf(newModifierKey);
        }
        if (sb.charAt(sb.length() - 1) == '+') {
            sb.setLength(sb.length() - 1);
        }
        if (sb.charAt(sb.length() - 1) == ' ') {
            sb.setLength(sb.length() - 1);
        }
    }
}

From source file:com.android.calendar.alerts.AlarmScheduler.java

/**
 * Queries for all the reminders of the events in the instancesCursor, and schedules
 * the alarm for the next upcoming reminder.
 *//*w  w  w. ja  v a2  s  . c o m*/
private static void queryNextReminderAndSchedule(Cursor instancesCursor, Context context,
        ContentResolver contentResolver, AlarmManagerInterface alarmManager, int batchSize,
        long currentMillis) {
    if (AlertService.DEBUG) {
        int eventCount = instancesCursor.getCount();
        if (eventCount == 0) {
            Log.d(TAG, "No events found starting within 1 week.");
        } else {
            Log.d(TAG, "Query result count for events starting within 1 week: " + eventCount);
        }
    }

    // Put query results of all events starting within some interval into map of event ID to
    // local start time.
    Map<Integer, List<Long>> eventMap = new HashMap<Integer, List<Long>>();
    Time timeObj = new Time();
    long nextAlarmTime = Long.MAX_VALUE;
    int nextAlarmEventId = 0;
    instancesCursor.moveToPosition(-1);
    while (!instancesCursor.isAfterLast()) {
        int index = 0;
        eventMap.clear();
        StringBuilder eventIdsForQuery = new StringBuilder();
        eventIdsForQuery.append('(');
        while (index++ < batchSize && instancesCursor.moveToNext()) {
            int eventId = instancesCursor.getInt(INSTANCES_INDEX_EVENTID);
            long begin = instancesCursor.getLong(INSTANCES_INDEX_BEGIN);
            boolean allday = instancesCursor.getInt(INSTANCES_INDEX_ALL_DAY) != 0;
            long localStartTime;
            if (allday) {
                // Adjust allday to local time.
                localStartTime = Utils.convertAlldayUtcToLocal(timeObj, begin, Time.getCurrentTimezone());
            } else {
                localStartTime = begin;
            }
            List<Long> startTimes = eventMap.get(eventId);
            if (startTimes == null) {
                startTimes = new ArrayList<Long>();
                eventMap.put(eventId, startTimes);
                eventIdsForQuery.append(eventId);
                eventIdsForQuery.append(",");
            }
            startTimes.add(localStartTime);

            // Log for debugging.
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                timeObj.set(localStartTime);
                StringBuilder msg = new StringBuilder();
                msg.append("Events cursor result -- eventId:").append(eventId);
                msg.append(", allDay:").append(allday);
                msg.append(", start:").append(localStartTime);
                msg.append(" (").append(timeObj.format("%a, %b %d, %Y %I:%M%P")).append(")");
                Log.d(TAG, msg.toString());
            }
        }
        if (eventIdsForQuery.charAt(eventIdsForQuery.length() - 1) == ',') {
            eventIdsForQuery.deleteCharAt(eventIdsForQuery.length() - 1);
        }
        eventIdsForQuery.append(')');

        // Query the reminders table for the events found.
        Cursor cursor = null;
        try {
            cursor = contentResolver.query(Reminders.CONTENT_URI, REMINDERS_PROJECTION,
                    REMINDERS_WHERE + eventIdsForQuery, null, null);

            // Process the reminders query results to find the next reminder time.
            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                int eventId = cursor.getInt(REMINDERS_INDEX_EVENT_ID);
                int reminderMinutes = cursor.getInt(REMINDERS_INDEX_MINUTES);
                List<Long> startTimes = eventMap.get(eventId);
                if (startTimes != null) {
                    for (Long startTime : startTimes) {
                        long alarmTime = startTime - reminderMinutes * DateUtils.MINUTE_IN_MILLIS;
                        if (alarmTime > currentMillis && alarmTime < nextAlarmTime) {
                            nextAlarmTime = alarmTime;
                            nextAlarmEventId = eventId;
                        }

                        if (Log.isLoggable(TAG, Log.DEBUG)) {
                            timeObj.set(alarmTime);
                            StringBuilder msg = new StringBuilder();
                            msg.append("Reminders cursor result -- eventId:").append(eventId);
                            msg.append(", startTime:").append(startTime);
                            msg.append(", minutes:").append(reminderMinutes);
                            msg.append(", alarmTime:").append(alarmTime);
                            msg.append(" (").append(timeObj.format("%a, %b %d, %Y %I:%M%P")).append(")");
                            Log.d(TAG, msg.toString());
                        }
                    }
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    // Schedule the alarm for the next reminder time.
    if (nextAlarmTime < Long.MAX_VALUE) {
        scheduleAlarm(context, nextAlarmEventId, nextAlarmTime, currentMillis, alarmManager);
    }
}

From source file:com.github.helenusdriver.driver.impl.StatementImpl.java

/**
 * {@inheritDoc}/*from  w w w . ja v a 2 s .  c o m*/
 *
 * @author paouelle
 *
 * @see com.github.helenusdriver.driver.GenericStatement#getQueryString()
 */
@Override
public String getQueryString() {
    if (dirty || (cache == null)) {
        final StringBuilder sb = buildQueryString();

        if (sb == null) {
            this.cache = null;
        } else {
            // Use the same test that String#trim() uses to determine
            // if a character is a whitespace character.
            int l = sb.length();

            while (l > 0 && sb.charAt(l - 1) <= ' ') {
                l -= 1;
            }
            if (l != sb.length()) {
                sb.setLength(l);
            }
            if (l == 0 || sb.charAt(l - 1) != ';') {
                sb.append(';');
            }
            this.cache = sb;
        }
        this.dirty = false;
    }
    return (cache != null) ? cache.toString() : null;
}