Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

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

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:org.apache.hms.controller.CommandHandler.java

private void generateClusterPlan(String cmdPath, ClusterCommand cmd)
        throws KeeperException, InterruptedException, IOException {
    String cmdStatusPath = ZookeeperUtil.getCommandStatusPath(cmdPath);
    Stat stat = zk.exists(cmdStatusPath, false);
    if (stat != null) {
        // plan already exists, let's pick up what's left from another controller
        return;// w  w w.  j  a v  a  2s  .c  o  m
    }
    // new create command
    LOG.info("Generate command plan: " + cmdPath);
    String startTime = new Date(System.currentTimeMillis()).toString();
    CommandStatus cmdStatus = new CommandStatus(Status.STARTED, startTime);

    // Setup actions
    List<ActionEntry> actionEntries = new LinkedList<ActionEntry>();

    ClusterManifest cm = ((ClusterCommand) cmd).getClusterManifest();
    cmdStatus.setClusterName(cm.getClusterName());
    NodesManifest nm = cm.getNodes();
    ConfigManifest configM = cm.getConfig();
    for (Action action : configM.getActions()) {
        // Find the host list for this action
        Set<String> hosts;
        if (action.getRole() == null) {
            hosts = convertRolesToHosts(nm, null);
        } else {
            Set<String> role = new HashSet<String>();
            role.add(action.getRole());
            hosts = convertRolesToHosts(nm, role);
        }
        List<HostStatusPair> nodesList = setHostStatus(hosts, Status.UNQUEUED);

        ActionEntry ae = new ActionEntry();
        action.setCmdPath(cmdPath);
        action.setActionId(actionCount.incrementAndGet());
        ae.setHostStatus(nodesList);
        List<ActionDependency> adList = action.getDependencies();
        if (adList != null) {
            for (ActionDependency ad : adList) {
                Set<String> roles = ad.getRoles();
                Set<String> dependentHosts = convertRolesToHosts(nm, roles);
                StringBuilder sb = new StringBuilder();
                List<String> myhosts = new ArrayList<String>();
                for (String host : dependentHosts) {
                    sb.append(CommonConfigurationKeys.ZOOKEEPER_CLUSTER_ROOT_DEFAULT);
                    sb.append("/");
                    sb.append(cm.getClusterName());
                    sb.append("/");
                    sb.append(host);
                    myhosts.add(sb.toString());
                    sb.delete(0, sb.length());
                }
                ad.setHosts(myhosts);
            }
        }

        // If the action is package action resolve the action from software manifest
        if (action instanceof PackageAction) {
            SoftwareManifest sm = cm.getSoftware();
            if (action.getRole() == null) {
                // If no role is defined, install all the software in the software manifest
                PackageInfo[] packages = convertRolesToPackages(sm, null);
                ((PackageAction) action).setPackages(packages);
            } else {
                for (Role role : sm.getRoles()) {
                    if (role.getName().equals(action.getRole())) {
                        PackageInfo[] packages = convertRolesToPackages(sm, action.getRole());
                        ((PackageAction) action).setPackages(packages);
                    }
                }
            }
        }

        ae.setAction(action);
        actionEntries.add(ae);
    }
    commitCommandPlan(cmdStatusPath, cmdStatus, actionEntries);
}

From source file:org.apache.tajo.catalog.store.HiveCatalogStore.java

/**
 * Get list of partitions matching specified filter.
 *
 * For example, consider you have a partitioned table for three columns (i.e., col1, col2, col3).
 * Assume that an user want to give a condition WHERE (col1 ='1' or col1 = '100') and col3 > 20 .
 *
 * Then, the filter string would be written as following:
 *   (col1 =\"1\" or col1 = \"100\") and col3 > 20
 *
 *
 * @param databaseName//from  w w w.j  a v a 2  s . c  o  m
 * @param tableName
 * @param filter
 * @return
 */
