List of usage examples for java.lang StringBuilder delete
@Override public StringBuilder delete(int start, int end)
From source file:de.ingrid.interfaces.csw.domain.filter.impl.LuceneFilterParser.java
/** * Build a piece of Lucene query with the specified Logical filter. * * @param logicOpsEl//from w w w. ja v a 2 s. co m * @return SpatialQuery * @throws CSWFilterException */ private SpatialQuery processLogicalOperator(JAXBElement<? extends LogicOpsType> logicOpsEl) throws CSWFilterException { List<SpatialQuery> subQueries = new ArrayList<SpatialQuery>(); StringBuilder queryBuilder = new StringBuilder(); List<Filter> filters = new ArrayList<Filter>(); String operator = logicOpsEl.getName().getLocalPart(); LogicOpsType logicOps = logicOpsEl.getValue(); if (logicOps instanceof BinaryLogicOpType) { BinaryLogicOpType binary = (BinaryLogicOpType) logicOps; queryBuilder.append('('); // process comparison operators: PropertyIsLike, IsNull, IsBetween, // ... for (JAXBElement<? extends ComparisonOpsType> el : binary.getComparisonOps()) { queryBuilder.append(this.processComparisonOperator(el)); queryBuilder.append(" ").append(operator.toUpperCase()).append(" "); } // process logical operators like AND, OR, ... for (JAXBElement<? extends LogicOpsType> el : binary.getLogicOps()) { boolean writeOperator = true; SpatialQuery sq = this.processLogicalOperator(el); String subQuery = sq.getQuery(); Filter subFilter = sq.getSpatialFilter(); // if the sub spatial query contains both term search and // spatial search we create a subQuery if ((subFilter != null && !subQuery.equals(defaultField)) || sq.getSubQueries().size() != 0 || (sq.getLogicalOperator() == SerialChainFilter.NOT && sq.getSpatialFilter() == null)) { subQueries.add(sq); writeOperator = false; } else { if (subQuery.equals("")) { writeOperator = false; } else { queryBuilder.append(subQuery); } if (subFilter != null) { filters.add(subFilter); } } if (writeOperator) { queryBuilder.append(" ").append(operator.toUpperCase()).append(" "); } else { writeOperator = true; } } // process spatial constraint : BBOX, Beyond, Overlaps, ... for (JAXBElement<? extends SpatialOpsType> el : binary.getSpatialOps()) { // for the spatial filter we don't need to write into the Lucene // query filters.add(this.processSpatialOperator(el)); } // remove the last Operator and add a ') ' int pos = queryBuilder.length() - (operator.length() + 2); if (pos > 0) { queryBuilder.delete(queryBuilder.length() - (operator.length() + 2), queryBuilder.length()); } queryBuilder.append(')'); } else if (logicOps instanceof UnaryLogicOpType) { UnaryLogicOpType unary = (UnaryLogicOpType) logicOps; // process comparison operator: PropertyIsLike, IsNull, IsBetween, // ... if (unary.getComparisonOps() != null) { queryBuilder.append(this.processComparisonOperator(unary.getComparisonOps())); } // process spatial constraint : BBOX, Beyond, Overlaps, ... else if (unary.getSpatialOps() != null) { filters.add(this.processSpatialOperator(unary.getSpatialOps())); } // process logical Operators like AND, OR, ... else if (unary.getLogicOps() != null) { SpatialQuery sq = this.processLogicalOperator(unary.getLogicOps()); String subQuery = sq.getQuery(); Filter subFilter = sq.getSpatialFilter(); if ((sq.getLogicalOperator() == SerialChainFilter.OR && subFilter != null && !subQuery.equals(defaultField)) || (sq.getLogicalOperator() == SerialChainFilter.NOT)) { subQueries.add(sq); } else { if (!subQuery.equals("")) { queryBuilder.append(subQuery); } if (subFilter != null) { filters.add(sq.getSpatialFilter()); } } } } String query = queryBuilder.toString(); if (query.equals("()")) { query = ""; } int logicalOperand = SerialChainFilter.valueOf(operator); Filter spatialFilter = this.getSpatialFilterFromList(logicalOperand, filters, query); SpatialQuery response = new SpatialQuery(query, spatialFilter, logicalOperand); response.setSubQueries(subQueries); return response; }
From source file:module.mailtracking.presentationTier.MailTrackingAction.java
private String serializeAjaxFilterResponseForReceivedMail(String sEcho, Integer iTotalRecords, Integer iTotalDisplayRecords, List<CorrespondenceEntry> limitedEntries, HttpServletRequest request) { StringBuilder stringBuilder = new StringBuilder("{"); stringBuilder.append("\"sEcho\": ").append(sEcho).append(", \n"); stringBuilder.append("\"iTotalRecords\": ").append(iTotalRecords).append(", \n"); stringBuilder.append("\"iTotalDisplayRecords\": ").append(iTotalDisplayRecords).append(", \n"); stringBuilder.append("\"aaData\": ").append("[ \n"); for (CorrespondenceEntry entry : limitedEntries) { stringBuilder.append("[ \"").append(entry.getReference()).append("\", "); stringBuilder.append("\"").append(entry.getWhenReceived().toString("dd/MM/yyyy")).append("\", "); stringBuilder.append("\"").append(escapeQuotes(entry.getSender())).append("\", "); stringBuilder.append("\"").append(escapeQuotes(entry.getSenderLetterNumber())).append("\", "); stringBuilder.append("\"").append(escapeQuotes(entry.getSubject())).append("\", "); stringBuilder.append("\"").append(escapeQuotes(entry.getRecipient())).append("\", "); stringBuilder.append("\"") .append(entry.isUserAbleToView(Authenticate.getUser()) ? generateLinkForCorrespondenceEntryView(request, entry) : "permission_not_granted") .append(","); stringBuilder.append(entry.isUserAbleToEdit(Authenticate.getUser()) && entry.isActive() ? generateLinkForCorrespondenceEntryEdition(request, entry) : "permission_not_granted").append(","); stringBuilder.append(entry.isUserAbleToDelete(Authenticate.getUser()) && entry.isActive() ? generateLinkForCorrespondenceEntryRemoval(request, entry) : "permission_not_granted").append(","); stringBuilder.append(entry.isUserAbleToViewMainDocument(Authenticate.getUser()) ? generateLinkForCorrespondenceEntryMainDocument(request, entry) : "permission_not_granted").append(","); stringBuilder.append(entry.isUserAbleToCopyEntry(Authenticate.getUser()) ? generateLinkForCorrespondenceEntryCopy(request, entry) : "permission_not_granted").append("\","); stringBuilder.append("\"").append(entry.isActive()).append("\" ], "); }//ww w . j ava 2 s. c om stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length()); stringBuilder.append(" ]\n }"); return stringBuilder.toString(); }
From source file:com.amaze.carbonfilemanager.activities.MainActivity.java
@Override public void onConnected(Bundle bundle) { if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient); Person.Image personImage; Person.Cover.CoverPhoto personCover; try {//from ww w . java2 s . c om personImage = currentPerson.getImage(); personCover = currentPerson.getCover().getCoverPhoto(); } catch (Exception e) { personCover = null; personImage = null; } if (personCover != null && personImage != null) { String imgUrl = personImage.getUrl(); // getting full size image StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(imgUrl); stringBuilder.delete(imgUrl.length() - 6, imgUrl.length()); Log.d("G+", stringBuilder.toString()); mGoogleName.setText(currentPerson.getDisplayName()); mGoogleId.setText(accountName); // setting cover pic mImageLoader.get(personCover.getUrl(), new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { drawerHeaderParent.setBackgroundColor(Color.parseColor("#ffffff")); if (SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { drawerHeaderView.setBackground(new BitmapDrawable(response.getBitmap())); } else drawerHeaderView.setBackgroundDrawable(new BitmapDrawable(response.getBitmap())); } @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, getString(R.string.no_cover_photo), Toast.LENGTH_LONG) .show(); } }); // setting profile pic mImageLoader.get(stringBuilder.toString(), new ImageLoader.ImageListener() { @Override public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { drawerProfilePic.setImageBitmap(response.getBitmap()); drawerProfilePic.setVisibility(View.VISIBLE); } @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, getString(R.string.no_profile_pic), Toast.LENGTH_LONG) .show(); } }); } else { Toast.makeText(this, getResources().getText(R.string.no_cover_photo), Toast.LENGTH_SHORT).show(); drawerHeaderView.setBackgroundResource(R.drawable.amaze_header); drawerHeaderParent.setBackgroundColor( getColorPreference().getColor(ColorUsage.getPrimary(MainActivity.currentTab))); } } }
From source file:net.storyspace.StorySpace.java
/** * Common backend for {@link #bulkShow(List)} and * {@link #bulkShowById(List)}./*from ww w . j a va 2 s.com*/ * * TODO what happens if an id or name is invalid or for a suspended bot * account? * * @param stringOrLong * @param screenNamesOrIds */ private List<User> bulkShow2(Class stringOrNumber, List screenNamesOrIds) { int batchSize = 100; ArrayList<User> users = new ArrayList<StorySpace.User>(screenNamesOrIds.size()); for (int i = 0; i < screenNamesOrIds.size(); i += batchSize) { StringBuilder names = new StringBuilder(); for (int si = i, n = Math.min(i + batchSize, screenNamesOrIds.size()); si < n; si++) { names.append(screenNamesOrIds.get(si)); names.append(","); } // pop final , names.delete(names.length() - 1, names.length()); String var = stringOrNumber == String.class ? "screen_name" : "user_id"; Map<String, String> vars = asMap(var, names); try { String json = http.getPage(StorySpace_URL + "/users/lookup.json", vars, http.canAuthenticate()); List<User> usersi = User.getUsers(json); users.addAll(usersi); } catch (StorySpaceException e) { // stop here break; } finally { updateRateLimits(KRequestType.SHOW_USER); } } return users; }
From source file:com.github.fauu.natrank.service.MatchDataImportServiceImpl.java
@Override public List<Match> createMatches(ProcessedMatchData matchData) throws DataAccessException { List<Match> newMatches = new LinkedList<>(); List<MatchType> types = matchTypeRepository.findAll(); List<City> cities = cityRepository.findAll(); List<Country> countries = countryRepository.findAll(); StringBuilder resultExtraBuilder = new StringBuilder(30); for (ParsedRawMatchDatum intMatch : matchData.getMatches()) { Match newMatch = new Match(); newMatch.setDate(intMatch.getDate()); for (MatchType type : types) { if (type.getFifaName().equals(intMatch.getType())) { newMatch.setType(type);/* w ww. ja va 2s.c o m*/ break; } } for (City city : cities) { if (city.getName().equals(intMatch.getCity())) { newMatch.setCity(city); break; } } for (Country country : countries) { if (country.getName().equals(intMatch.getTeam1())) { newMatch.setTeam1(country.getTeam()); } else if (country.getName().equals(intMatch.getTeam2())) { newMatch.setTeam2(country.getTeam()); } if ((newMatch.getTeam1() != null) && (newMatch.getTeam2() != null)) { break; } } String fullResult = intMatch.getResult(); Pattern resultPattern = Pattern .compile("(\\d+):(\\d+)(?:\\s(a\\.e\\.t\\.))?(?:\\s(\\(\\d+:\\d+(?:,\\s\\d+:\\d+)?\\)))?" + "(?:\\s(\\d+):(\\d+)\\sPSO)?"); Matcher resultMatcher = resultPattern.matcher(fullResult); int team1Goals = 0; int team2Goals = 0; boolean extraTime = false; String resultsOnGameBreaks = null; int penTeam1Goals = 0; int penTeam2Goals = 0; if (resultMatcher.matches()) { if ((resultMatcher.group(1) != null) && (resultMatcher.group(2) != null)) { team1Goals = Integer.parseInt(resultMatcher.group(1)); team2Goals = Integer.parseInt(resultMatcher.group(2)); } else { // TODO: Should not happen, log this } extraTime = (resultMatcher.group(3) != null) ? true : false; resultsOnGameBreaks = resultMatcher.group(4); if ((resultMatcher.group(5) != null) && (resultMatcher.group(6) != null)) { penTeam1Goals = Integer.parseInt(resultMatcher.group(5)); penTeam2Goals = Integer.parseInt(resultMatcher.group(6)); } } else { // TODO: Should not happen, log this } newMatch.setTeam1Goals(team1Goals); newMatch.setTeam2Goals(team2Goals); if (newMatch.getTeam1().isCityHomeForDate(newMatch.getCity(), newMatch.getDate())) { newMatch.setHomeTeam(newMatch.getTeam1()); } else if (newMatch.getTeam2().isCityHomeForDate(newMatch.getCity(), newMatch.getDate())) { newMatch.setHomeTeam(newMatch.getTeam2()); } else { // TODO: Should not happen, log this } resultExtraBuilder.delete(0, resultExtraBuilder.length()); if (extraTime) { resultExtraBuilder.append("AET"); resultExtraBuilder.append(' '); } if (resultsOnGameBreaks != null) { resultExtraBuilder.append(resultsOnGameBreaks); resultExtraBuilder.append(' '); } if (penTeam1Goals > 0 || penTeam2Goals > 0) { resultExtraBuilder.append(' '); resultExtraBuilder.append(penTeam1Goals); resultExtraBuilder.append(':'); resultExtraBuilder.append(penTeam2Goals); resultExtraBuilder.append(" PEN"); newMatch.setPenaltyShootout(true); } else { newMatch.setPenaltyShootout(false); } if (!newMatch.isPenaltyShootout()) { if (team1Goals > team2Goals) { newMatch.setWinnerTeam(newMatch.getTeam1()); } else if (team1Goals < team2Goals) { newMatch.setWinnerTeam(newMatch.getTeam2()); } else { newMatch.setWinnerTeam(null); } } else { if (penTeam1Goals > penTeam2Goals) { newMatch.setWinnerTeam(newMatch.getTeam1()); } else { newMatch.setWinnerTeam(newMatch.getTeam2()); } } newMatch.setResultExtra(resultExtraBuilder.toString()); newMatches.add(newMatch); } return newMatches; }
From source file:com.impetus.client.cassandra.CassandraClientBase.java
/** * Return update query string for given entity intended for counter column * family./*w w w. jav a2s . c o m*/ * * @param entityMetadata * the entity metadata * @param entity * the entity * @param cassandra_client * the cassandra_client * @param rlHolders * the rl holders * @return the list */ protected List<String> createUpdateQueryForCounter(EntityMetadata entityMetadata, Object entity, Cassandra.Client cassandra_client, List<RelationHolder> rlHolders) { Map<String, String> builders = new HashMap<String, String>(); CQLTranslator translator = new CQLTranslator(); Object rowId = PropertyAccessorHelper.getId(entity, entityMetadata); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(entityMetadata.getPersistenceUnit()); EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz()); Set<Attribute> attributes = entityType.getAttributes(); for (Attribute attrib : attributes) { if (!entityMetadata.getIdAttribute().getName().equals(attrib.getName()) && !metaModel.isEmbeddable(attrib.getJavaType()) && !attrib.isAssociation()) { String tableName = ((AbstractAttribute) attrib).getTableName() != null ? ((AbstractAttribute) attrib).getTableName() : entityMetadata.getTableName(); String queryString = builders.get(tableName); StringBuilder builder; if (queryString == null) { builder = new StringBuilder(); } else { builder = new StringBuilder(queryString); } translator.buildSetClauseForCounters(builder, ((AbstractAttribute) attrib).getJPAColumnName(), PropertyAccessorHelper.getObject(entity, attrib.getName())); builders.put(tableName, builder.toString()); } } for (RelationHolder rl : rlHolders) { translator.buildSetClauseForCounters(new StringBuilder(builders.get(entityMetadata.getTableName())), rl.getRelationName(), rl.getRelationValue()); } for (String tableName : builders.keySet()) { StringBuilder builder = new StringBuilder(builders.get(tableName)); String update_Query = translator.UPDATE_QUERY; update_Query = StringUtils.replace(update_Query, CQLTranslator.COLUMN_FAMILY, translator.ensureCase(new StringBuilder(), tableName, false).toString()); // strip last "," clause. builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length()); builder.append(CQLTranslator.ADD_WHERE_CLAUSE); onWhereClause(entityMetadata, rowId, translator, builder, metaModel, entityMetadata.getIdAttribute()); // strip last "AND" clause. builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length()); StringBuilder queryBuilder = new StringBuilder(update_Query); queryBuilder.append(CQLTranslator.ADD_SET_CLAUSE); queryBuilder.append(builder); if (log.isDebugEnabled()) { log.debug("Returning update query {}.", queryBuilder.toString()); } builders.put(tableName, queryBuilder.toString()); } return new ArrayList(builders.values()); }
From source file:com.impetus.client.cassandra.schemamanager.CassandraSchemaManager.java
/** * Sets the column family properties./* w ww .j a va2s . c o m*/ * * @param cfDef * the cf def * @param cfProperties * the c f properties * @param builder * the builder */ private void setColumnFamilyProperties(CfDef cfDef, Properties cfProperties, StringBuilder builder) { if ((cfDef != null && cfProperties != null) || (builder != null && cfProperties != null)) { if (builder != null) { builder.append(CQLTranslator.WITH_CLAUSE); } onSetKeyValidation(cfDef, cfProperties, builder); onSetCompactionStrategy(cfDef, cfProperties, builder); onSetComparatorType(cfDef, cfProperties, builder); onSetSubComparator(cfDef, cfProperties, builder); // onSetReplicateOnWrite(cfDef, cfProperties, builder); onSetCompactionThreshold(cfDef, cfProperties, builder); onSetComment(cfDef, cfProperties, builder); onSetTableId(cfDef, cfProperties, builder); onSetGcGrace(cfDef, cfProperties, builder); onSetCaching(cfDef, cfProperties, builder); onSetBloomFilter(cfDef, cfProperties, builder); onSetRepairChance(cfDef, cfProperties, builder); onSetReadRepairChance(cfDef, cfProperties, builder); // Strip last AND clause. if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.AND_CLAUSE)) { builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length()); // builder.deleteCharAt(builder.length() - 2); } // Strip last WITH clause. if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.WITH_CLAUSE)) { builder.delete(builder.lastIndexOf(CQLTranslator.WITH_CLAUSE), builder.length()); // builder.deleteCharAt(builder.length() - 2); } } }
From source file:com.gtwm.pb.model.manageData.DataManagement.java
/** * TODO: perhaps move this static method to a more appropriate class * //from w w w .j av a 2s .c o m * @param shortTitle * If true, return only the first part of the title */ public static String buildEventTitle(BaseReportInfo report, DataRowInfo reportDataRow, boolean shortTitle) { // ignore any date fields other than the one used for specifying // the event date // ignore any blank fields // for numeric and boolean fields, include the field title StringBuilder eventTitleBuilder = new StringBuilder(); int fieldCount = 0; REPORT_FIELD_LOOP: for (ReportFieldInfo reportField : report.getReportFields()) { BaseField baseField = reportField.getBaseField(); DataRowFieldInfo dataRowField = reportDataRow.getValue(baseField); String displayValue = dataRowField.getDisplayValue(); if (displayValue.equals("")) { continue REPORT_FIELD_LOOP; } if (baseField.getDbType().equals(DatabaseFieldType.TIMESTAMP) || baseField.equals(baseField.getTableContainingField().getPrimaryKey())) { continue REPORT_FIELD_LOOP; } switch (baseField.getDbType()) { case BOOLEAN: boolean reportFieldTrue = Helpers.valueRepresentsBooleanTrue(dataRowField.getKeyValue()); if (reportFieldTrue) { eventTitleBuilder.append(reportField.getFieldName() + ", "); fieldCount++; } break; case INTEGER: case FLOAT: eventTitleBuilder.append(reportField.getFieldName()).append(" = ").append(displayValue + ", "); fieldCount++; break; case SERIAL: eventTitleBuilder.append(reportField.getFieldName()).append(" = ") .append(dataRowField.getKeyValue() + ", "); fieldCount++; break; default: eventTitleBuilder.append(displayValue + ", "); fieldCount++; } if (shortTitle && (fieldCount > 3)) { break REPORT_FIELD_LOOP; } } int titleLength = eventTitleBuilder.length(); if (titleLength > 1) { eventTitleBuilder.delete(eventTitleBuilder.length() - 2, eventTitleBuilder.length()); } String eventTitle = eventTitleBuilder.toString(); return eventTitle; }