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:edu.psu.iam.cpr.core.util.Utility.java

/**
 * <p>Convert IPv6 address into RFC 5952 form.
 * E.g. 2001:db8:0:1:0:0:0:1 -> 2001:db8:0:1::1</p>
 * <p/>//www .  jav  a2  s  .co m
 * <p>Method is null safe, and if IPv4 address or host name is passed to the
 * method it is returned wihout any processing.</p>
 * <p/>
 * <p>Method also supports IPv4 in IPv6 (e.g. 0:0:0:0:0:ffff:192.0.2.1 ->
 * ::ffff:192.0.2.1), and zone ID (e.g. fe80:0:0:0:f0f0:c0c0:1919:1234%4
 * -> fe80::f0f0:c0c0:1919:1234%4).</p>
 *
 * @param ipv6Address String representing valid IPv6 address.
 * @return String representing IPv6 in canonical form.
 * @throws IllegalArgumentException if IPv6 format is unacceptable.
 */
public static String canonicalizeAddress(final String ipv6Address) throws IllegalArgumentException {

    if (ipv6Address == null) {
        return null;
    }

    // Definitely not an IPv6, return untouched input.
    if (!mayBeIPv6Address(ipv6Address)) {
        return ipv6Address;
    }

    // Length without zone ID (%zone) or IPv4 address
    int ipv6AddressLength = ipv6Address.length();
    if (ipv6Address.contains(":") && ipv6Address.contains(".")) {
        // IPv4 in IPv6
        // e.g. 0:0:0:0:0:FFFF:127.0.0.1
        final int lastColonPos = ipv6Address.lastIndexOf(':');
        final int lastColonsPos = ipv6Address.lastIndexOf("::");
        if (lastColonsPos >= 0 && lastColonPos == lastColonsPos + 1) {
            /*
             *  IPv6 part ends with two consecutive colons,
             *  last colon is part of IPv6 format.
             *  e.g. ::127.0.0.1
             */
            ipv6AddressLength = lastColonPos + 1;
        } else {
            /*
             *  IPv6 part ends with only one colon,
             *  last colon is not part of IPv6 format.
             *  e.g. ::FFFF:127.0.0.1
             */
            ipv6AddressLength = lastColonPos;
        }
    } else if (ipv6Address.contains(":") && ipv6Address.contains("%")) {
        // Zone ID
        // e.g. fe80:0:0:0:f0f0:c0c0:1919:1234%4
        ipv6AddressLength = ipv6Address.lastIndexOf('%');
    }

    final StringBuilder result = new StringBuilder();
    final char[][] groups = new char[MAX_NUMBER_OF_GROUPS][MAX_GROUP_LENGTH];
    int groupCounter = 0;
    int charInGroupCounter = 0;

    // Index of the current zeroGroup, -1 means not found.
    int zeroGroupIndex = -1;
    int zeroGroupLength = 0;

    // maximum length zero group, if there is more then one, then first one
    int maxZeroGroupIndex = -1;
    int maxZeroGroupLength = 0;

    boolean isZero = true;
    boolean groupStart = true;

    /*
     *  Two consecutive colons, initial expansion.
     *  e.g. 2001:db8:0:0:1::1 -> 2001:db8:0:0:1:0:0:1
     */

    final StringBuilder expanded = new StringBuilder(ipv6Address);
    final int colonsPos = ipv6Address.indexOf("::");
    int length = ipv6AddressLength;
    int change = 0;

    if (colonsPos >= 0 && colonsPos < ipv6AddressLength - 2) {
        int colonCounter = 0;
        for (int i = 0; i < ipv6AddressLength; i++) {
            if (ipv6Address.charAt(i) == ':') {
                colonCounter++;
            }
        }

        if (colonsPos == 0) {
            expanded.insert(0, "0");
            change = change + 1;
        }

        for (int i = 0; i < MAX_NUMBER_OF_GROUPS - colonCounter; i++) {
            expanded.insert(colonsPos + 1, "0:");
            change = change + 2;
        }

        if (colonsPos == ipv6AddressLength - 2) {
            expanded.setCharAt(colonsPos + change + 1, '0');
        } else {
            expanded.deleteCharAt(colonsPos + change + 1);
            change = change - 1;
        }
        length = length + change;
    }

    // Processing one char at the time
    for (int charCounter = 0; charCounter < length; charCounter++) {
        char c = expanded.charAt(charCounter);
        if (c >= 'A' && c <= 'F') {
            c = (char) (c + 32);
        }
        if (c != ':') {
            groups[groupCounter][charInGroupCounter] = c;
            if (!(groupStart && c == '0')) {
                ++charInGroupCounter;
                groupStart = false;
            }
            if (c != '0') {
                isZero = false;
            }
        }
        if (c == ':' || charCounter == length - 1) {
            // We reached end of current group
            if (isZero) {
                ++zeroGroupLength;
                if (zeroGroupIndex == -1) {
                    zeroGroupIndex = groupCounter;
                }
            }

            if (!isZero || charCounter == length - 1) {
                // We reached end of zero group
                if (zeroGroupLength > maxZeroGroupLength) {
                    maxZeroGroupLength = zeroGroupLength;
                    maxZeroGroupIndex = zeroGroupIndex;
                }
                zeroGroupLength = 0;
                zeroGroupIndex = -1;
            }
            ++groupCounter;
            charInGroupCounter = 0;
            isZero = true;
            groupStart = true;
        }
    }

    final int numberOfGroups = groupCounter;

    // Output results
    for (groupCounter = 0; groupCounter < numberOfGroups; groupCounter++) {
        if (maxZeroGroupLength <= 1 || groupCounter < maxZeroGroupIndex
                || groupCounter >= maxZeroGroupIndex + maxZeroGroupLength) {
            for (int j = 0; j < MAX_GROUP_LENGTH; j++) {
                if (groups[groupCounter][j] != 0) {
                    result.append(groups[groupCounter][j]);
                }
            }
            if (groupCounter < numberOfGroups - 1
                    && (groupCounter != maxZeroGroupIndex - 1 || maxZeroGroupLength <= 1)) {
                result.append(':');
            }
        } else if (groupCounter == maxZeroGroupIndex) {
            result.append("::");
        }
    }

    // Solve problem with three colons in IPv4 in IPv6 format
    // e.g. 0:0:0:0:0:0:127.0.0.1 -> :::127.0.0.1 -> ::127.0.0.1
    final int resultLength = result.length();
    if (result.charAt(resultLength - 1) == ':' && ipv6AddressLength < ipv6Address.length()
            && ipv6Address.charAt(ipv6AddressLength) == ':') {
        result.delete(resultLength - 1, resultLength);
    }

    /*
     * Append IPv4 from IPv4-in-IPv6 format or Zone ID
     */
    for (int i = ipv6AddressLength; i < ipv6Address.length(); i++) {
        result.append(ipv6Address.charAt(i));
    }

    return result.toString();
}