private List<PartitionDescProto> getPartitionsFromHiveMetaStore(String databaseName, String tableName,
        String filter) {
    HiveCatalogStoreClientPool.HiveCatalogStoreClient client = null;
    List<PartitionDescProto> partitions = null;
    TableDescProto tableDesc = null;
    List<ColumnProto> parititonColumns = null;

    try {
        partitions = new ArrayList<>();
        client = clientPool.getClient();

        List<Partition> hivePartitions = client.getHiveClient().listPartitionsByFilter(databaseName, tableName,
                filter, (short) -1);

        tableDesc = getTable(databaseName, tableName);
        parititonColumns = tableDesc.getPartition().getExpressionSchema().getFieldsList();

        StringBuilder partitionName = new StringBuilder();
        for (Partition hivePartition : hivePartitions) {
            CatalogProtos.PartitionDescProto.Builder builder = CatalogProtos.PartitionDescProto.newBuilder();
            builder.setPath(hivePartition.getSd().getLocation());

            partitionName.delete(0, partitionName.length());
            for (int i = 0; i < parititonColumns.size(); i++) {
                if (i > 0) {
                    partitionName.append(File.separator);
                }
                partitionName.append(IdentifierUtil.extractSimpleName(parititonColumns.get(i).getName()));
                partitionName.append("=");
                partitionName.append(hivePartition.getValues().get(i));
            }

            builder.setPartitionName(partitionName.toString());

            Map<String, String> params = hivePartition.getParameters();
            if (params != null) {
                if (params.get(StatsSetupConst.TOTAL_SIZE) != null) {
                    builder.setNumBytes(Long.parseLong(params.get(StatsSetupConst.TOTAL_SIZE)));
                }
            }

            partitions.add(builder.build());
        }
    } catch (Exception e) {
        throw new TajoInternalError(e);
    } finally {
        if (client != null) {
            client.release();
        }
    }

    return partitions;
}

From source file:org.alfresco.repo.favourites.FavouritesServiceImpl.java

private void updateFavouriteNodes(String userName, Type type,
        Map<PersonFavouriteKey, PersonFavourite> favouriteNodes) {
    PrefKeys prefKeys = getPrefKeys(type);

    Map<String, Serializable> preferences = new HashMap<String, Serializable>(1);

    StringBuilder values = new StringBuilder();
    for (PersonFavourite node : favouriteNodes.values()) {
        NodeRef nodeRef = node.getNodeRef();

        values.append(nodeRef.toString());
        values.append(",");

        // ISO8601 string format: PreferenceService works with strings only for dates it seems
        StringBuilder sb = new StringBuilder(prefKeys.getAlfrescoPrefKey());
        sb.append(nodeRef.toString());//from   ww w .  j av  a  2  s . c  om
        sb.append(".createdAt");
        String createdAtKey = sb.toString();
        Date createdAt = node.getCreatedAt();
        if (createdAt != null) {
            String createdAtStr = ISO8601DateFormat.format(createdAt);
            preferences.put(createdAtKey, createdAtStr);
        }
    }

    if (values.length() > 1) {
        values.delete(values.length() - 1, values.length());
    }

    preferences.put(prefKeys.getSharePrefKey(), values.toString());
    preferenceService.setPreferences(userName, preferences);
}

From source file:br.com.nordestefomento.jrimum.bopepo.view.ViewerPDF.java

private void setSacado() throws IOException, DocumentException {

    StringBuilder sb = new StringBuilder();
    Sacado sacado = boleto.getTitulo().getSacado();

    if (isNotNull(sacado.getNome())) {
        sb.append(sacado.getNome());//  ww w.  jav  a 2  s.  c  o  m
    }

    if (isNotNull(sacado.getCPRF())) {
        sb.append(", ");

        if (sacado.getCPRF().isFisica()) {
            sb.append("CPF: ");

        } else if (sacado.getCPRF().isJuridica()) {
            sb.append("CNPJ: ");
        }

        sb.append(sacado.getCPRF().getCodigoFormatado());
    }

    form.setField("txtRsSacado", sb.toString());
    form.setField("txtFcSacadoL1", sb.toString());

    // TODO Cdigo em teste
    sb.delete(0, sb.length());
    Endereco endereco = sacado.getEnderecos().iterator().next();

    setEndereco(endereco, "txtFcSacadoL2", "txtFcSacadoL3", sb);
}

From source file:com.untangle.app.web_filter.WebFilterDecisionEngine.java

/**
 * Encode a URL/*from  ww w  .  ja v  a 2s  .c o  m*/
 * 
 * @param domain
 *        The domain
 * @param uri
 *        The URI
 * @return The encoded URL
 */
