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:org.alfresco.textgen.TextGenerator.java

public String generateQueryString(long seed, int words, int wordLimit) {
    if (wordLimit < words) {
        throw new IllegalStateException();
    }/*from   w ww .j a  va 2  s  .  c  o m*/

    Random random = new Random();
    random.setSeed(seed);

    int start = 0;
    if (wordLimit > words) {
        start = random.nextInt(wordLimit - words);
    }

    random.setSeed(seed);

    for (int i = 0; i < start; i++) {
        random.nextDouble();
    }

    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < words; i++) {
        String word = wordGenerator.getWord(random.nextDouble());
        if (buffer.length() > 0) {
            buffer.append(" ");
        }
        buffer.append(word);
    }
    return buffer.toString();
}

From source file:org.dspace.submit.lookup.ArXivService.java

public List<Record> searchByTerm(String title, String author, int year) throws HttpException, IOException {
    StringBuffer query = new StringBuffer();
    if (StringUtils.isNotBlank(title)) {
        query.append("ti:\"").append(title).append("\"");
    }/*from  w w w  .j  a va2  s  .co  m*/
    if (StringUtils.isNotBlank(author)) {
        // [FAU]
        if (query.length() > 0)
            query.append(" AND ");
        query.append("au:\"").append(author).append("\"");
    }
    return search(query.toString(), "", 10);
}

From source file:com.spoledge.audao.db.dao.RootDaoImpl.java

/**
 * Used for logging./*from  w  ww.jav  a  2  s.  c om*/
 */
protected final String sqlLog(String sql, Object[] params) {
    String ret = "SQL: " + sql;

    if (params == null || params.length == 0) {
        return ret;
    } else {
        StringBuffer sb = new StringBuffer();

        for (Object param : params) {
            if (param != null) {
                if (sb.length() != 0) {
                    sb.append(", ");
                }

                if (param instanceof Number) {
                    sb.append(param);
                } else {
                    sb.append('\'').append(param).append('\'');
                }
            }
        }

        return ret + "; PARAMS: " + sb;
    }
}

From source file:ShowFileDialog.java

/**
 * Creates the contents for the window//  w  w w  .  j  a  va  2  s . co  m
 * 
 * @param shell the parent shell
 */
public void createContents(final Shell shell) {
    shell.setLayout(new GridLayout(5, true));

    new Label(shell, SWT.NONE).setText("File Name:");

    final Text fileName = new Text(shell, SWT.BORDER);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    fileName.setLayoutData(data);

    Button multi = new Button(shell, SWT.PUSH);
    multi.setText("Open Multiple...");
    multi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            // User has selected to open multiple files
            FileDialog dlg = new FileDialog(shell, SWT.MULTI);
            dlg.setFilterNames(FILTER_NAMES);
            dlg.setFilterExtensions(FILTER_EXTS);
            String fn = dlg.open();
            if (fn != null) {
                // Append all the selected files. Since getFileNames() returns only 
                // the names, and not the path, prepend the path, normalizing
                // if necessary
                StringBuffer buf = new StringBuffer();
                String[] files = dlg.getFileNames();
                for (int i = 0, n = files.length; i < n; i++) {
                    buf.append(dlg.getFilterPath());
                    if (buf.charAt(buf.length() - 1) != File.separatorChar) {
                        buf.append(File.separatorChar);
                    }
                    buf.append(files[i]);
                    buf.append(" ");
                }
                fileName.setText(buf.toString());
            }
        }
    });

    Button open = new Button(shell, SWT.PUSH);
    open.setText("Open...");
    open.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            // User has selected to open a single file
            FileDialog dlg = new FileDialog(shell, SWT.OPEN);
            dlg.setFilterNames(FILTER_NAMES);
            dlg.setFilterExtensions(FILTER_EXTS);
            String fn = dlg.open();
            if (fn != null) {
                fileName.setText(fn);
            }
        }
    });

    Button save = new Button(shell, SWT.PUSH);
    save.setText("Save...");
    save.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
            // User has selected to save a file
            FileDialog dlg = new FileDialog(shell, SWT.SAVE);
            dlg.setFilterNames(FILTER_NAMES);
            dlg.setFilterExtensions(FILTER_EXTS);
            String fn = dlg.open();
            if (fn != null) {
                fileName.setText(fn);
            }
        }
    });
}

From source file:org.jasig.portlet.emailpreview.dao.EmailAccountService.java

