Example usage for java.lang StringBuilder lastIndexOf

List of usage examples for java.lang StringBuilder lastIndexOf

Introduction

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

Prototype

@Override
    public int lastIndexOf(String str) 

Source Link

Usage

From source file:jp.co.worksap.message.decoder.HeaderDecoder.java

private String createEncodingRegex() {
    StringBuilder builder = new StringBuilder();
    String[] charSets = Encoding.VALID_CHARSETS;
    builder.append("\\?==\\?(");
    for (int i = 0; i < charSets.length; i++) {
        builder.append("(").append(charSets[i]).append(")");
        builder.append("|");
    }/*from  w  w w.  j av a2  s.  com*/
    // delete the last "|"
    builder.deleteCharAt(builder.lastIndexOf("|"));
    builder.append(")\\?.?\\?");
    // finally, this regex may look like
    // "\\?==\\?((utf-8)|(iso-2022-jp)|(shift_jis))\\?.?\\?"
    return builder.toString();
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.locator.AbstractScriptLocator.java

/**
 * Resolves a relative location value against the reference location provided by the currently exectued script.
 * /*ww w  . j a  v  a2 s .c o  m*/
 * @param locationValue
 *            The relative location value to resolve
 * @param referenceValue
 *            The reference location to resolve against. This parameter is primarily used in an informative capacity (e.g. for logging)
 *            while the pathBuilder is the work-item.
 * @param pathBuilder
 *            A builder for the final path that should be manipulated during the resolution. The instance passed should be
 *            pre-initialized with the base path determined from the reference location.
 */
@SuppressWarnings("static-method")
protected void resolveRelativeLocation(final String locationValue, final String referenceValue,
        final StringBuilder pathBuilder) {
    LOGGER.debug("Resolving relativ classpath location {} from reference {}", locationValue, referenceValue);
    int lastSlash = -1;
    int nextSlash = locationValue.indexOf("/");
    boolean descending = false;
    while (nextSlash != -1) {
        final String fragment = locationValue.substring(lastSlash + 1, nextSlash);

        if (fragment.length() != 0) {

            if (fragment.equalsIgnoreCase("..")) {
                if (!descending) {
                    // ascend
                    final int deleteFrom = pathBuilder.lastIndexOf("/");
                    if (deleteFrom == -1) {
                        if (pathBuilder.length() > 0) {
                            pathBuilder.delete(0, pathBuilder.length());
                        } else {
                            LOGGER.warn("Resolving {} from reference {} caused ascension beyond root",
                                    locationValue, referenceValue);
                            // nowhere to ascend to
                            throw new ScriptImportException(
                                    "Unable to ascend out of classpath - context location: [{0}], script location: [{1}]",
                                    new Object[] { referenceValue, locationValue });
                        }
                    } else {
                        pathBuilder.delete(deleteFrom, pathBuilder.length());
                    }
                } else {
                    LOGGER.warn("Cannot ascend after descending in resolution of {} from reference {}",
                            locationValue, referenceValue);
                    // no re-ascension
                    throw new ScriptImportException(
                            "Unable to ascend after already descending - context location: [{0}], script location: [{1}]",
                            new Object[] { referenceValue, locationValue });
                }
            } else if (fragment.equalsIgnoreCase(".")) {
                descending = true;
            } else {
                descending = true;
                pathBuilder.append("/").append(fragment);
            }
        }

        lastSlash = nextSlash;
        nextSlash = locationValue.indexOf('/', lastSlash + 1);
    }

    if (nextSlash == -1 && lastSlash == -1) {
        // no slash found at all
        pathBuilder.append("/");
    }

    pathBuilder.append(lastSlash != -1 ? locationValue.substring(lastSlash) : locationValue);

    LOGGER.debug("Resolved classpath location {} by relative path {} from reference {}",
            new Object[] { pathBuilder, locationValue, referenceValue });
}

From source file:com.gmail.at.faint545.fragments.HistoryFragment.java

private String collectSelectedItems() {
    StringBuilder selectedJobs = new StringBuilder();
    /* Create a string of jobs to delete, separated by commas i.e: job1,job2,job3 */
    for (int position : mSelectedPositions) {
        JSONObject job = mOldJobs.get(position);
        try {//from w ww  .  j a v a 2 s.co  m
            String id = job.getString(SabnzbdConstants.NZOID);
            selectedJobs.append(id).append(",");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return selectedJobs.substring(0, selectedJobs.lastIndexOf(","));
}

From source file:Main.java

/**
 * Builds an XPointer that refers to the given node. If a shorthand pointer
 * (using a schema-determined identifier) cannot be constructed, then a
 * scheme-based pointer is derived that indicates the absolute location path
 * of a node in a DOM document. The location is specified as a scheme-based
 * XPointer having two parts:// w  w w. j  a  v a2 s.c  o m
 * <ul>
 * <li>an xmlns() part that declares a namespace binding context;</li>
 * <li>an xpointer() part that includes an XPath expression using the
 * abbreviated '//' syntax for selecting a descendant node.</li>
 * </ul>
 * 
 * @param node
 *            A node in a DOM document.
 * @return A String containing either a shorthand or a scheme-based pointer
 *         that refers to the node.
 * 
 * @see <a href="http://www.w3.org/TR/xptr-framework/"target="_blank">
 *      XPointer Framework</a>
 * @see <a href="http://www.w3.org/TR/xptr-xmlns/" target="_blank">XPointer
 *      xmlns() Scheme</a>
 * @see <a href="http://www.w3.org/TR/xptr-xpointer/"
 *      target="_blank">XPointer xpointer() Scheme</a>
 */
public static String buildXPointer(Node node) {
    if (null == node) {
        return "";
    }
    StringBuilder xpointer = new StringBuilder();
    if (null != node.getAttributes() && null != node.getAttributes().getNamedItem("id")) {
        String id = node.getAttributes().getNamedItem("id").getNodeValue();
        xpointer.append(node.getLocalName()).append("[@id='").append(id).append("']");
        return xpointer.toString();
    }
    String nsURI = node.getNamespaceURI();
    String nsPrefix = node.getPrefix();
    if (null == nsPrefix)
        nsPrefix = "tns";
    // WARNING: Escaping rules are currently ignored.
    xpointer.append("xmlns(").append(nsPrefix).append("=").append(nsURI).append(")");
    xpointer.append("xpointer((");
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        // Find the element in the list of all similarly named descendants
        // of the document root.
        NodeList elementsByName = node.getOwnerDocument().getElementsByTagNameNS(nsURI, node.getLocalName());
        for (int i = 0; i < elementsByName.getLength(); i++) {
            if (elementsByName.item(i).isSameNode(node)) {
                xpointer.append("//");
                xpointer.append(nsPrefix).append(':').append(node.getLocalName()).append(")[").append(i + 1)
                        .append("])");
                break;
            }
        }
        break;
    case Node.DOCUMENT_NODE:
        xpointer.append("/");
        break;
    case Node.ATTRIBUTE_NODE:
        Attr attrNode = (Attr) node;
        xpointer = new StringBuilder(buildXPointer(attrNode.getOwnerElement()));
        xpointer.insert(xpointer.lastIndexOf(")"), "/@" + attrNode.getName());
        break;
    default:
        xpointer.setLength(0);
        break;
    }
    return xpointer.toString();
}

From source file:org.wso2.carbon.identity.governance.store.InMemoryIdentityDataStore.java

@Override
public void store(UserIdentityClaim userIdentityDTO, UserStoreManager userStoreManager)
        throws IdentityException {

    try {/*from  w ww .j a v a  2  s  .  c o  m*/
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        if (userIdentityDTO != null && userIdentityDTO.getUserName() != null) {
            String userName = userIdentityDTO.getUserName();
            if (userStoreManager instanceof org.wso2.carbon.user.core.UserStoreManager) {
                if (!IdentityUtil.isUserStoreCaseSensitive(
                        (org.wso2.carbon.user.core.UserStoreManager) userStoreManager)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Case insensitive user store found. Changing username from : " + userName
                                + " to : " + userName.toLowerCase());
                    }
                    userName = userName.toLowerCase();
                }
            }

            if (log.isDebugEnabled()) {
                StringBuilder data = new StringBuilder("{");
                if (userIdentityDTO.getUserIdentityDataMap() != null) {
                    for (Map.Entry<String, String> entry : userIdentityDTO.getUserIdentityDataMap()
                            .entrySet()) {
                        data.append("[").append(entry.getKey()).append(" = ").append(entry.getValue())
                                .append("], ");
                    }
                }
                if (data.indexOf(",") >= 0) {
                    data.deleteCharAt(data.lastIndexOf(","));
                }
                data.append("}");
                log.debug("Storing UserIdentityClaimsDO to cache for user: " + userName + " with claims: "
                        + data);
            }

            org.wso2.carbon.user.core.UserStoreManager store = (org.wso2.carbon.user.core.UserStoreManager) userStoreManager;
            String domainName = store.getRealmConfiguration()
                    .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

            String key = domainName + userStoreManager.getTenantId() + userName;

            Cache<String, UserIdentityClaim> cache = getCache();
            if (cache != null) {
                cache.put(key, userIdentityDTO);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error while obtaining tenant ID from user store manager", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:net.dmulloy2.swornrpg.commands.CmdStaffList.java

@Override
public void perform() {
    // Calculate online staff
    Map<String, List<String>> staffMap = new HashMap<>();

    int total = 0;

    for (Player player : Util.getOnlinePlayers()) {
        if (plugin.getPermissionHandler().hasPermission(player, Permission.STAFF)) {
            if (plugin.isVaultEnabled()) {
                String group = plugin.getVaultHandler().getGroup(player);
                if (group != null) {
                    if (!staffMap.containsKey(group)) {
                        staffMap.put(group, new ArrayList<String>());
                    }/*ww w.jav a2s .c  o  m*/

                    staffMap.get(group).add((player.isOp() ? "&b" : "&e") + player.getName());
                }
            } else {
                if (!staffMap.containsKey("staff")) {
                    staffMap.put("staff", new ArrayList<String>());
                }

                staffMap.get("staff").add(player.isOp() ? "&b" : "&e" + player.getName());
            }

            total++;
        }
    }

    List<String> lines = new ArrayList<String>();

    StringBuilder line = new StringBuilder();
    line.append(FormatUtil.format(getMessage("stafflist_header"), total, plugin.getServer().getMaxPlayers()));
    lines.add(line.toString());

    // Specific Group

    String group = "all";
    if (args.length > 0) {
        group = args[0];
    }

    if (staffMap.containsKey(group)) {
        line = new StringBuilder();
        line.append("&3" + WordUtils.capitalize(group) + "&e: ");

        for (String player : staffMap.get(group)) {
            line.append("&e" + player + "&b, ");
        }

        if (line.lastIndexOf("&b, ") >= 0) {
            line.replace(line.lastIndexOf("&"), line.lastIndexOf(" "), "");
        }

        lines.add(line.toString());

        for (String string : lines)
            sendMessage(string);

        return;
    }

    // All online staff

    for (Entry<String, List<String>> entry : staffMap.entrySet()) {
        line = new StringBuilder();
        line.append("&3" + WordUtils.capitalize(entry.getKey()) + "&e: ");

        for (String player : entry.getValue()) {
            line.append("&e" + player + "&b, ");
        }

        if (line.lastIndexOf("&b, ") >= 0) {
            line.replace(line.lastIndexOf("&"), line.lastIndexOf(" "), "");
        }

        lines.add(line.toString());
    }

    for (String string : lines)
        sendMessage(string);
}

From source file:com.ae.apps.tripmeter.fragments.expenses.AddExpenseDialogFragment.java

@NonNull
private TripExpense getTripExpense(ContactVo expenseContributor) throws ExpenseValidationException {
    TripExpense tripExpense = new TripExpense();
    if (TextUtils.isEmpty(mTxtExpenseAmount.getText())) {
        throw new ExpenseValidationException("Please Enter expense amount");
    }/*from  w w w  .j a  v  a  2 s.  c om*/

    // Get selected expense members
    CheckBox checkbox;
    StringBuilder selectedMemberIds = new StringBuilder();
    for (int i = 0; i < mMembersContainer.getChildCount(); i++) {
        if (mMembersContainer.getChildAt(i) instanceof CheckBox) {
            checkbox = (CheckBox) mMembersContainer.getChildAt(i);
            if (checkbox.isChecked()) {
                selectedMemberIds.append(checkbox.getTag()).append(",");
            }
        }
    }
    // Remove the extra "," at the end
    if (selectedMemberIds.length() > 0) {
        selectedMemberIds.deleteCharAt(selectedMemberIds.lastIndexOf(","));
    }

    if (TextUtils.isEmpty(selectedMemberIds)) {
        throw new ExpenseValidationException("Please select at least 1 member for this expense");
    }

    tripExpense.setTripId(trip.getId());
    tripExpense.setMemberIds(selectedMemberIds.toString());

    tripExpense.setAmount(Float.parseFloat(mTxtExpenseAmount.getText().toString()));
    tripExpense.setPaidById(expenseContributor.getId());
    tripExpense.setCategory(mTxtExpenseCategory.getText().toString());
    tripExpense.setNote(mTxtExpenseNote.getText().toString());

    return tripExpense;
}

From source file:org.tonguetied.web.DirectoryViewController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
    final StringBuilder servletPath = new StringBuilder(request.getServletPath());
    if (logger.isDebugEnabled())
        logger.debug("servletPath = " + servletPath);
    if (servletPath.toString().endsWith(suffix))
        servletPath.delete(servletPath.length() - suffix.length(), servletPath.length());

    final String homePath = request.getSession().getServletContext().getRealPath(servletPath.toString());
    if (logger.isDebugEnabled())
        logger.debug("homePath = " + homePath);

    final FileBean baseDirectory = new FileBean(homePath);
    if (logger.isInfoEnabled())
        logger.info("displaying contents of basedir = " + baseDirectory);
    final int lastIndex = servletPath.lastIndexOf("/");
    final String[] parents;
    if (lastIndex > 0)
        parents = servletPath.substring(1, lastIndex).split("/");
    else/*from   ww w  .  j a v  a 2 s .  c om*/
        parents = new String[] {};

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("baseDir", baseDirectory);
    model.put("suffix", suffix);
    model.put("parents", parents);

    return new ModelAndView("export/fileListing", model);
}

From source file:fr.gael.dhus.olingo.v1.V1Processor.java

private URI makeLink(boolean remove_last_segment) throws ODataException {
    URI selfLnk = getServiceRoot();
    StringBuilder sb = new StringBuilder(selfLnk.getPath());

    if (remove_last_segment) {
        // Removes the last segment.
        int lio = sb.lastIndexOf("/");
        while (lio != -1 && lio == sb.length() - 1) {
            sb.deleteCharAt(lio);//from ww  w .  j a v  a2s  .co  m
            lio = sb.lastIndexOf("/");
        }
        if (lio != -1)
            sb.delete(lio + 1, sb.length());

        // Removes the `$links` segment.
        lio = sb.lastIndexOf("$links/");
        if (lio != -1)
            sb.delete(lio, lio + 7);
    } else {
        if (!sb.toString().endsWith("/") && !sb.toString().endsWith("\\")) {
            sb.append("/");
        }
    }
    try {
        URI res = new URI(selfLnk.getScheme(), selfLnk.getUserInfo(), selfLnk.getHost(), selfLnk.getPort(),
                sb.toString(), null, selfLnk.getFragment());
        return res;
    } catch (Exception e) {
        throw new ODataException(e);
    }
}

From source file:net.duckling.ddl.service.resource.dao.ResourceDAOImpl.java

@Override
public int batchDelete(final List<Integer> rids) {
    if (null == rids || rids.isEmpty()) {
        return 0;
    }//from   ww w .  j  a v a 2 s  .  co m
    String sql = "update a1_resource set status='" + LynxConstants.STATUS_DELETE + "' where rid in(";
    int size = rids.size();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < size; i++) {
        sb.append(rids.get(i) + ",");
    }
    sb.replace(sb.lastIndexOf(","), sb.length(), ")");
    sql += sb.toString();
    return this.getJdbcTemplate().update(sql);
}