private static String encodeUrl(String domain, String uri) {
    // Remote trailing dots from domain
    Matcher matcher = trailingDotsPattern.matcher(domain);
    domain = matcher.replaceAll("");

    String url = domain + uri;

    // Remote trailing dots or slashes from URL
    matcher = trailingDotsSlashesPattern.matcher(url);
    url = matcher.replaceAll("");

    StringBuilder qBuilder = new StringBuilder(url);

    int i;
    int lastDot = 0;

    for (i = 0; i < qBuilder.length(); i++) {

        int numCharsAfterThisOne = (qBuilder.length() - i) - 1;

        // Must insert a null escape to divide long spans
        if (i > lastDot + 59) {
            qBuilder.insert(i, "_-0.");
            lastDot = i + 3;
            i += 4;
        }

        if (qBuilder.charAt(i) == '.') {
            lastDot = i;
        }
        // Take care of the rare, but possible case of _- being in the string
        else if (qBuilder.charAt(i) == '_' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '-') {
            qBuilder.replace(i, i + 2, "_-_-");
            i += 4;
        }
        // Convert / to rfc compliant characters _-.
        else if (qBuilder.charAt(i) == '/') {
            qBuilder.replace(i, i + 1, "_-.");
            lastDot = i + 2;
            i += 3;
        }
        // Convert any dots next to each other
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne >= 1 && qBuilder.charAt(i + 1) == '.') {
            qBuilder.replace(i, i + 2, "._-2e");
            i += 5;
        }
        // Convert any dots at the end. (these should have already been stripped but the zvelo implementation has this here)
        else if (qBuilder.charAt(i) == '.' && numCharsAfterThisOne == 0) {
            qBuilder.replace(i, i + 1, "_-2e");
            i += 4;
        }
        // Convert : to _--
        else if (qBuilder.charAt(i) == ':') {
            qBuilder.replace(i, i + 1, "_--");
            i += 3;
        }
        // Drop everything after ? or #
        else if (qBuilder.charAt(i) == '?' || qBuilder.charAt(i) == '#') {
            qBuilder.delete(i, qBuilder.length());
            break;
        }
        // Convert %HEXHEX to encoded form
        else if (qBuilder.charAt(i) == '%' && numCharsAfterThisOne >= 2 && _isHex(qBuilder.charAt(i + 1))
                && _isHex(qBuilder.charAt(i + 2))) {
            //String hexString = new String(new char[] {qBuilder.charAt(i+1), qBuilder.charAt(i+2)});
            //char c = (char)( Integer.parseInt( hexString , 16) );
            //System.out.println("HEX: \"" + hexString +"\" -> \"" + Character.toString(c) + "\"");
            qBuilder.replace(i, i + 1, "_-");
            i += 4; // 2 for length of replacement + 2 for the hex characters
        }
        // Convert % charaters to encoded form
        else if (qBuilder.charAt(i) == '%') {
            qBuilder.replace(i, i + 1, "_-25");
            i += 4;
        }
        // Convert any remaining non-RFC characters.
        else if (!_isRfc(qBuilder.charAt(i))) {
            String replaceStr = String.format("_-%02X", ((byte) qBuilder.charAt(i)));
            qBuilder.replace(i, i + 1, replaceStr);
            i += 4;
        }
    }

    return qBuilder.toString();
}

From source file:com.impetus.client.couchdb.CouchDBClient.java

/**
 * Creates the query.//  www  . j  ava  2 s.  co m
 * 
 * @param interpreter
 *            the interpreter
 * @param m
 *            the m
 * @param q
 *            the q
 * @param _id
 *            the _id
 * @return the string
 * @throws URISyntaxException
 *             the URI syntax exception
 * @throws UnsupportedEncodingException
 *             the unsupported encoding exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClientProtocolException
 *             the client protocol exception
 */
