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.hadoopvietnam.cache.memcached.MemcachedCache.java

/**
 * {@inheritDoc}/*from   w  w  w  .  j  a  v a 2  s .  c  o m*/
 */
public void addToTopOfList(final String inKey, final List<Long> inValue) {
    if (inValue == null) {
        // cannot pass null to memcached
        log.warn("In addToTopOfList, attempting to pass in NULL to memcached for key " + inKey);
        return;
    }

    if (log.isTraceEnabled()) {
        StringBuilder allLongs = new StringBuilder();
        for (Long lng : inValue) {
            allLongs.append(lng.toString());
            allLongs.append(',');
        }

        // trim the last , just for clarity in the log
        if (allLongs.charAt(allLongs.length() - 1) == ',') {
            allLongs.deleteCharAt(allLongs.length() - 1);
        }

        log.trace("Prepending to list '" + inKey + "', values: " + allLongs.toString());
    }

    // NOTE: memcached will NOT create a List if one does
    // not exist already, it will silently fail.
    // THIS IS WHAT WE WANT!

    // try to prepend data, NOTE the cas key is ignored
    // in ASCII protocol which we are using
    byte[] bytesToPrepend;
    try {
        bytesToPrepend = this.getBytesFromList(inValue);
    } catch (IOException e) {
        // problem getting the key .. set a null so the client goes
        // to the database and clear marker so next time we'll try again
        log.error("Unable to prepend LIST key " + inKey + " into memcached.  Exception " + e.getMessage());
        bytesToPrepend = null;
    }

    if (bytesToPrepend != null) {
        client.prepend(0, inKey, bytesToPrepend);
    }
}

From source file:com.jaspersoft.bigquery.connection.BigQueryConnection.java

public String test() throws JRException {
    try {/*www  . j av  a  2 s  .co m*/
        if (transport != null && jsonFactory != null && bigquery != null) {
            List datasetRequest = bigquery.datasets().list("publicdata");
            DatasetList datasetList = datasetRequest.execute();
            StringBuilder builder = new StringBuilder();
            builder.append("Available datasets: ");
            if (datasetList != null) {
                java.util.List<Datasets> datasets = datasetList.getDatasets();
                for (Datasets dataset : datasets) {
                    builder.append(dataset.getId());
                    builder.append(",");
                }
            }
            if (builder.charAt(builder.length() - 1) == ',') {
                builder.setCharAt(builder.length() - 1, '.');
            }
            return builder.toString();
        }
    } catch (Throwable e) {
        if (e.getMessage() != null && e.getMessage().toLowerCase().contains("unauthorized")) {
            logger.error(e);
            NTPUDPClient ntpClient = new NTPUDPClient();
            TimeInfo timeInfo = null;
            try {
                timeInfo = ntpClient.getTime(InetAddress.getByName(NTP_SERVER));
            } catch (Throwable e1) {
                e1.printStackTrace();
            } finally {
                ntpClient.close();
            }
            StringBuilder timeMessage = new StringBuilder();
            timeMessage.append("Ensure your system clock is synchronized with an NTP server.\n");
            if (timeInfo != null) {
                timeInfo.computeDetails();
                long offset = (timeInfo.getOffset() != null) ? timeInfo.getOffset() : 0l;
                SimpleDateFormat df = new SimpleDateFormat("EEE yyyy MMM d HH:mm:ss SSS z");
                String localDateString = df.format(new java.util.Date(System.currentTimeMillis()));
                String ntpDateString = df.format(new java.util.Date(System.currentTimeMillis() + offset));
                timeMessage.append("Current offset against \"");
                timeMessage.append(NTP_SERVER);
                timeMessage.append("\" is: ");
                timeMessage.append(offset);
                timeMessage.append(" milliseconds.\n");
                timeMessage.append("Current time on NTP   server: " + ntpDateString + "\n");
                timeMessage.append("Current time on local server: " + localDateString);
            }
            throw new JRException(
                    "Unauthorized exception. Please review your serviceAccountId and privateKeyFilePath.\n"
                            + timeMessage.toString());
        }
        throw new JRException(e);
    }
    throw new JRException("Could not connect to BigQuery");
}