private String convertIdsToString(String[] messageIds) {
    StringBuffer ids = new StringBuffer();
    for (String id : messageIds) {
        ids.append(id).append(",");
    }/*from  www.  j  a va 2s .c  o  m*/
    ids.deleteCharAt(ids.length() - 1);
    return ids.toString();
}

From source file:net.lightbody.bmp.proxy.jetty.util.URI.java

/** Convert a path to a cananonical form.
 * All instances of "." and ".." are factored out.  Null is returned
 * if the path tries to .. above it's root.
 * @param path //from   www  .j  ava  2 s. c o m
 * @return path or null.
 */
public static String canonicalPath(String path) {
    if (path == null || path.length() == 0)
        return path;

    int end = path.length();
    int queryIdx = path.indexOf('?');
    int start = path.lastIndexOf('/', (queryIdx > 0 ? queryIdx : end));

    search: while (end > 0) {
        switch (end - start) {
        case 2: // possible single dot
            if (path.charAt(start + 1) != '.')
                break;
            break search;
        case 3: // possible double dot
            if (path.charAt(start + 1) != '.' || path.charAt(start + 2) != '.')
                break;
            break search;
        }

        end = start;
        start = path.lastIndexOf('/', end - 1);
    }

    // If we have checked the entire string
    if (start >= end)
        return path;

    StringBuffer buf = new StringBuffer(path);
    int delStart = -1;
    int delEnd = -1;
    int skip = 0;

    while (end > 0) {
        switch (end - start) {
        case 2: // possible single dot
            if (buf.charAt(start + 1) != '.') {
                if (skip > 0 && --skip == 0) {
                    delStart = start >= 0 ? start : 0;
                    if (delStart > 0 && delEnd == buf.length() && buf.charAt(delEnd - 1) == '.')
                        delStart++;
                }
                break;
            }

            if (start < 0 && buf.length() > 2 && buf.charAt(1) == '/' && buf.charAt(2) == '/')
                break;

            if (delEnd < 0)
                delEnd = end;
            delStart = start;
            if (delStart < 0 || delStart == 0 && buf.charAt(delStart) == '/') {
                delStart++;
                if (delEnd < buf.length() && buf.charAt(delEnd) == '/')
                    delEnd++;
                break;
            }
            if (end == buf.length())
                delStart++;

            end = start--;
            while (start >= 0 && buf.charAt(start) != '/')
                start--;
            continue;

        case 3: // possible double dot
            if (buf.charAt(start + 1) != '.' || buf.charAt(start + 2) != '.') {
                if (skip > 0 && --skip == 0) {
                    delStart = start >= 0 ? start : 0;
                    if (delStart > 0 && delEnd == buf.length() && buf.charAt(delEnd - 1) == '.')
                        delStart++;
                }
                break;
            }

            delStart = start;
            if (delEnd < 0)
                delEnd = end;

            skip++;
            end = start--;
            while (start >= 0 && buf.charAt(start) != '/')
                start--;
            continue;

        default:
            if (skip > 0 && --skip == 0) {
                delStart = start >= 0 ? start : 0;
                if (delEnd == buf.length() && buf.charAt(delEnd - 1) == '.')
                    delStart++;
            }
        }

        // Do the delete
        if (skip <= 0 && delStart >= 0 && delStart >= 0) {
            buf.delete(delStart, delEnd);
            delStart = delEnd = -1;
            if (skip > 0)
                delEnd = end;
        }

        end = start--;
        while (start >= 0 && buf.charAt(start) != '/')
            start--;
    }

    // Too many ..
    if (skip > 0)
        return null;

    // Do the delete
    if (delEnd >= 0)
        buf.delete(delStart, delEnd);

    return buf.toString();
}

From source file:ductive.parse.parsers.LongParser.java

@Override
public Result<Long> doApply(ParseContext ctx) {
    int pos = 0;// w  w w  . j a va  2 s.co m

    if (ctx.length() == 0)
        throw new UnexpectedEofException(String.format(LongParser.UNEXPECTED_EOF_MESSAGE, pos), ctx, 0);

    StringBuffer buf = new StringBuffer();

    char c = ctx.charAt(pos);
    while (true) {
        if (!CharUtils.isAsciiNumeric(c))
            break;

        buf.append(c);

        if (++pos >= ctx.length())
            break;

        c = ctx.charAt(pos);
    }

    if (buf.length() == 0)
        throw new UnexpectedCharacterException(String.format(UNEXPECTED_CHARACTER_MESSAGE, c, 0), ctx, 0);

    String str = buf.toString();
    return Result.make(Long.parseLong(str), ctx.eatInput(str.length()));
}