From source file:bhl.pages.handler.PagesDocumentsHandler.java

String concoctTitle(String docid) {
    StringBuilder className = new StringBuilder();
    StringBuilder yearName = new StringBuilder();
    StringBuilder author = new StringBuilder();
    int state = 0;
    for (int i = 0; i < docid.length(); i++) {
        char token = docid.charAt(i);
        switch (state) {
        case 0: // looking for document classname
            if (Character.isDigit(token)) {
                yearName.append(token);// www.  j av a2s. com
                state = 1;
            } else
                className.append(token);
            break;
        case 1: // looking for year
            if (Character.isDigit(token) && yearName.length() < 4)
                yearName.append(token);
            else
                state = 2;
            break;
        case 2: // looking for author
            if (Character.isLetter(token))
                author.append(token);
            break;
        }
    }
    StringBuilder total = new StringBuilder();
    total.append(author);
    total.append(" ");
    if (className.length() > 0 && className.charAt(className.length() - 1) == 's')
        className.setLength(className.length() - 1);
    total.append(className);
    total.append(" ");
    total.append(yearName);
    return total.toString();
}

From source file:com.zimbra.cs.service.formatter.VCard.java

public static List<VCard> parseVCard(String vcard) throws ServiceException {
    List<VCard> cards = new ArrayList<VCard>();

    Map<String, String> fields = new HashMap<String, String>();
    ListMultimap<String, VCardParamsAndValue> xprops = ArrayListMultimap.create();
    List<Attachment> attachments = new ArrayList<Attachment>();

    VCardProperty vcprop = new VCardProperty();
    int depth = 0;
    int cardstart = 0;
    String uid = null;/* w  w w .j a v  a  2  s  . c o m*/
    StringBuilder line = new StringBuilder(256);
    for (int start, pos = 0, limit = vcard.length(); pos < limit;) {
        // unfold the next line in the vcard
        line.setLength(0);
        String name = null;
        String value;
        int linestart = pos;
        boolean folded = true;
        do {
            start = pos;
            while (pos < limit && vcard.charAt(pos) != '\r' && vcard.charAt(pos) != '\n') {
                pos++;
            }
            line.append(vcard.substring(start, pos));
            if (pos < limit) {
                if (pos < limit && vcard.charAt(pos) == '\r')
                    pos++;
                if (pos < limit && vcard.charAt(pos) == '\n')
                    pos++;
            }
            if (pos < limit && (vcard.charAt(pos) == ' ' || vcard.charAt(pos) == '\t')) {
                pos++;
            } else {
                name = vcprop.parse(line);
                if ((vcprop.getEncoding() != Encoding.Q)
                        || !((line.length() > 0) && ('=' == (line.charAt(line.length() - 1))))) {
                    folded = false;
                }
            }
        } while (folded);
        if (vcprop.isEmpty()) {
            continue;
        }

        if (Strings.isNullOrEmpty(name)) {
            throw ServiceException.PARSE_ERROR("missing property name in line " + shortFormForLogging(line),
                    null);
        } else if (name.equals("VERSION") || name.equals("REV") || name.equals("PRODID")) {
            continue;
        } else if ((name.startsWith("X-") && !name.startsWith("X-ZIMBRA-"))
                || (!PROPERTY_NAMES.contains(name) /* Assume iana-token */)) {
            VCardParamsAndValue ppav;
            if (Encoding.B.equals(vcprop.encoding)) {
                // Keep value encoded as don't trust binary data stored in metadata
                Set<String> params = vcprop.params;
                params.add("ENCODING=B");
                if ((vcprop.charset != null) && (!MimeConstants.P_CHARSET_UTF8.equals(vcprop.charset))) {
                    params.add(String.format("CHARSET=%s", vcprop.charset));
                }
                ppav = new VCardParamsAndValue(vcprop.value, vcprop.params);
            } else {
                ppav = new VCardParamsAndValue(vcfDecode(vcprop.getValue()), vcprop.params);
            }
            // handle multiple occurrences of xprops with the same key
            String group = vcprop.getGroup();
            String key = (group == null) ? name : group + "." + name;
            xprops.put(key, ppav);
        } else if (name.equals("BEGIN")) {
            if (++depth == 1) {
                // starting a top-level vCard; reset state
                fields = new HashMap<String, String>();
                xprops = ArrayListMultimap.create();
                attachments = new ArrayList<Attachment>();
                cardstart = linestart;
                uid = null;
            }
            continue;
        } else if (name.equals("END")) {
            if (depth > 0 && depth-- == 1) {
                if (!xprops.isEmpty()) {
                    fields.put(ContactConstants.A_vCardXProps, Contact.encodeUnknownVCardProps(xprops));
                }

                // finished a vCard; add to list if non-empty
                if (!fields.isEmpty()) {
                    Contact.normalizeFileAs(fields);
                    cards.add(new VCard(fields.get(ContactConstants.A_fullName),
                            vcard.substring(cardstart, pos), fields, attachments, uid));
                }
            }
            continue;
        } else if (depth <= 0) {
            continue;
        } else if (name.equals("AGENT")) {
            // catch AGENT on same line as BEGIN block when rest of AGENT is not on the same line
            if (vcprop.getValue().trim().toUpperCase().matches("BEGIN\\s*:\\s*VCARD"))
                depth++;
            continue;
        }

        if (vcprop.getEncoding() == Encoding.B && !vcprop.containsParam("VALUE=URI")) {
            if (name.equals("PHOTO")) {
                String suffix = vcprop.getParamValue("TYPE").toUpperCase();
                String ctype = null;
                if (!Strings.isNullOrEmpty(suffix)) {
                    ctype = "image/" + suffix.toLowerCase();
                    suffix = '.' + suffix;
                }
                attachments.add(new Attachment(vcprop.getDecoded(), ctype, "image", "image" + suffix));
                continue;
            }
            if (name.equals("KEY")) {
                String encoded = new String(Base64.encodeBase64Chunked(vcprop.getDecoded()));
                fields.put(ContactConstants.A_userCertificate, encoded);
                continue;
            }
        }

        value = vcprop.getValue();

        // decode the property's value and assign to the appropriate contact field(s)
        if (name.equals("FN"))
            addField(ContactConstants.A_fullName, vcfDecode(value), "altFullName", 2, fields);
        else if (name.equals("N"))
            decodeStructured(value, NAME_FIELDS, fields);
        else if (name.equals("NICKNAME")) // TODO: VCARD 4 NICKNAME is multi-valued (COMMA separated)
                                          //       It is treated as a single value here
            addField(ContactConstants.A_nickname, vcfDecode(value), "altNickName", 2, fields);
        else if (name.equals("PHOTO"))
            fields.put(ContactConstants.A_image, vcfDecode(value)); // Assumption: Do not want multiple photos.
        else if (name.equals("BDAY"))
            addField(ContactConstants.A_birthday, vcfDecode(value), null, 2, fields);
        else if (name.equals("ADR"))
            decodeAddress(value, vcprop, fields);
        else if (name.equals("TEL"))
            decodeTelephone(value, vcprop, fields);
        else if (name.equals("URL"))
            decodeURL(value, vcprop, fields);
        else if (name.equals("ORG"))
            decodeStructured(value, ORG_FIELDS, fields);
        else if (name.equals("TITLE"))
            addField(ContactConstants.A_jobTitle, vcfDecode(value), "altJobTitle", 2, fields);
        else if (name.equals("NOTE"))
            addField(ContactConstants.A_notes, vcfDecode(value), null, 2, fields);
        else if (name.equals("EMAIL"))
            addField(ContactConstants.A_email, vcfDecode(value), null, 2, fields);
        else if (name.equals("X-ZIMBRA-MAIDENNAME"))
            fields.put(ContactConstants.A_maidenName, vcfDecode(value));
        else if (name.startsWith("X-ZIMBRA-IMADDRESS"))
            addField("imAddress", true, vcfDecode(value), null, 1, fields);
        else if (name.equals("X-ZIMBRA-ANNIVERSARY"))
            addField(ContactConstants.A_anniversary, vcfDecode(value), null, 2, fields);
        else if (name.equals("UID"))
            uid = value;
    }

    return cards;
}