String createQuery(CouchDBQueryInterpreter interpreter, EntityMetadata m, StringBuilder q, String _id)
        throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException {
    if (interpreter.isAggregation()) {
        _id = CouchDBConstants.URL_SEPARATOR + m.getSchema().toLowerCase() + CouchDBConstants.URL_SEPARATOR
                + CouchDBConstants.DESIGN + CouchDBConstants.AGGREGATIONS + CouchDBConstants.VIEW
                + interpreter.getAggregationType();
        if (interpreter.getAggregationColumn() != null) {
            q.append("key=");
            q.append("\"" + interpreter.getAggregationColumn() + "_" + m.getTableName() + "\"");

        } else {
            q.append("key=" + "\"" + CouchDBConstants.ALL + "_" + m.getTableName() + "\"");
        }
        q.append("&group=true");
    } else if (!interpreter.isRangeQuery() && interpreter.getOperator() != null
            && interpreter.getOperator().equalsIgnoreCase("AND")) {
        StringBuilder viewName = new StringBuilder();
        List<String> columns = new ArrayList<String>();
        q.append("key=[");
        for (String columnName : interpreter.getKeyValues().keySet()) {
            viewName.append(columnName + "AND");
            q.append(CouchDBUtils.appendQuotes(interpreter.getKeyValues().get(columnName)));
            q.append(",");
            columns.add(columnName);
        }
        q.deleteCharAt(q.toString().lastIndexOf(","));
        q.append("]");
        viewName.delete(viewName.toString().lastIndexOf("AND"), viewName.toString().lastIndexOf("AND") + 3);
        _id = _id + viewName.toString();
        CouchDBUtils.createDesignDocumentIfNotExist(httpClient, httpHost, gson, m.getTableName(), m.getSchema(),
                viewName.toString(), columns);
    } else if (interpreter.getKeyValues() != null) {
        if (interpreter.getStartKeyValue() != null || interpreter.getEndKeyValue() != null) {
            String queryString = null;
            if (interpreter.getStartKeyValue() != null) {
                queryString = "startkey=" + CouchDBUtils.appendQuotes(interpreter.getStartKeyValue());
                q.append(queryString);
            }
            if (interpreter.getEndKeyValue() != null) {
                if (interpreter.getStartKeyValue() != null) {
                    q.append("&");
                }
                queryString = "endkey=" + CouchDBUtils.appendQuotes(interpreter.getEndKeyValue());
                q.append(queryString);
                if (interpreter.isIncludeLastKey()) {
                    q.append("&inclusive_end=");
                    q.append(true);
                }
            }
        } else if (interpreter.getKeyValue() != null) {
            q.append("key=" + CouchDBUtils.appendQuotes(interpreter.getKeyValue()));
        }
        _id = _id + interpreter.getKeyName();
    } else if (interpreter.getColumns() != null && interpreter.getColumns().length != 0) {
        _id += CouchDBConstants.FIELDS;
        q.append("keys=[");
        for (String column : interpreter.getColumns()) {
            q.append("\"" + column + "\",");
        }
        q.setCharAt(q.length() - 1, ']');
    } else {
        _id = _id + "all";
    }

    return _id;
}

From source file:br.com.nordestefomento.jrimum.bopepo.view.ViewerPDF.java

private void setSacadorAvalista() throws IOException, DocumentException {

    if (boleto.getTitulo().hasSacadorAvalista()) {

        SacadorAvalista sacadorAvalista = boleto.getTitulo().getSacadorAvalista();

        StringBuilder sb = new StringBuilder();

        if (isNotNull(sacadorAvalista.getNome())) {
            sb.append(sacadorAvalista.getNome());
        }//  ww w.  j a  va 2s  .c o  m

        if (isNotNull(sacadorAvalista.getCPRF())) {

            sb.append(", ");

            if (sacadorAvalista.getCPRF().isFisica()) {
                sb.append("CPF: ");

            } else if (sacadorAvalista.getCPRF().isJuridica()) {
                sb.append("CNPJ: ");
            }

            sb.append(sacadorAvalista.getCPRF().getCodigoFormatado());
        }

        form.setField("txtFcSacadorAvalistaL1", sb.toString());

        // TODO Cdigo em teste
        sb.delete(0, sb.length());
        Endereco endereco = sacadorAvalista.getEnderecos().iterator().next();

        setEndereco(endereco, "txtFcSacadorAvalistaL2", "txtFcSacadorAvalistaL3", sb);
    }
}

From source file:com.virtusa.akura.common.controller.ExamSubjectController.java

/**
 * Updates a relevant object of exam subject.
 * /*from ww w .  j  a  v a2 s .c o m*/
 * @param model - a hashMap contains the examSubject related data.
 * @param examSubject - the exam subject.
 * @param result - the error results.
 * @param request - an instance of HttpServletRequest.
 * @return - the view to be redirected.
 * @throws AkuraAppException - The exception details that occurred when processing.
 */
@RequestMapping(EDIT_EXAM_SUBJECTS_HTM)
public String editExamSubject(final ModelMap model,
        @ModelAttribute(MODEL_ATT_EXAM_SUBJECT) final ExamSubject examSubject, final BindingResult result,
        HttpServletRequest request) throws AkuraAppException {

    String examDescription = request.getParameter(EXAM_DESCRIPTION);
    Exam exam = commonService.getExamByExamName(examDescription);
    List<ExamSubject> selectedSubjectsList = commonService.findSubjectsByExam(examDescription);
    List<Integer> selectedSubjectsIdList = new ArrayList<Integer>();

    List<String> allClasses = new ArrayList<String>();
    boolean isFirst = true;
    StringBuilder classes = new StringBuilder();
    for (ExamSubject examSubj : selectedSubjectsList) {
        selectedSubjectsIdList.add(examSubj.getSubject().getSubjectId());
    }
    List<?> subjectsListByExam = commonService.getSubjectListByExam(exam.getGradeId());
    Iterator<?> iterator = subjectsListByExam.iterator();
    int indexSubjectId = 1;
    while (iterator.hasNext()) {
        Object[] object = (Object[]) iterator.next();
        int subjectId = (Integer) object[indexSubjectId];
        if (!selectedSubjectsIdList.contains(subjectId)) {
            classes.append((String) object[0]);
            classes.append(STRING_HIPHEN);
            classes.append(subjectId);
            if (isFirst) {
                allClasses.add(classes.toString()); // no comma
                isFirst = false;
            } else {
                allClasses.add(classes.toString());
            }
            classes.delete(0, classes.length());
        }
    }

    model.addAttribute(SELECTED_DESCRIPTION, examDescription);
    model.addAttribute(SELECTED_SUBJECTS_LIST, selectedSubjectsList);
    model.addAttribute(AVAILABLE_SUBJECTS_LIST, allClasses);
    return VIEW_GET_MANAGE_EXAM_SUBJECT;
}