From source file:org.apache.pig.builtin.OrcStorage.java

private String getReqiredColumnIdString(boolean[] requiredColumns) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < requiredColumns.length; i++) {
        if (requiredColumns[i]) {
            sb.append(i).append(",");
        }//from w  ww  .  j a  va2  s  .  c o  m
    }
    if (sb.charAt(sb.length() - 1) == ',') {
        sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlTextArea.java

private String readValue() {
    final StringBuilder buffer = new StringBuilder();
    for (final DomNode node : getChildren()) {
        if (node instanceof DomText) {
            buffer.append(((DomText) node).getData());
        }// ww w  . j a  v  a2  s  .co m
    }
    // if content starts with new line, it is ignored (=> for the parser?)
    if (buffer.length() != 0 && buffer.charAt(0) == '\n') {
        buffer.deleteCharAt(0);
    }
    return buffer.toString();
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlTextArea.java

private String readValueIE() {
    final StringBuilder buffer = new StringBuilder();
    for (final DomNode node : getDescendants()) {
        if (node instanceof DomText) {
            buffer.append(((DomText) node).getData());
        }/*ww  w  . j  av  a 2s  .c  o m*/
    }
    // if content starts with new line, it is ignored (=> for the parser?)
    if (buffer.length() != 0 && buffer.charAt(0) == '\n') {
        buffer.deleteCharAt(0);
    }
    return buffer.toString();
}

From source file:com.wabacus.WabacusFacade.java

private static String assembleOptionsResult(String realSelectboxid,
        List<Map<String, String>> lstOptionsResult) {
    StringBuilder resultBuf = new StringBuilder();
    resultBuf.append(realSelectboxid).append(":[");
    if (lstOptionsResult != null && lstOptionsResult.size() > 0) {
        String labelTmp, valueTmp;
        for (Map<String, String> mItemsTmp : lstOptionsResult) {
            labelTmp = mItemsTmp.get("label");
            valueTmp = mItemsTmp.get("value");
            labelTmp = labelTmp == null ? "" : labelTmp.trim();
            valueTmp = valueTmp == null ? "" : valueTmp.trim();
            resultBuf.append("{label:\"").append(labelTmp).append("\",");
            resultBuf.append("value:\"").append(valueTmp).append("\"},");
        }/*from  w  ww .  ja  v  a2s  . c o  m*/
    }
    if (resultBuf.charAt(resultBuf.length() - 1) == ',')
        resultBuf.deleteCharAt(resultBuf.length() - 1);
    resultBuf.append("],");
    return resultBuf.toString();
}

From source file:org.apache.syncope.core.persistence.dao.impl.SubjectSearchDAOImpl.java

@SuppressWarnings("unchecked")
private <T extends AbstractSubject> List<T> doSearch(final Set<Long> adminRoles, final SearchCond nodeCond,
        final int page, final int itemsPerPage, final List<OrderByClause> orderBy, final SubjectType type) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());

    // 1. get the query string from the search condition
    SearchSupport svs = new SearchSupport(type);
    StringBuilder queryString = getQuery(nodeCond, parameters, type, svs);

    // 2. take into account administrative roles and ordering
    OrderBySupport orderBySupport = parseOrderBy(type, svs, orderBy);
    if (queryString.charAt(0) == '(') {
        queryString.insert(0, buildSelect(orderBySupport));
        queryString.append(buildWhere(orderBySupport, type));
    } else {//w  w w .  ja  va2 s .  c  om
        queryString.insert(0, buildSelect(orderBySupport).append('('));
        queryString.append(')').append(buildWhere(orderBySupport, type));
    }
    queryString.append(getAdminRolesFilter(adminRoles, type)).append(')').append(buildOrderBy(orderBySupport));

    // 3. prepare the search query
    Query query = entityManager.createNativeQuery(queryString.toString());

    // 4. page starts from 1, while setFirtResult() starts from 0
    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage >= 0) {
        query.setMaxResults(itemsPerPage);
    }

    // 5. populate the search query with parameter values
    fillWithParameters(query, parameters);

    LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);

    // 6. Prepare the result (avoiding duplicates)
    List<T> result = new ArrayList<T>();

    for (Object subjectId : query.getResultList()) {
        long actualId;
        if (subjectId instanceof Object[]) {
            actualId = ((Number) ((Object[]) subjectId)[0]).longValue();
        } else {
            actualId = ((Number) subjectId).longValue();
        }

        T subject = type == SubjectType.USER ? (T) userDAO.find(actualId) : (T) roleDAO.find(actualId);
        if (subject == null) {
            LOG.error("Could not find {} with id {}, even though returned by the native query", type,
                    subjectId);
        } else {
            if (!result.contains(subject)) {
                result.add(subject);
            }
        }
    }

    return result;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPASubjectSearchDAO.java

