Example usage for java.lang StringBuffer length

List of usage examples for java.lang StringBuffer length

Introduction

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

Prototype

@Override
    public synchronized int length() 

Source Link

Usage

From source file:de.suse.swamp.core.filter.DatabaseFilter.java

public String buildSQLString(ArrayList columns, ArrayList tables, ArrayList conditions) {
    StringBuffer sqlString = new StringBuffer("SELECT DISTINCT ");
    for (Iterator it = columns.iterator(); it.hasNext();) {
        sqlString.append(StringEscapeUtils.escapeSql((String) it.next())).append(", ");
    }/*from   ww w  .  j  a va2  s. co m*/
    sqlString.delete(sqlString.length() - 2, sqlString.length());

    sqlString.append(" FROM ");
    for (Iterator it = tables.iterator(); it.hasNext();) {
        sqlString.append(StringEscapeUtils.escapeSql((String) it.next())).append(", ");
    }
    sqlString.delete(sqlString.length() - 2, sqlString.length());

    if (conditions != null && conditions.size() >= 1) {
        sqlString.append(" WHERE ");
        for (Iterator it = conditions.iterator(); it.hasNext();) {
            sqlString.append((String) it.next()).append(" AND ");
        }
        sqlString.delete(sqlString.length() - 5, sqlString.length());
    }

    // does this filter set an ordering?
    if (descending != null && orderColumn != null) {
        sqlString.append(" ORDER BY " + orderColumn);
        if (descending.equals(Boolean.TRUE))
            sqlString.append(" DESC");
        else
            sqlString.append(" ASC");
        sqlString.append(", dbWorkflows.wfid ASC");

    }
    if (limit > 0) {
        sqlString.append(" LIMIT " + limit);
    }

    sqlString.append(";");
    return sqlString.toString();
}

From source file:hydrograph.ui.graph.command.ComponentPasteCommand.java

private String getPrefix(Object node) {
    String currentName = ((Component) node).getComponentLabel().getLabelContents();
    String prefix = currentName;/* w  w  w .ja  v a2s  .  co  m*/
    StringBuffer buffer = new StringBuffer(currentName);
    try {
        if (buffer.lastIndexOf(UNDERSCORE) != -1 && (buffer.lastIndexOf(UNDERSCORE) != buffer.length())) {
            String substring = StringUtils
                    .trim(buffer.substring(buffer.lastIndexOf(UNDERSCORE) + 1, buffer.length()));
            if (StringUtils.isNumeric(substring)) {
                prefix = buffer.substring(0, buffer.lastIndexOf(UNDERSCORE));
            }
        }
    } catch (Exception exception) {
        LOGGER.warn("Cannot process component name for detecting prefix : ", exception.getMessage());
    }
    return prefix;
}

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.HelpMojo.java

/**
 * Adds the specified line to the output sequence, performing line wrapping if necessary.
 *
 * @param lines      The sequence of display lines, must not be <code>null</code>.
 * @param line       The line to add, must not be <code>null</code>.
 * @param indentSize The size of each indentation, must not be negative.
 * @param lineLength The length of the line, must not be negative.
 *//*  w ww  .  j a v  a2s  . co m*/
private static void toLines(List lines, String line, int indentSize, int lineLength) {
    int lineIndent = getIndentLevel(line);
    StringBuffer buf = new StringBuffer(256);
    String[] tokens = line.split(" +");
    for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i];
        if (i > 0) {
            if (buf.length() + token.length() >= lineLength) {
                lines.add(buf.toString());
                buf.setLength(0);
                buf.append(repeat(" ", lineIndent * indentSize));
            } else {
                buf.append(' ');
            }
        }
        for (int j = 0; j < token.length(); j++) {
            char c = token.charAt(j);
            if (c == '\t') {
                buf.append(repeat(" ", indentSize - buf.length() % indentSize));
            } else if (c == '\u00A0') {
                buf.append(' ');
            } else {
                buf.append(c);
            }
        }
    }
    lines.add(buf.toString());
}