From source file:org.apache.solr.servlet.HttpSolrCall.java

private AuthorizationContext getAuthCtx() {

    String resource = getPath();//from w w  w. j a v a  2s.  c  om

    SolrParams params = getQueryParams();
    final ArrayList<CollectionRequest> collectionRequests = new ArrayList<>();
    if (getCollectionsList() != null) {
        for (String collection : getCollectionsList()) {
            collectionRequests.add(new CollectionRequest(collection));
        }
    }

    // Extract collection name from the params in case of a Collection Admin request
    if (getPath().equals("/admin/collections")) {
        if (CREATE.isEqual(params.get("action")) || RELOAD.isEqual(params.get("action"))
                || DELETE.isEqual(params.get("action")))
            collectionRequests.add(new CollectionRequest(params.get("name")));
        else if (params.get(COLLECTION_PROP) != null)
            collectionRequests.add(new CollectionRequest(params.get(COLLECTION_PROP)));
    }

    // Handle the case when it's a /select request and collections are specified as a param
    if (resource.equals("/select") && params.get("collection") != null) {
        collectionRequests.clear();
        for (String collection : params.get("collection").split(",")) {
            collectionRequests.add(new CollectionRequest(collection));
        }
    }

    // Populate the request type if the request is select or update
    if (requestType == RequestType.UNKNOWN) {
        if (resource.startsWith("/select") || resource.startsWith("/get"))
            requestType = RequestType.READ;
        if (resource.startsWith("/update"))
            requestType = RequestType.WRITE;
    }

    // There's no collection explicitly mentioned, let's try and extract it from the core if one exists for
    // the purpose of processing this request.
    if (getCore() != null && (getCollectionsList() == null || getCollectionsList().size() == 0)) {
        collectionRequests.add(new CollectionRequest(getCore().getCoreDescriptor().getCollectionName()));
    }

    if (getQueryParams().get(COLLECTION_PROP) != null)
        collectionRequests.add(new CollectionRequest(getQueryParams().get(COLLECTION_PROP)));

    return new AuthorizationContext() {
        @Override
        public SolrParams getParams() {
            return solrReq.getParams();
        }

        @Override
        public Principal getUserPrincipal() {
            return getReq().getUserPrincipal();
        }

        @Override
        public String getHttpHeader(String s) {
            return getReq().getHeader(s);
        }

        @Override
        public Enumeration getHeaderNames() {
            return getReq().getHeaderNames();
        }

        @Override
        public List<CollectionRequest> getCollectionRequests() {
            return collectionRequests;
        }

        @Override
        public RequestType getRequestType() {
            return requestType;
        }

        public String getResource() {
            return path;
        }

        @Override
        public String getHttpMethod() {
            return getReq().getMethod();
        }

        @Override
        public Object getHandler() {
            return _getHandler();
        }

        @Override
        public String toString() {
            StringBuilder response = new StringBuilder("userPrincipal: [").append(getUserPrincipal())
                    .append("]").append(" type: [").append(requestType.toString()).append("], collections: [");
            for (CollectionRequest collectionRequest : collectionRequests) {
                response.append(collectionRequest.collectionName).append(", ");
            }
            if (collectionRequests.size() > 0)
                response.delete(response.length() - 1, response.length());

            response.append("], Path: [").append(resource).append("]");
            response.append(" path : ").append(path).append(" params :").append(solrReq.getParams());
            return response.toString();
        }

        @Override
        public String getRemoteAddr() {
            return getReq().getRemoteAddr();
        }

        @Override
        public String getRemoteHost() {
            return getReq().getRemoteHost();
        }
    };

}