@SuppressWarnings("unchecked")
private <T extends Subject<?, ?, ?>> List<T> doSearch(final Set<Long> adminRoles, final SearchCond nodeCond,
        final int page, final int itemsPerPage, final List<OrderByClause> orderBy, final SubjectType type) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<>());

    // 1. get the query string from the search condition
    SearchSupport svs = new SearchSupport(type);
    StringBuilder queryString = getQuery(nodeCond, parameters, type, svs);

    // 2. take into account administrative roles and ordering
    OrderBySupport orderBySupport = parseOrderBy(type, svs, orderBy);
    if (queryString.charAt(0) == '(') {
        queryString.insert(0, buildSelect(orderBySupport));
        queryString.append(buildWhere(orderBySupport, type));
    } else {//  w  ww .  java2  s.  c o m
        queryString.insert(0, buildSelect(orderBySupport).append('('));
        queryString.append(')').append(buildWhere(orderBySupport, type));
    }
    queryString.append(getAdminRolesFilter(adminRoles, type)).append(')').append(buildOrderBy(orderBySupport));

    // 3. prepare the search query
    Query query = entityManager.createNativeQuery(queryString.toString());

    // 4. page starts from 1, while setFirtResult() starts from 0
    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage >= 0) {
        query.setMaxResults(itemsPerPage);
    }

    // 5. populate the search query with parameter values
    fillWithParameters(query, parameters);

    LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);

    // 6. Prepare the result (avoiding duplicates)
    List<T> result = new ArrayList<>();

    for (Object subjectId : query.getResultList()) {
        long actualId;
        if (subjectId instanceof Object[]) {
            actualId = ((Number) ((Object[]) subjectId)[0]).longValue();
        } else {
            actualId = ((Number) subjectId).longValue();
        }

        T subject = type == SubjectType.USER ? (T) userDAO.find(actualId) : (T) roleDAO.find(actualId);
        if (subject == null) {
            LOG.error("Could not find {} with id {}, even though returned by the native query", type, actualId);
        } else {
            if (!result.contains(subject)) {
                result.add(subject);
            }
        }
    }

    return result;
}

From source file:com.thejoshwa.ultrasonic.androidapp.util.Util.java

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

    SharedPreferences prefs = getPreferences(context);

    int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
    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  ww  .  ja v a 2 s .com
    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:org.apache.nutch.analysis.lang.NGramProfile.java

/**
 * Analyze a piece of text/* ww  w  . j a  v a 2s.  com*/
 * 
 * @param text the text to be analyzed
 */
public void analyze(StringBuilder text) {

    if (ngrams != null) {
        ngrams.clear();
        sorted = null;
        ngramcounts = null;
    }

    word.clear().append(SEPARATOR);
    for (int i = 0; i < text.length(); i++) {
        char c = Character.toLowerCase(text.charAt(i));

        if (Character.isLetter(c)) {
            add(word.append(c));
        } else {
            //found word boundary
            if (word.length() > 1) {
                //we have a word!
                add(word.append(SEPARATOR));
                word.clear().append(SEPARATOR);
            }
        }
    }

    if (word.length() > 1) {
        //we have a word!
        add(word.append(SEPARATOR));
    }
    normalize();
}