From source file:org.dspace.app.bulkedit.DSpaceCSV.java

/**
 * Create a new instance, reading the lines in from file
 *
 * @param f The file to read from/*from ww w . j  a v a 2  s.  com*/
 * @param c The DSpace Context
 *
 * @throws Exception thrown if there is an error reading or processing the file
 */
public DSpaceCSV(File f, Context c) throws Exception {
    // Initialise the class
    init();

    // Open the CSV file
    BufferedReader input = null;
    try {
        input = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));

        // Read the heading line
        String head = input.readLine();
        String[] headingElements = head.split(escapedFieldSeparator);
        int columnCounter = 0;
        for (String element : headingElements) {
            columnCounter++;

            // Remove surrounding quotes if there are any
            if ((element.startsWith("\"")) && (element.endsWith("\""))) {
                element = element.substring(1, element.length() - 1);
            }

            // Store the heading
            if ("collection".equals(element)) {
                // Store the heading
                headings.add(element);
            }
            // Store the action
            else if ("action".equals(element)) {
                // Store the heading
                headings.add(element);
            } else if (!"id".equals(element)) {
                String authorityPrefix = "";
                AuthorityValue authorityValueType = authorityValueService.getAuthorityValueType(element);
                if (authorityValueType != null) {
                    String authorityType = authorityValueType.getAuthorityType();
                    authorityPrefix = element.substring(0, authorityType.length() + 1);
                    element = element.substring(authorityPrefix.length());
                }

                // Verify that the heading is valid in the metadata registry
                String[] clean = element.split("\\[");
                String[] parts = clean[0].split("\\.");

                if (parts.length < 2) {
                    throw new MetadataImportInvalidHeadingException(element,
                            MetadataImportInvalidHeadingException.ENTRY, columnCounter);
                }

                String metadataSchema = parts[0];
                String metadataElement = parts[1];
                String metadataQualifier = null;
                if (parts.length > 2) {
                    metadataQualifier = parts[2];
                }

                // Check that the scheme exists
                MetadataSchema foundSchema = metadataSchemaService.find(c, metadataSchema);
                if (foundSchema == null) {
                    throw new MetadataImportInvalidHeadingException(clean[0],
                            MetadataImportInvalidHeadingException.SCHEMA, columnCounter);
                }

                // Check that the metadata element exists in the schema
                MetadataField foundField = metadataFieldService.findByElement(c, foundSchema, metadataElement,
                        metadataQualifier);
                if (foundField == null) {
                    throw new MetadataImportInvalidHeadingException(clean[0],
                            MetadataImportInvalidHeadingException.ELEMENT, columnCounter);
                }

                // Store the heading
                headings.add(authorityPrefix + element);
            }
        }

        // Read each subsequent line
        StringBuilder lineBuilder = new StringBuilder();
        String lineRead;

        while ((lineRead = input.readLine()) != null) {
            if (lineBuilder.length() > 0) {
                // Already have a previously read value - add this line
                lineBuilder.append("\n").append(lineRead);

                // Count the number of quotes in the buffer
                int quoteCount = 0;
                for (int pos = 0; pos < lineBuilder.length(); pos++) {
                    if (lineBuilder.charAt(pos) == '"') {
                        quoteCount++;
                    }
                }

                if (quoteCount % 2 == 0) {
                    // Number of quotes is a multiple of 2, add the item
                    addItem(lineBuilder.toString());
                    lineBuilder = new StringBuilder();
                }
            } else if (lineRead.indexOf('"') > -1) {
                // Get the number of quotes in the line
                int quoteCount = 0;
                for (int pos = 0; pos < lineRead.length(); pos++) {
                    if (lineRead.charAt(pos) == '"') {
                        quoteCount++;
                    }
                }

                if (quoteCount % 2 == 0) {
                    // Number of quotes is a multiple of 2, add the item
                    addItem(lineRead);
                } else {
                    // Uneven quotes - add to the buffer and leave for later
                    lineBuilder.append(lineRead);
                }
            } else {
                // No previously read line, and no quotes in the line - add item
                addItem(lineRead);
            }
        }
    } finally {
        if (input != null) {
            input.close();
        }
    }
}