From source file:net.wasdev.gameon.auth.github.GitHubCallback.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //ok, we have our code.. so the user has agreed to our app being authed.
    String code = request.getParameter("code");

    String state = (String) request.getSession().getAttribute("github");

    //now we need to invoke the access_token endpoint to swap the code for a token.
    StringBuffer callbackURL = request.getRequestURL();
    int index = callbackURL.lastIndexOf("/");
    callbackURL.replace(index, callbackURL.length(), "").append("/GitHubCallback");

    HttpRequestFactory requestFactory;//w w  w .  jav a2s .  com
    try {
        //we'll ignore the ssl cert of the github server for now.. 
        //eventually we may add this to the player truststore.. 
        requestFactory = new NetHttpTransport.Builder().doNotValidateCertificate().build()
                .createRequestFactory();

        //prepare the request.. 
        GenericUrl url = new GenericUrl("https://github.com/login/oauth/access_token");
        //set the client id & secret from the injected environment.
        url.put("client_id", key);
        url.put("client_secret", secret);
        //add the code we just got given.. 
        url.put("code", code);
        url.put("redirect_uri", callbackURL);
        url.put("state", state);

        //now place the request to github..
        HttpRequest infoRequest = requestFactory.buildGetRequest(url);
        HttpResponse r = infoRequest.execute();
        String resp = "failed.";
        if (r.isSuccessStatusCode()) {

            //response comes back as query param encoded data.. we'll grab the token from that...
            resp = r.parseAsString();

            //http client way to parse query params.. 
            List<NameValuePair> params = URLEncodedUtils.parse(resp, Charset.forName("UTF-8"));
            String token = null;
            for (NameValuePair param : params) {
                if ("access_token".equals(param.getName())) {
                    token = param.getValue();
                }
            }

            if (token != null) {
                //great, we have a token, now we can use that to request the user profile..                    
                GenericUrl query = new GenericUrl("https://api.github.com/user");
                query.put("access_token", token);

                HttpRequest userRequest = requestFactory.buildGetRequest(query);
                HttpResponse u = userRequest.execute();
                if (u.isSuccessStatusCode()) {
                    //user profile comes back as json..                         
                    resp = u.parseAsString();
                    System.out.println(resp);

                    //use om to parse the json, so we can grab the id & name from it.
                    ObjectMapper om = new ObjectMapper();
                    JsonNode jn = om.readValue(resp, JsonNode.class);

                    Map<String, String> claims = new HashMap<String, String>();
                    claims.put("valid", "true");
                    //github id is a number, but we'll read it as text incase it changes in future.. 
                    claims.put("id", "github:" + jn.get("id").asText());
                    claims.put("name", jn.get("login").textValue());

                    String jwt = createJwt(claims);

                    //log for now, we'll clean this up once it's all working =)
                    System.out.println("New User Authed: " + claims.get("id") + " jwt " + jwt);
                    response.sendRedirect(callbackSuccess + "/" + jwt);

                } else {
                    System.out.println(u.getStatusCode());
                    response.sendRedirect("http://game-on.org/#/game");
                }
            } else {
                System.out.println("did not find token in github response " + resp);
                response.sendRedirect("http://game-on.org/#/game");
            }
        } else {
            response.sendRedirect("http://game-on.org/#/game");
        }

    } catch (GeneralSecurityException e) {
        throw new ServletException(e);
    }

}

From source file:com.konakart.bl.modules.payment.BasePaymentModule.java

/**
 * Split the name into first name and surname using simple logic... The surname is assumed to be
 * the last whitespace-separated item; everything before that is used as the first name.
 * // ww  w. j a v  a  2 s .  c om
 * @deprecated Replaced by a more robust solution where the address is looked up
 *             {@link #splitStreetAddressIntoNumberAndStreet(String streetAddress)}
 * @param name
 *            the name as a String to convert.
 * @return a String array where the first element is the first name and the second element is
 *         the surname.
 */
@Deprecated
protected String[] splitNameIntoFirstAndLastNames(String name) {
    String[] result = new String[2];

    if (name != null) {
        String[] names = name.split(" ");
        int len = names.length;
        if (len >= 2) {
            StringBuffer firstName = new StringBuffer();
            for (int i = 0; i < len - 1; i++) {
                if (firstName.length() == 0) {
                    firstName.append(names[i]);
                } else {
                    firstName.append(" ");
                    firstName.append(names[i]);
                }
            }
            result[0] = firstName.toString();
            result[1] = names[len - 1];
        }
    }

    return result;
}

From source file:org.jamwiki.servlets.RecentChangesFeedServlet.java

/**
 * TODO cache feed to avoid high load caused by RSS aggregators
 *
 * @throws Exception//  w  w w.  j a v a 2s . c o  m
 */
