Example usage for java.lang StringBuilder deleteCharAt

List of usage examples for java.lang StringBuilder deleteCharAt

Introduction

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

Prototype

@Override
public StringBuilder deleteCharAt(int index) 

Source Link

Usage

From source file:com.impetus.client.rdbms.query.RDBMSEntityReader.java

/**
 * //from w ww .j  a  va 2s .  co  m
 * @param queryBuilder
 * @param value
 * @param isString
 */
private void buildINClause(StringBuilder queryBuilder, Object value, boolean isString) {
    if (List.class.isAssignableFrom(value.getClass()) || Set.class.isAssignableFrom(value.getClass())) {
        queryBuilder.append(" (");
        Collection collection = ((Collection) value);
        for (Object obj : collection) {
            if (isString) {
                appendStringPrefix(queryBuilder, isString);
            }
            queryBuilder.append(obj.toString());
            if (isString) {
                appendStringPrefix(queryBuilder, isString);
            }
            queryBuilder.append(",");
        }
        if (!collection.isEmpty()) {
            queryBuilder.deleteCharAt(queryBuilder.lastIndexOf(","));
        }
        queryBuilder.append(")");
    } else {
        queryBuilder.append(value.toString());
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.lists.StudentListByDegreeDA.java

private void addBranchsInformation(final StyledExcelSpreadsheet spreadsheet,
        final StudentCurricularPlan studentCurricularPlan) {

    final StringBuilder majorBranches = new StringBuilder();
    final StringBuilder minorBranches = new StringBuilder();

    for (final BranchCurriculumGroup group : studentCurricularPlan.getBranchCurriculumGroups()) {
        if (group.isMajor()) {
            majorBranches.append(group.getName().toString()).append(",");
        } else if (group.isMinor()) {
            minorBranches.append(group.getName().toString()).append(",");
        }/*from w w  w.ja va 2 s  .c om*/
    }

    if (majorBranches.length() > 0) {
        spreadsheet.addCell(majorBranches.deleteCharAt(majorBranches.length() - 1).toString());
    } else {
        spreadsheet.addCell("");
    }

    if (minorBranches.length() > 0) {
        spreadsheet.addCell(minorBranches.deleteCharAt(minorBranches.length() - 1).toString());
    } else {
        spreadsheet.addCell("");
    }
}

From source file:com.cloudera.oryx.contrib.flume.OryxJSONEventParser.java

/** {@inheritDoc} */
@Override//from   w  w  w .j  av  a  2  s  .  c o  m
public void parseEvent(Event event, List<List<String>> fields, List<String> batch) {
    ReadContext context = JsonPath.parse(new String(event.getBody()));

    for (List<String> keys : fields) {
        StringBuilder record = new StringBuilder();
        // add user and item
        for (int i = 0; i < 2; i++) {
            String val = null;
            try {
                val = context.read(keys.get(i));
            } catch (Exception ex) {
                if (ex instanceof PathNotFoundException) {
                    log.error("Unable to find key '{}'", keys.get(i), ex);
                } else if (ex instanceof ClassCastException) {
                    log.error("Unable to cast value for key '{}'", keys.get(i), ex);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Skipping record '{}'", new String(event.getBody()));
                }
                record.setLength(0);
                break;
            }
            record.append(StringEscapeUtils.escapeCsv(val) + ",");
        }

        if (record.length() > 0) {
            if (keys.size() == 3) {
                // add strength
                record.append(keys.get(2));
            } else {
                record.deleteCharAt(record.length() - 1);
            }
            if (log.isDebugEnabled()) {
                log.debug("Adding record '{}' to batch", record.toString());
            }
            batch.add(record.toString());
        }
    }
}

From source file:com.haulmont.cuba.gui.app.core.categories.AttributeEditor.java

@Override
public boolean preCommit() {
    Collection<ScreenAndComponent> screens = screensDs.getItems();
    StringBuilder stringBuilder = new StringBuilder();
    for (ScreenAndComponent screenAndComponent : screens) {
        if (StringUtils.isNotBlank(screenAndComponent.getScreen())) {
            stringBuilder.append(screenAndComponent.getScreen());
            if (StringUtils.isNotBlank(screenAndComponent.getComponent())) {
                stringBuilder.append("#");
                stringBuilder.append(screenAndComponent.getComponent());
            }//from ww w.  jav  a  2s . c  om
            stringBuilder.append(",");
        }
    }

    if (stringBuilder.length() > 0) {
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
    }
    attribute.setTargetScreens(stringBuilder.toString());

    if (localizedFrame != null) {
        attribute.setLocaleNames(localizedFrame.getValue());
    }

    return true;
}

From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java

/**
 * Determines the namespace(s) for the action based on the action class. If there is a {@link Namespace}
 * annotation on the class (including parent classes) or on the package that the class is in, than
 * it is used. Otherwise, the Java package name that the class is in is used in conjunction with
 * either the <b>struts.convention.action.packages</b> or <b>struts.convention.package.locators</b>
 * configuration values. These are used to determine which part of the Java package name should
 * be converted into the namespace for the XWork PackageConfig.
 *
 * @param actionClass The action class.//from   ww w . j  a va  2 s.c  o  m
 * @return The namespace or an empty string.
 */
protected List<String> determineActionNamespace(Class<?> actionClass) {
    List<String> namespaces = new ArrayList<String>();

    // Check if there is a class or package level annotation for the namespace
    //single namespace
    Namespace namespaceAnnotation = AnnotationTools.findAnnotation(actionClass, Namespace.class);
    if (namespaceAnnotation != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using non-default action namespace from Namespace annotation of [#0]",
                    namespaceAnnotation.value());
        }

        namespaces.add(namespaceAnnotation.value());
    }

    //multiple annotations
    Namespaces namespacesAnnotation = AnnotationTools.findAnnotation(actionClass, Namespaces.class);
    if (namespacesAnnotation != null) {
        if (LOG.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder();
            for (Namespace namespace : namespacesAnnotation.value())
                sb.append(namespace.value()).append(",");
            sb.deleteCharAt(sb.length() - 1);
            LOG.trace("Using non-default action namespaces from Namespaces annotation of [#0]", sb.toString());
        }

        for (Namespace namespace : namespacesAnnotation.value())
            namespaces.add(namespace.value());
    }

    //don't use default if there are annotations
    if (!namespaces.isEmpty())
        return namespaces;

    String pkg = actionClass.getPackage().getName();
    String pkgPart = null;
    if (actionPackages != null) {
        for (String actionPackage : actionPackages) {
            if (pkg.startsWith(actionPackage)) {
                pkgPart = actionClass.getName().substring(actionPackage.length() + 1);
            }
        }
    }

    if (pkgPart == null && packageLocators != null) {
        for (String packageLocator : packageLocators) {
            int index = pkg.lastIndexOf(packageLocator);

            // This ensures that the match is at the end, beginning or has a dot on each side of it
            if (index >= 0 && (index + packageLocator.length() == pkg.length() || index == 0
                    || (pkg.charAt(index - 1) == '.' && pkg.charAt(index + packageLocator.length()) == '.'))) {
                pkgPart = actionClass.getName().substring(index + packageLocator.length() + 1);
            }
        }
    }

    if (pkgPart != null) {
        final int indexOfDot = pkgPart.lastIndexOf('.');
        if (indexOfDot >= 0) {
            String convertedNamespace = actionNameBuilder.build(pkgPart.substring(0, indexOfDot));
            namespaces.add("/" + convertedNamespace.replace('.', '/'));
            return namespaces;
        }
    }

    namespaces.add("");
    return namespaces;
}

From source file:com.ewcms.component.interaction.service.InteractionService.java

private String replayRatioJSON(Integer type) {
    StringBuilder builder = new StringBuilder();
    builder.append("[");
    List<Organ> list = interactionDAO.findInteractionBackOrder(9, true);
    for (Organ organ : list) {
        builder.append("{");
        builder.append("\"id\":\"").append(organ.getId()).append("\",");
        builder.append("\"organ\":\"").append(organ.getName()).append("\",");
        builder.append("\"ratio\":").append(organ.getBackRatio()).append(",");
        builder.append("\"type\":").append(0);
        builder.append("},");
    }//from w  w  w  .  j  ava  2 s  .c  o  m
    list = interactionDAO.findInteractionBackOrder(9, false);
    for (Organ organ : list) {
        builder.append("{");
        builder.append("\"id\":\"").append(organ.getId()).append("\",");
        builder.append("\"organ\":\"").append(organ.getName()).append("\",");
        builder.append("\"ratio\":").append(organ.getNoBackRatio()).append(",");
        builder.append("\"type\":").append(1);
        builder.append("},");
    }
    builder.deleteCharAt(builder.length() - 1);
    builder.append("]");

    return builder.toString();
}

From source file:io.teak.sdk.Request.java

@Override
public void run() {
    HttpsURLConnection connection = null;
    SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256");
    String requestBody;//from ww w  .j  a v  a 2  s  .  c  o m

    String hostnameForEndpoint = this.hostname;
    if (hostnameForEndpoint == null) {
        hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint);
    }

    try {
        ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet());
        Collections.sort(payloadKeys);

        StringBuilder builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            if (value != null) {
                String valueString;
                if (value instanceof Map) {
                    valueString = new JSONObject((Map) value).toString();
                } else if (value instanceof Array) {
                    valueString = new JSONArray(Collections.singletonList(value)).toString();
                } else if (value instanceof Collection) {
                    valueString = new JSONArray((Collection) value).toString();
                } else {
                    valueString = value.toString();
                }
                builder.append(key).append("=").append(valueString).append("&");
            } else {
                Log.e(LOG_TAG, "Value for key: " + key + " is null.");
            }
        }
        builder.deleteCharAt(builder.length() - 1);

        String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        byte[] result = mac.doFinal(stringToSign.getBytes());

        builder = new StringBuilder();
        for (String key : payloadKeys) {
            Object value = this.payload.get(key);
            String valueString;
            if (value instanceof Map) {
                valueString = new JSONObject((Map) value).toString();
            } else if (value instanceof Array) {
                valueString = new JSONArray(Collections.singletonList(value)).toString();
            } else if (value instanceof Collection) {
                valueString = new JSONArray((Collection) value).toString();
            } else {
                valueString = value.toString();
            }
            builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&");
        }
        builder.append("sig=")
                .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8"));

        requestBody = builder.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e));
        return;
    }

    try {
        if (Teak.isDebug) {
            Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': "
                    + new JSONObject(this.payload).toString(2));
        }

        URL url = new URL("https://" + hostnameForEndpoint + this.endpoint);
        connection = (HttpsURLConnection) url.openConnection();

        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(requestBody);
        wr.flush();
        wr.close();

        // Get Response
        InputStream is;
        if (connection.getResponseCode() < 400) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        if (Teak.isDebug) {
            String responseText = response.toString();
            try {
                responseText = new JSONObject(response.toString()).toString(2);
            } catch (Exception ignored) {
            }
            Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText);
        }

        // For extending classes
        done(connection.getResponseCode(), response.toString());
    } catch (Exception e) {
        Log.e(LOG_TAG, Log.getStackTraceString(e));
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:ac.ucy.cs.spdx.service.Compatibility.java

@POST
@Path("/compatible/")
@Consumes(MediaType.TEXT_PLAIN)//ww w.  j  a v a 2 s  .co m
@Produces(MediaType.APPLICATION_JSON)
public String areCompatible(String jsonString) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode fileNode = null;
    try {
        fileNode = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<String> licenses = new ArrayList<String>();
    JsonNode licensesJSON = fileNode.get("licenses");
    StringBuilder compatibleJSON = new StringBuilder();

    for (int i = 0; i < licensesJSON.size(); i++) {
        String licenseId = licensesJSON.get(i).get("identifier").toString();
        licenseId = licenseId.substring(1, licenseId.length() - 1);
        licenses.add(licenseId);
    }

    boolean compatible = LicenseCompatibility.areCompatible(licenses.toArray(new String[licenses.size()]));
    boolean adjustable = true;
    ArrayList<License> proposed = new ArrayList<License>();

    if (!compatible) {
        LicenseCompatibility.proposeLicense(licenses.toArray(new String[licenses.size()]));
    }

    if (proposed.isEmpty()) {
        adjustable = false;
    }

    compatibleJSON.append(
            "{\"compatible\":\"" + compatible + "\",\"adjustable\":\"" + adjustable + "\",\"proposals\":[");
    for (License proposal : proposed) {
        compatibleJSON.append("{\"identifier\":\"" + proposal.getIdentifier() + "\"},");
    }

    if (adjustable) {
        compatibleJSON.deleteCharAt(compatibleJSON.length() - 1);
    }

    compatibleJSON.append("]}");
    return compatibleJSON.toString();// {"licenses":[{"identifier":"Apache-2.0"},{"identifier":"MPL-2.0"}]}
}

From source file:jongo.filter.DefaultFormatFilter.java

private String formatSuccessJSONResponse(final JongoSuccess response) {
    final StringBuilder b = new StringBuilder("{");
    b.append("\"success\":");
    b.append(response.isSuccess());//from   w  w  w. j a v  a 2 s.c  om
    b.append(",\"cells\":[ "); //this last space is important!
    for (Row r : response.getRows()) {
        List<String> args = new ArrayList<String>();
        for (String key : r.getCells().keySet()) {
            String val = StringEscapeUtils.escapeJson(r.getCells().get(key));
            if (StringUtils.isNumeric(val)) {
                if (StringUtils.isWhitespace(val)) {
                    args.add("\"" + key.toLowerCase() + "\"" + ":" + "\"\"");
                } else {
                    args.add("\"" + key.toLowerCase() + "\"" + ":" + val);
                }
            } else {
                args.add("\"" + key.toLowerCase() + "\"" + ":" + "\"" + val + "\"");
            }
        }

        b.append("{");
        b.append(StringUtils.join(args, ","));
        b.append("}");
        b.append(",");
    }
    b.deleteCharAt(b.length() - 1);
    b.append("]}");
    return b.toString();
}

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();/*from   ww w.  jav  a  2  s.  co 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 + ") ";
}