From source file:com.splicemachine.db.impl.sql.compile.QueryTreeNode.java

/**
 * Format a node that has been converted to a String for printing
 * as part of a tree.  This method indents the String to the given
 * depth by inserting tabs at the beginning of the string, and also
 * after every newline./*from ww  w.  j a  va  2  s  . c o  m*/
 *
 * @param nodeString The node formatted as a String
 * @param depth      The depth to indent the given node
 * @return The node String reformatted with tab indentation
 */

public static String formatNodeString(String nodeString, int depth) {
    if (SanityManager.DEBUG) {
        StringBuilder nodeStringBuffer = new StringBuilder(nodeString);
        int pos;
        char c;
        char[] indent = new char[depth];

        /*
           ** Form an array of tab characters for indentation.
        */
        while (depth > 0) {
            indent[depth - 1] = '\t';
            depth--;
        }

        /* Indent the beginning of the string */
        nodeStringBuffer.insert(0, indent);

        /*
        ** Look for newline characters, except for the last character.
        ** We don't want to indent after the last newline.
        */
        for (pos = 0; pos < nodeStringBuffer.length() - 1; pos++) {
            c = nodeStringBuffer.charAt(pos);
            if (c == '\n') {
                /* Indent again after each newline */
                nodeStringBuffer.insert(pos + 1, indent);
            }
        }

        return nodeStringBuffer.toString();
    } else {
        return "";
    }
}