private SyndFeed getFeed(HttpServletRequest request) throws Exception {
    List<RecentChange> changes = getChanges(request);
    SyndFeed feed = new SyndFeedImpl();
    feed.setEncoding(FEED_ENCODING);
    feed.setTitle(Environment.getValue(Environment.PROP_RSS_TITLE));
    StringBuffer requestURL = request.getRequestURL();
    String feedURL = feedUrlPrefix
            + requestURL.substring(0, requestURL.length() - WikiUtil.getTopicFromURI(request).length());
    feed.setLink(feedURL);
    feed.setDescription("List of the last " + changes.size() + " changed wiki pages.");
    boolean includeMinorEdits = ServletRequestUtils.getBooleanParameter(request, MINOR_EDITS,
            defaultIncludeMinorEdits);
    boolean linkToVersion = ServletRequestUtils.getBooleanParameter(request, LINK_TO_VERSION,
            defaultLinkToVersion);
    feed.setEntries(getFeedEntries(changes, includeMinorEdits, linkToVersion, feedURL));
    return feed;
}

From source file:co.id.app.sys.util.StringUtils.java

public static String rpad(String string, String format, int len) {
    StringBuffer buffer = null;
    if (string == null || string.equals("")) {
        buffer = new StringBuffer();
    } else {//  w  w w  . j  a va2 s . co  m
        buffer = new StringBuffer(string);
    }

    while (buffer.length() < len) {
        buffer.append(format);
    }
    return buffer.toString();
}

From source file:com.callidusrobotics.ui.PaginatedMenuBox.java

private void printMessages(final Console console) {
    final int row = consoleTextBox.getInternalRow() + 3;
    final int col = consoleTextBox.getInternalCol() + 1;

    if (lineBuffer.isEmpty()) {
        return;/*from  w  w w  .  jav a2s  . co m*/
    }

    // TODO: This has a nice effect when the menuBuffer size is divisible by the pageSize, but can look wonky otherwise
    final int startIndex = currentIndex >= maxLines
            ? Math.max(currentIndex - maxLines, lineBuffer.size() - maxLines)
            : 0;
    final int nEntries = Math.min(maxLines, lineBuffer.size());

    // Copy the messageBuffer into the console's buffer
    final StringBuffer stringBuffer = new StringBuffer(lineLength);
    for (int r = startIndex; r < startIndex + nEntries; r++) {
        final BufferLine line = lineBuffer.get(r);
        stringBuffer.delete(0, stringBuffer.length());
        stringBuffer.append(line.line, 0, Math.min(lineLength, line.line.length()));
        for (int c = line.line.length(); c < lineLength; c++) {
            stringBuffer.append(' ');
        }

        if (r == currentIndex) {
            console.print(row + (r - startIndex) % maxLines, col, stringBuffer.toString(), selectForeground,
                    selectBackground);
        } else {
            console.print(row + (r - startIndex) % maxLines, col, stringBuffer.toString(), line.foreground,
                    line.background);
        }
    }
}

From source file:au.org.ala.biocache.util.ContactUtils.java

/**
 * Retrieve a list of contacts for this UID.
 *
 * @param collectionUid/*from ww w.j a  v a 2s . co  m*/
 * @return list of contacts
 */
public List<ContactDTO> getContactsForUID(String collectionUid) {

    if (collectionUid == null) {
        return new ArrayList<ContactDTO>();
    }

    List<ContactDTO> contactDTOs = new ArrayList<ContactDTO>();

    final String jsonUri = collectionContactsUrl + "/" + collectionUid + "/contacts.json";

    List<Map<String, Object>> contacts = restTemplate.getForObject(jsonUri, List.class);
    logger.debug("number of contacts = " + contacts.size());

    for (Map<String, Object> contact : contacts) {
        Map<String, String> details = (Map<String, String>) contact.get("contact");
        String email = details.get("email");

        String title = details.get("title");
        String firstName = details.get("firstName");
        String lastName = details.get("lastName");
        String phone = details.get("phone");

        logger.debug("email = " + email);

        ContactDTO c = new ContactDTO();
        c.setEmail(email);

        StringBuffer sb = new StringBuffer();
        if (StringUtils.isNotEmpty(title)) {
            sb.append(title);
            sb.append(" ");
        }
        sb.append(firstName);
        if (sb.length() > 0) {
            sb.append(" ");
        }
        sb.append(lastName);
        c.setDisplayName(sb.toString());
        c.setPhone(phone);
        c.setRole((String) contact.get("role"));

        contactDTOs.add(c);
    }

    return contactDTOs;
}

From source file:com.sonicle.webtop.core.app.servlet.Login.java

private String getBaseUrl(HttpServletRequest request) {
    StringBuffer url = request.getRequestURL();
    String uri = request.getRequestURI();
    String ctx = request.getContextPath();
    return url.substring(0, url.length() - uri.length() + ctx.length()) + "/";
}