Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

In this page you can find the example usage for java.lang StringBuilder insert.

Prototype

@Override
public StringBuilder insert(int offset, double d) 

Source Link

Usage

From source file:chat.viska.xmpp.NettyTcpSession.java

private String preprocessOutboundXml(@UnknownInitialization(NettyTcpSession.class) NettyTcpSession this,
        final Document xml) throws TransformerException {
    final String streamHeaderXmlnsBlock = String.format("xmlns=\"%1s\"", CommonXmlns.STREAM_HEADER);
    final String rootNs = xml.getDocumentElement().getNamespaceURI();
    final String rootName = xml.getDocumentElement().getLocalName();

    if (CommonXmlns.STREAM_OPENING_WEBSOCKET.equals(rootNs)) {
        if ("close".equals(rootName)) {
            return "</stream:stream>";
        } else if ("open".equals(rootName)) {
            return convertToTcpStreamOpening(xml);
        } else {/*from w w w. ja va 2s .  c  om*/
            throw new IllegalArgumentException("Incorrect stream opening XML.");
        }
    } else if (CommonXmlns.STREAM_HEADER.equals(rootNs)) {
        // Elements with header namespace, which mean should be prefixed "stream:"
        final StringBuilder builder = new StringBuilder(DomUtils.writeString(xml));
        final int streamHeaderNamespaceBlockIdx = builder.indexOf(streamHeaderXmlnsBlock);
        builder.insert(1, serverStreamPrefix + ":");
        builder.delete(streamHeaderNamespaceBlockIdx,
                streamHeaderNamespaceBlockIdx + streamHeaderXmlnsBlock.length());
        return builder.toString();
    } else {
        return DomUtils.writeString(xml);
    }
}

From source file:de.jfachwert.post.Postfach.java

/**
 * Liefert die Postfach-Nummer als formattierte Zahl. Dies macht natuerlich
 * nur Sinn, wenn diese Nummer gesetzt ist. Daher wird eine
 * {@link IllegalStateException} geworfen, wenn dies nicht der Fall ist.
 *
 * @return z.B. "8 15"//from   w ww  .  java  2 s  .  c  om
 */
@SuppressWarnings("squid:S3655")
public String getNummerFormatted() {
    if (!this.getNummer().isPresent()) {
        throw new IllegalStateException("no number present");
    }
    BigInteger hundert = BigInteger.valueOf(100);
    StringBuilder formatted = new StringBuilder();
    for (BigInteger i = this.getNummer().get(); i.compareTo(BigInteger.ONE) > 0; i = i.divide(hundert)) {
        formatted.insert(0, " " + i.remainder(hundert));
    }
    return formatted.toString().trim();
}

From source file:newsgroup.ToJSON.java