From source file:com.wabacus.system.dataset.select.report.value.RelationalDBReportDataSetValueProvider.java

public String getRowSelectValueConditionExpression(ReportRequest rrequest) {
    if (rrequest.getShowtype() == Consts.DISPLAY_ON_PAGE || rrequest.getShowtype() == Consts.DISPLAY_ON_PRINT)
        return null;
    ReportBean rbean = getReportBean();/*  ww  w  .j ava 2s.  c o  m*/
    IComponentType typeObj = rrequest.getComponentTypeObj(rbean, null, false);
    if (!(typeObj instanceof AbsListReportType))
        return null;
    AbsDataExportBean dataExportBean = rbean.getDataExportsBean() != null
            ? rbean.getDataExportsBean().getDataExportBean(rrequest.getShowtype())
            : null;
    if (dataExportBean == null)
        return null;//?<dataexport/>????
    List<String> lstRowSelectColProperties = this.ownerDataSetValueBean.getLstRowSelectValueColProperties();
    if (Tools.isEmpty(lstRowSelectColProperties))
        return null;
    List<Map<String, String>> lstSelectRowDatas = rrequest.getCdb(rbean.getId()).getLstRowSelectData();
    if (Tools.isEmpty(lstSelectRowDatas))
        return null;//???
    StringBuilder resultBuf = new StringBuilder();
    String nameTmp, valueTmp;
    for (String colPropertyTmp : lstRowSelectColProperties) {
        nameTmp = dataExportBean.getRowSelectDataBean().getColExpression(colPropertyTmp);
        if (Tools.isEmpty(nameTmp))
            continue;
        resultBuf.append(nameTmp).append(" in (");
        for (Map<String, String> mRowDataTmp : lstSelectRowDatas) {
            valueTmp = mRowDataTmp.get(colPropertyTmp);
            if (valueTmp == null)
                valueTmp = "";
            resultBuf.append("'" + valueTmp + "',");
        }
        if (resultBuf.charAt(resultBuf.length() - 1) == ',')
            resultBuf.deleteCharAt(resultBuf.length() - 1);
        resultBuf.append(") and ");
    }
    String resultStr = resultBuf.toString().trim();
    if (resultStr.endsWith(" and"))
        resultStr = resultStr.substring(0, resultStr.length() - 4);
    return resultStr.trim().equals("") ? resultStr : " (" + resultStr + ") ";
}