From source file:eionet.cr.web.util.columns.SubjectPredicateColumn.java

/**
 * @see eionet.cr.web.util.columns.SearchResultColumn#format(java.lang.Object)
 *
 *      Gets the collection of objects matching to the given predicate in the given subject. Formats the given collection to
 *      comma-separated string. For literal objects, simply the value of the literal will be used. For resource objects,
 *      clickable factsheet links will be created.
 *//*from w  w  w .j a  v  a 2  s.c o m*/
@Override
public String format(Object object) {

    String result = null;
    if (object != null && object instanceof SubjectDTO && predicateUri != null) {

        SubjectDTO subjectDTO = (SubjectDTO) object;
        Collection<ObjectDTO> objects = subjectDTO.getObjectsForSearchResultsDisplay(predicateUri,
                getLanguages());

        if (predicateUri.equals(Predicates.RDFS_LABEL)) {

            if (objects.isEmpty()) {
                Collection<String> rdfTypes = subjectDTO.getObjectValues(Predicates.RDF_TYPE);
                if (CollectionUtils.isEmpty(rdfTypes) && subjectTypes != null) {
                    rdfTypes = Arrays.asList(subjectTypes);
                }
                if (CollectionUtils.exists(rdfTypes, new EqualPredicate(Subjects.DATACUBE_OBSERVATION))) {
                    // If type is DataCube observation, then special handling.
                    result = StringUtils.substringAfter(subjectDTO.getUri(),
                            ScoreboardSparqlDAO.OBSERVATION_URI_PREFIX);
                    if (StringUtils.isBlank(result)) {
                        result = subjectDTO.getUri();
                    }
                } else {
                    result = URIUtil.extractURILabel(subjectDTO.getUri(), SubjectDTO.NO_LABEL);
                }
            } else {
                result = objectValuesToCSV(objects);
            }
            logger.debug(result);
            result = buildFactsheetLink(subjectDTO.getUri(), StringEscapeUtils.escapeXml(result), false);

        } else if (!objects.isEmpty()) {

            StringBuffer buf = new StringBuffer();
            for (ObjectDTO o : objects) {

                if (buf.length() > 0) {
                    buf.append(", ");
                }

                if (o.isLiteral()) {
                    buf.append(o.getValue());
                } else {
                    String label = o.getDerviedLiteralValue();
                    if (label == null) {
                        label = URIUtil.extractURILabel(o.getValue(), SubjectDTO.NO_LABEL);
                    }
                    buf.append(buildFactsheetLink(o.getValue(), StringEscapeUtils.escapeXml(label), true));
                }
            }
            result = buf.toString();
        }
    }

    return StringUtils.isBlank(result) ? "&nbsp;" : result;
}

From source file:net.ostis.scpdev.editors.SequenceRule.java

public IToken evaluate(ICharacterScanner scanner) {
    char c = (char) scanner.read();

    StringBuffer buffer = new StringBuffer(maxWordLen);
    buffer.append(c);/*from  w ww .j av  a2s. c  om*/

    int successLength = 0;

    if (starts.contains(c)) {
        if (words.contains(buffer.toString()))
            successLength = 1;

        while (buffer.length() <= maxWordLen) {
            c = (char) scanner.read();

            if (parts.contains(c)) {
                buffer.append(c);

                if (words.contains(buffer.toString()))
                    successLength = buffer.length();
            } else {
                scanner.unread();
                break;
            }
        }
    }

    for (int i = buffer.length() - successLength; i != 0; i--)
        scanner.unread();

    return (successLength != 0) ? token : Token.UNDEFINED;
}

From source file:com.redhat.victims.database.VictimsSQL.java

/**
 * Given a an sql query containing the string "IN (?)" and a set of strings,
 * this method constructs a query by safely replacing the first occurence of
 * "IN (?)" with "IN ('v1','v2'...)", where v1,v2,.. are in values.
 *
 * @param query//  w w w .  jav  a  2s  .  com
 * @param values
 * @return
 */
protected String constructInStringsQuery(String query, Set<String> values) {
    String replace = "IN (?)";
    assert query.lastIndexOf(replace) == query.indexOf(replace);
    String sql = query.replace("IN (?)", "IN (%s)");

    StringBuffer list = new StringBuffer();
    for (String value : values) {
        if (list.length() > 0) {
            list.append(",");
        }
        value = String.format("'%s'", StringEscapeUtils.escapeSql(value));
        list.append(value);
    }

    return String.format(sql, list.toString());
}