public static void go2json(String path, boolean is3d) throws IOException {
    List<String> readLines = FileUtils.readLines(new File(path));
    if (readLines.size() == 0) {
        System.err.println("empty");
    }//w w  w.  ja v  a  2  s  . c  o m
    List<String[]> cat1 = new ArrayList<>();
    List<String[]> cat2 = new ArrayList<>();
    for (String line : readLines) {
        String[] split = line.split(",");
        if (split[split.length - 1].equals("1")) {
            cat1.add(split);
        } else if (split[split.length - 1].equals("2")) {
            cat2.add(split);
        } else {
            break;
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("[");
    sb.append("[");
    for (int k = 0; k < cat1.size(); k++) {
        String[] li = cat1.get(k);
        sb.append("[");
        for (int i = 0; i < li[i].length() - 1; i++) {
            sb.append(li[i]);
            if (i < li[i].length() - 2) {
                sb.append(",");
            }
        }
        sb.append("]");
        if (k < cat1.size() - 1) {
            sb.append(",");
        }
    }
    sb.append("]");

    sb.append(",[");
    for (int k = 0; k < cat2.size(); k++) {
        String[] li = cat2.get(k);
        sb.append("[");
        for (int i = 0; i < li[i].length() - 1; i++) {
            sb.append(li[i]);
            if (i < li[i].length() - 2) {
                sb.append(",");
            }
        }
        sb.append("]");
        if (k < cat1.size() - 1) {
            sb.append(",");
        }
    }
    sb.append("]];");
    String name = "";
    if (path.contains("mtrick")) {
        name = "mtrick";
    } else if (path.contains("DTL")) {
        name = "DTL";
    } else if (path.contains("TriTL")) {
        name = "TriTL";
    } else if (path.contains("our")) {
        name = "our";
    }
    sb.insert(0, "var " + name + "=");
    FileUtils.write(new File(path + ".js"), sb.toString());
}

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 .j a  va  2  s.  c  o  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:edu.indiana.lib.twinpeaks.util.ParameterMap.java

/**
 * Build fixed length numeric filler text.
 * @return Fill text.  This is the HEX representation of the "rightmost"
 *         <code>PREFIXSIZE</code> digits of the original value.
 *//*from  w  w  w . ja v a2  s  . c  o  m*/
private String generateFillText() {
    StringBuilder result;
    int value;

    value = getFillSeed();
    if ((value < 0) || (value > MAXVALUE)) {
        throw new UnsupportedOperationException("Value " + value + " out of range");
    }

    result = new StringBuilder();

    for (int i = 0; i < PREFIXSIZE; i++) {
        result.insert(0, Integer.toHexString(value & 0xf));
        value >>= 4;
    }
    return result.toString();
}

From source file:com.autentia.bcbp.elements.ConditionalItemsUnique.java

public ConditionalItemsUnique(String passengerDescription, String sourceCheckin,
        String sourceBoardingPassIssuance, String dateOfIssueOfBoardingPass, String documentType,
        String airlineDesignatorOfBoardingPassIssuer, String baggageTagLicencePlateNumber,
        String firstNCBaggageTagLicencePlateNumber, String secondNCBaggageTagLicencePlateNumber) {
    super();/*from   w ww  .j a  va2s . co  m*/

    Stack<Item> items = new Stack<Item>();

    items.push(new Item(passengerDescription, passengerDescriptionLength, 142, PaddingType.String));
    items.push(new Item(sourceCheckin, sourceCheckinLength, 143, PaddingType.String));
    items.push(new Item(sourceBoardingPassIssuance, sourceBoardingPassIssuanceLength, 18, PaddingType.String));
    items.push(new Item(dateOfIssueOfBoardingPass, dateOfIssueOfBoardingPassLength, 108, PaddingType.Number));
    items.push(new Item(documentType, documentTypeLength, 19, PaddingType.String));
    items.push(new Item(airlineDesignatorOfBoardingPassIssuer, airlineDesignatorOfBoardingPassIssuerLength, 20,
            PaddingType.String));
    items.push(new Item(baggageTagLicencePlateNumber, baggageTagLicencePlateNumberLength, 236,
            PaddingType.String));
    items.push(new Item(firstNCBaggageTagLicencePlateNumber, firstNCBaggageTagLicencePlateNumberLength, 89,
            PaddingType.String));
    items.push(new Item(secondNCBaggageTagLicencePlateNumber, secondNCBaggageTagLicencePlateNumberLength, 118,
            PaddingType.String));

    final StringBuilder codeBuilder = new StringBuilder();
    boolean starting = true;
    while (!items.isEmpty()) {
        Item item = items.pop();
        if (starting && StringUtils.isNotBlank(item.getEncoded()) || !removeEndingEmptyElements)
            starting = false;
        if (!starting)
            codeBuilder.insert(0, item.getEncoded());
    }

    final String baseCode = codeBuilder.toString();

    if (StringUtils.isBlank(baseCode))
        code = "";
    else
        code = ">"
                + BCBPversion + StringUtils
                        .leftPad(Integer.toHexString(baseCode.length()), variableSizeLength, "0").toUpperCase()
                + baseCode;
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopTimeField.java

@Override
public void setShowSeconds(boolean showSeconds) {
    this.showSeconds = showSeconds;
    if (showSeconds) {
        if (!timeFormat.contains("ss")) {
            int minutesIndex = timeFormat.indexOf("mm");
            StringBuilder builder = new StringBuilder(timeFormat);
            builder.insert(minutesIndex + 2, ":ss");
            timeFormat = builder.toString();
        }/* ww w .ja v  a2s  .c om*/
    } else {
        if (timeFormat.contains("ss")) {
            int secondsIndex = timeFormat.indexOf("ss");
            StringBuilder builder = new StringBuilder(timeFormat);
            builder.delete(secondsIndex > 0 ? --secondsIndex : secondsIndex, secondsIndex + 3);
            timeFormat = builder.toString();
        }
    }
    updateTimeFormat();
    updateWidth();
}

From source file:com.autentia.bcbp.elements.ConditionalItemsRepeated.java

private ConditionalItemsRepeated(String airlineNumericCode, String serialNumber, String selecteeIndicator,
        String internationalDocumentVerification, String marketingCarrierDesignator,
        String frecuentFlyerAirlineDesignator, String frecuentFlyerNumber, String iDADIndicator,
        String freeBaggageAllowance, String fastTrack) {

    Stack<Item> items = new Stack<Item>();

    items.push(new Item(airlineNumericCode, airlineNumericCodeLength, 142, PaddingType.Number));
    items.push(new Item(serialNumber, serialNumberLength, 143, PaddingType.Number));
    items.push(new Item(selecteeIndicator, selecteeIndicatorLength, 18, PaddingType.String));
    items.push(new Item(internationalDocumentVerification, internationalDocumentVerificationLength, 108,
            PaddingType.String));
    items.push(new Item(marketingCarrierDesignator, marketingCarrierDesignatorLength, 19, PaddingType.String));
    items.push(new Item(frecuentFlyerAirlineDesignator, frecuentFlyerAirlineDesignatorLength, 20,
            PaddingType.String));
    items.push(new Item(frecuentFlyerNumber, frecuentFlyerNumberLength, 236, PaddingType.String));
    items.push(new Item(iDADIndicator, IDADIndicatorLength, 89, PaddingType.String));
    items.push(new Item(freeBaggageAllowance, freeBaggageAllowanceLength, 118, PaddingType.String));
    items.push(new Item(fastTrack, fastTrackLength, 254, PaddingType.String));

    final StringBuilder codeBuilder = new StringBuilder();
    boolean starting = true;
    while (!items.isEmpty()) {
        Item item = items.pop();/*from  w w w  .  ja v  a  2 s.co  m*/
        if (starting && StringUtils.isNotBlank(item.getEncoded()) || !removeEndingEmptyElements)
            starting = false;
        if (!starting)
            codeBuilder.insert(0, item.getEncoded());
    }

    final String baseCode = codeBuilder.toString();
    if (StringUtils.isBlank(baseCode)) {
        code = "";
    } else {
        code = StringUtils.leftPad(Integer.toHexString(baseCode.length()), variableSizeLength, "0")
                .toUpperCase() + baseCode;
    }
}

From source file:hudson.plugins.robot.model.RobotTestObject.java

public String getRelativeParent(RobotTestObject thisObject) {
    StringBuilder sb = new StringBuilder();
    RobotTestObject parent = getParent();
    if (parent != null && !parent.equals(thisObject)) {
        String parentPackage = parent.getRelativePackageName(thisObject);
        if (StringUtils.isNotBlank(parentPackage)) {
            sb.insert(0, ".");
            sb.insert(0, parentPackage);
        }/*from  w  ww .  j  a  v a2 s .c  o  m*/
    }
    return sb.toString();
}

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

@Override
public final int count(final Set<Long> adminRoles) {
    StringBuilder queryString = getFindAllQuery(adminRoles);
    queryString.insert(0, "SELECT COUNT(id) FROM (");
    queryString.append(") count_user_id");

    Query countQuery = entityManager.createNativeQuery(queryString.toString());

    return ((Number) countQuery.getSingleResult()).intValue();
}