From source file:com.abstratt.mdd.internal.frontend.textuml.TextUMLFormatter.java

@SuppressWarnings("unchecked")
private void doGenericFormat(Node node, StringBuilder output, int indentation) {
    if (node == null)
        return;/*from   w  w w.  ja va  2  s.  com*/
    List<Node> ignored = (List<Node>) ignoredTokens.getIn(node);
    if (ignored != null)
        for (Node ignoredNode : ignored)
            format(ignoredNode, output, indentation);
    if (node instanceof Token) {
        final Token token = ((Token) node);
        final boolean newLine = isAtNewLine(output);
        if (newLine)
            for (int i = 0; i < indentation; i++)
                output.append("    ");
        else if (!isPunctuation(token.getText()) && !isPunctuation("" + output.charAt(output.length() - 1)))
            addWhitespace(output);
        output.append(token.getText());
    } else {
        ASTNode<Token, Node> astNode = ASTNode.<Token, Node>buildTree(node);
        List<ASTNode<Token, Node>> children = astNode.getChildren();
        for (Iterator<ASTNode<Token, Node>> i = children.iterator(); i.hasNext();) {
            ASTNode<Token, Node> element = (ASTNode<Token, Node>) i.next();
            format((Node) element.getBaseNode(), output, indentation);
        }
    }
}

From source file:org.openregistry.core.domain.jpa.JpaAddressImpl.java

public String getSingleLineAddress() {
    final StringBuilder builder = new StringBuilder();

    if (StringUtils.hasText(this.line1) && !this.line1.equalsIgnoreCase("none")) {
        builder.append(getLine1());/*  ww  w.  j  a v  a2s  .c om*/
    }

    if (StringUtils.hasText(this.line2)) {
        builder.append(", ");
        builder.append(getLine2());
    }
    if (StringUtils.hasText(this.line3)) {
        builder.append(", ");
        builder.append(getLine3());
    }
    if (StringUtils.hasText(this.city) && !this.city.equalsIgnoreCase("none")) {
        builder.append(", ");
        builder.append(getCity());
    }
    if (getRegion() != null) {
        builder.append(", ");
        builder.append(getRegion().getCode());
    }
    if (StringUtils.hasText(this.postalCode) && !this.postalCode.equalsIgnoreCase("none")) {
        builder.append(" ");
        builder.append(getPostalCode());
    }
    if (getCountry() != null) {
        builder.append(" ");
        builder.append(getCountry().getName());
    }

    if (builder.charAt(0) == ',')
        return builder.toString().substring(2);
    else
        return builder.toString();
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

private String validateName(String originalName) {
    StringBuilder name = new StringBuilder();

    for (int i = 0; i < originalName.length(); i++) {
        char c = originalName.charAt(i);

        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            name.append(c);/*from   w  w w.  j  a v a  2s.co  m*/
        } else if (((c >= '0' && c <= '9') || c == '-' || c == '_' || c == ' ') && name.length() > 0) {
            if (c == ' ') {
                c = '-';
            }
            name.append(c);
        }
    }
    if (name.length() < 1) {
        return "unnamed-" + System.currentTimeMillis();
    }
    if (name.charAt(name.length() - 1) == '-' || name.charAt(name.length() - 1) == '_') { // check for trailing - or _
        name.deleteCharAt(name.length() - 1);
    }
    return name.toString();
}

From source file:com.google.dart.java2dart.util.JavaUtils.java

/**
 * @param binding the {@link ITypeBinding} to analyze.
 * @param runtime flag <code>true</code> if we need name for class loading, <code>false</code> if
 *          we need name for source generation.
 * @param withGenerics flag <code>true</code> if generics type arguments should be appended.
 * @return the fully qualified name of given {@link ITypeBinding}, or
 *         {@link #NO_TYPE_BINDING_NAME} .
 *///  www  . j a  va  2  s  .  c o m
public static String getFullyQualifiedName(ITypeBinding binding, boolean runtime, boolean withGenerics) {
    // check if no binding
    if (binding == null) {
        return NO_TYPE_BINDING_NAME;
    }
    // check for primitive type
    if (binding.isPrimitive()) {
        return binding.getName();
    }
    // array
    if (binding.isArray()) {
        StringBuilder sb = new StringBuilder();
        // append element type qualified name
        ITypeBinding elementType = binding.getElementType();
        String elementTypeQualifiedName = getFullyQualifiedName(elementType, runtime);
        sb.append(elementTypeQualifiedName);
        // append dimensions
        for (int i = 0; i < binding.getDimensions(); i++) {
            sb.append("[]");
        }
        // done
        return sb.toString();
    }
    // object
    {
        String scope;
        ITypeBinding declaringType = binding.getDeclaringClass();
        if (declaringType == null) {
            IPackageBinding packageBinding = binding.getPackage();
            if (packageBinding == null || packageBinding.isUnnamed()) {
                scope = "";
            } else {
                scope = packageBinding.getName() + ".";
            }
        } else if (binding.isTypeVariable()) {
            return binding.getName();
        } else {
            // use '$', because we use this class name for loading class
            scope = getFullyQualifiedName(declaringType, runtime);
            if (runtime) {
                scope += "$";
            } else {
                scope += ".";
            }
        }
        // prepare "simple" name, without scope
        String jdtName = binding.getName();
        String name = StringUtils.substringBefore(jdtName, "<");
        if (withGenerics) {
            ITypeBinding[] typeArguments = binding.getTypeArguments();
            if (typeArguments.length != 0) {
                StringBuilder sb = new StringBuilder(name);
                sb.append("<");
                for (ITypeBinding typeArgument : typeArguments) {
                    if (sb.charAt(sb.length() - 1) != '<') {
                        sb.append(",");
                    }
                    String typeArgumentName = getFullyQualifiedName(typeArgument, runtime, withGenerics);
                    sb.append(typeArgumentName);
                }
                sb.append(">");
                name = sb.toString();
            }
        }
        // qualified name is scope plus "simple" name
        return scope + name;
    }
}