List of usage examples for java.lang StringBuilder indexOf
@Override public int indexOf(String str)
From source file:com.manydesigns.portofino.pageactions.crud.AbstractCrudAction.java
/** * If a search has been executed, appends a URL-encoded String representation of the search criteria * to the given StringBuilder, as a GET parameter. The StringBuilder's contents are modified. * @param sb the base string./*w w w.j a v a 2 s. c o m*/ * @return sb. */ protected StringBuilder appendSearchStringParamIfNecessary(StringBuilder sb) { String searchStringParam = getEncodedSearchStringParam(); if (searchStringParam != null) { if (sb.indexOf("?") == -1) { sb.append('?'); } else { sb.append('&'); } sb.append(searchStringParam); } return sb; }
From source file:oscar.form.study.hsfo2.pageUtil.XMLTransferUtil.java
private String getPatientName(String xmlText, String location) { StringBuilder body = new StringBuilder(xmlText); String a1 = body.substring(0, body.indexOf(location)); String a2 = a1.substring(a1.lastIndexOf("txt_Surname value")); String surname = a2.substring(19, a2.indexOf("signedWhen") - 2); String a3 = a2.substring(a2.indexOf("txt_GivenNames value")); String givenname = a3.substring(22, a3.indexOf("signedWhen") - 2); return givenname + " " + surname; }
From source file:mondrian.test.loader.MondrianFoodMartLoader.java
private StringBuilder insertSchema(StringBuilder sb, String toFind, boolean mandatory, boolean insertBefore) { int pos = sb.indexOf(toFind); if (pos < 0) { if (mandatory) { throw new RuntimeException("insert.sql error: No insert clause in " + sb.toString()); } else {/* www.ja v a2s .co m*/ return sb; } } StringBuilder insertSb = new StringBuilder(); if (insertBefore) { insertSb.append(sb.substring(0, pos)).append(toFind).append(quoteId(schema)).append(".") .append(sb.substring(pos + toFind.length())); } else { insertSb.append(sb.substring(0, pos)).append(quoteId(schema)).append(".").append(toFind) .append(sb.substring(pos + toFind.length())); } return insertSb; }
From source file:edu.usu.sdl.openstorefront.service.PersistenceService.java
public long countByExample(QueryByExample queryByExample) { long count = 0; StringBuilder queryString = new StringBuilder(); if (QueryType.SELECT.equals(queryByExample.getQueryType())) { queryByExample.setQueryType(QueryType.COUNT); }/* w w w . ja va 2s.c o m*/ switch (queryByExample.getQueryType()) { case COUNT: queryString.append("select count(*) "); break; case COUNT_DISTINCT: queryString.append("select count(distinct(").append(queryByExample.getDistinctField()).append(") "); break; default: throw new OpenStorefrontRuntimeException("Query Type unsupported: " + queryByExample.getQueryType(), "Only supports Count types"); } queryString.append("from ").append(queryByExample.getExample().getClass().getSimpleName()); Map<String, Object> mappedParams = new HashMap<>(); String whereClause = generateWhereClause(queryByExample.getExample()); if (StringUtils.isNotBlank(whereClause)) { queryString.append(" where ").append(whereClause); mappedParams.putAll(mapParameters(queryByExample.getExample())); } queryByExample.getExtraWhereCauses().forEach(item -> { SpecialOperatorModel special = (SpecialOperatorModel) item; String extraWhere = generateWhereClause(special.getExample(), new ComplexFieldStack(), special.getGenerateStatementOption()); if (StringUtils.isNotBlank(extraWhere)) { if (queryString.indexOf(" where ") != -1) { queryString.append(" AND "); } else { queryString.append(" where "); } queryString.append(extraWhere); mappedParams.putAll(mapParameters(special.getExample(), new ComplexFieldStack(), special.getGenerateStatementOption())); } }); OObjectDatabaseTx db = getConnection(); try { List<ODocument> documents = db.command(new OCommandSQL(queryString.toString())).execute(mappedParams); if (documents.isEmpty() == false) { count = documents.get(0).field("count"); } } finally { closeConnection(db); } return count; }
From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java
/** * {@inheritDoc}// w w w. j a v a 2 s. com */ public String replaceSystemValues(String inString) { UserDirectoryService userDirectoryService = org.sakaiproject.user.cover.UserDirectoryService.getInstance(); Session s = SessionManager.getCurrentSession(); User user = userDirectoryService.getCurrentUser(); String worksiteId = ToolManager.getCurrentPlacement().getContext(); // current site id Site site = getCurrentWorksite(worksiteId); Map map = new HashMap(); map.put("{userid}", Validator.escapeSql(s.getUserId())); //system values are stored in session if report is scheduled through quartz if (s.getAttribute("toolid") == null) { UserDirectoryService dirServ = org.sakaiproject.user.cover.UserDirectoryService.getInstance(); User u = dirServ.getCurrentUser(); map.put("{userdisplayname}", Validator.escapeSql(u.getDisplayName())); map.put("{useremail}", Validator.escapeSql(u.getEmail())); map.put("{userfirstname}", Validator.escapeSql(u.getFirstName())); map.put("{userlastname}", Validator.escapeSql(u.getLastName())); map.put("{worksiteid}", Validator.escapeSql(ToolManager.getCurrentPlacement().getContext())); map.put("{toolid}", Validator.escapeSql(ToolManager.getCurrentPlacement().getId())); } else { map.put("{userdisplayname}", Validator.escapeSql((String) s.getAttribute("userdisplayname"))); map.put("{useremail}", Validator.escapeSql((String) s.getAttribute("useremail"))); map.put("{userfirstname}", Validator.escapeSql((String) s.getAttribute("userfirstname"))); map.put("{userlastname}", Validator.escapeSql((String) s.getAttribute("userlastname"))); map.put("{worksiteid}", Validator.escapeSql((String) s.getAttribute("worksiteid"))); map.put("{toolid}", Validator.escapeSql((String) s.getAttribute("toolid"))); } Iterator iter = map.keySet().iterator(); StringBuilder str = new StringBuilder(inString); // loop through all the parameters and find in query for replacement while (iter.hasNext()) { // get the parameter and associated parameter definition String key = (String) iter.next(); int i = str.indexOf(key); // Loop until no instances exist while (i != -1) { // replace the parameter with the value str.delete(i, i + key.length()); str.insert(i, (String) map.get(key)); // look for a second instance i = str.indexOf(key); } } String string = str.toString(); // create a list of the supported bean objects whose values can be replaced Map beans = new HashMap(); beans.put("{session.attribute.", s); beans.put("{site.property.", site); beans.put("{user.property.", user); string = replaceSystemValues(string, beans); beans = new HashMap(); beans.put("{session.", s); beans.put("{site.", site); beans.put("{user.", user); string = replaceSystemValues(string, beans); return string; }
From source file:edu.usu.sdl.openstorefront.service.OrientPersistenceService.java
@Override public long countByExample(QueryByExample queryByExample) { long count = 0; StringBuilder queryString = new StringBuilder(); if (QueryType.SELECT.equals(queryByExample.getQueryType())) { queryByExample.setQueryType(QueryType.COUNT); }//from w w w .j a va 2 s.c o m switch (queryByExample.getQueryType()) { case COUNT: queryString.append("select count(*) "); break; case COUNT_DISTINCT: queryString.append("select count(distinct(").append(queryByExample.getDistinctField()).append(") "); break; default: throw new OpenStorefrontRuntimeException("Query Type unsupported: " + queryByExample.getQueryType(), "Only supports Count types"); } queryString.append("from ").append(queryByExample.getExample().getClass().getSimpleName()); Map<String, Object> mappedParams = new HashMap<>(); String whereClause = generateWhereClause(queryByExample.getExample(), new ComplexFieldStack(), queryByExample.getExampleOption()); if (StringUtils.isNotBlank(whereClause)) { queryString.append(" where ").append(whereClause); mappedParams.putAll(mapParameters(queryByExample.getExample())); } queryByExample.getExtraWhereCauses().forEach(item -> { SpecialOperatorModel special = (SpecialOperatorModel) item; String extraWhere = generateWhereClause(special.getExample(), new ComplexFieldStack(), special.getGenerateStatementOption()); if (StringUtils.isNotBlank(extraWhere)) { if (queryString.indexOf(" where ") != -1) { queryString.append(" AND "); } else { queryString.append(" where "); } queryString.append(extraWhere); mappedParams.putAll(mapParameters(special.getExample(), new ComplexFieldStack(), special.getGenerateStatementOption())); } }); OObjectDatabaseTx db = getConnection(); try { List<ODocument> documents = db.command(new OCommandSQL(queryString.toString())).execute(mappedParams); if (documents.isEmpty() == false) { count = documents.get(0).field("count"); } } finally { closeConnection(db); } return count; }
From source file:raptor.connector.ics.IcsConnector.java
/** * This method is invoked by the run method when there is new text to be * handled. It buffers text until a prompt is found then invokes * parseMessage.//from w w w .ja v a 2 s . co m * * This method also handles login logic which is tricky. */ public void messageArrived(StringBuilder buffer) { // System.err.println("Message arrived (buffer): " + buffer); if (isLoggedIn) { isLoggingIn = false; // If we are logged in. Then parse out all the text between the // prompts. int promptIndex = -1; while ((promptIndex = buffer.indexOf(context.getRawPrompt())) != -1) { String message = drainInboundMessageBuffer(buffer, promptIndex + context.getRawPrompt().length()); parseMessage(message); } } else { // We are not logged in. // There are several complex cases here depending on the prompt // we are waiting on. // There is a login prompt, a password prompt, an enter prompt, // and also you have to handle invalid logins. int loggedInMessageIndex = buffer.indexOf(context.getLoggedInMessage()); if (loggedInMessageIndex != -1) { for (int i = 0; i < buffer.length(); i++) { char character = buffer.charAt(i); if (LOGIN_CHARACTERS_TO_FILTER.indexOf(character) != -1) { buffer.deleteCharAt(i); i--; } } int nameStartIndex = buffer.indexOf(context.getLoggedInMessage()) + context.getLoggedInMessage().length(); int endIndex = buffer.indexOf("****", nameStartIndex); if (endIndex != -1) { userName = IcsUtils.stripTitles(buffer.substring(nameStartIndex, endIndex).trim()); LOG.info(context.getShortName() + "Connector " + "login complete. userName=" + userName); isLoggedIn = true; onSuccessfulLogin(); restoreTabStates(); // Since we are now logged in, just buffer the text // received and // invoke parseMessage when the prompt arrives. } else { // We have yet to receive the **** closing message so // wait // until it arrives. } } else { int loginIndex = buffer.indexOf(context.getLoginPrompt()); if (loginIndex != -1) { String event = drainInboundMessageBuffer(buffer, loginIndex + context.getLoginPrompt().length()); onLoginEvent(event, true); } else { int enterPromptIndex = buffer.indexOf(context.getEnterPrompt()); if (enterPromptIndex != -1) { String event = drainInboundMessageBuffer(buffer, enterPromptIndex + context.getEnterPrompt().length()); onLoginEvent(event, false); } else { int passwordPromptIndex = buffer.indexOf(context.getPasswordPrompt()); if (passwordPromptIndex != -1) { String event = drainInboundMessageBuffer(buffer, passwordPromptIndex + context.getPasswordPrompt().length()); onLoginEvent(event, false); } else { int errorMessageIndex = buffer.indexOf(context.getLoginErrorMessage()); if (errorMessageIndex != -1) { String event = drainInboundMessageBuffer(buffer); event = StringUtils.replaceChars(event, "\uefbf\ubdef\ubfbd\uefbf\ubdef\ubfbd", ""); parseMessage(event); } } } } } } }
From source file:com.impetus.client.cassandra.CassandraClientBase.java
/** * On relation columns./*from w w w . j a va 2s. com*/ * * @param columnNames * the column names * @param columnValues * the column values * @param columnNameBuilder * the column name builder * @param columnValueBuilder * the column value builder * @param rl * the rl * @return To remove redundant columns in insert query */ private StringBuilder onRelationColumns(String columnNames, String columnValues, StringBuilder columnNameBuilder, StringBuilder columnValueBuilder, RelationHolder rl) { int relnameIndx = columnNameBuilder.indexOf("\"" + rl.getRelationName() + "\""); if (relnameIndx != -1 && rl.getRelationValue() != null) { List<String> cNameArray = Arrays.asList(columnNames.split(",")); List<String> cValueArray = new ArrayList<String>(Arrays.asList(columnValues.split(","))); int cValueIndex = cNameArray.indexOf("\"" + rl.getRelationName() + "\""); if (cValueArray.get(cValueIndex).equals("null")) { columnNameBuilder.delete(relnameIndx - 1, relnameIndx + rl.getRelationName().length() + 2); cValueArray.remove(cValueIndex); columnValueBuilder = new StringBuilder( cValueArray.toString().substring(1, cValueArray.toString().length() - 1)); } } return columnValueBuilder; }
From source file:org.calrissian.accumulorecipes.commons.iterators.support.QueryEvaluator.java
public StringBuilder rewriteQuery(StringBuilder query, String fieldName, Collection<FieldValue> fieldValues) { if (log.isDebugEnabled()) { log.debug("rewriteQuery"); }//ww w. j a v a 2s. co m if (log.isDebugEnabled()) { log.debug("Modifying original criteria: " + query); } // Pull the values out of the FieldValue object String[] values = new String[fieldValues.size()]; int idx = 0; for (FieldValue fv : fieldValues) { values[idx] = new String(fv.getValue()); idx++; } // Add the array to the context ctx.set(fieldName, values); Collection<QueryParser.QueryTerm> qt = terms.get(fieldName); // Add a script to the beginning of the criteria for this multi-valued field StringBuilder script = new StringBuilder(); script.append("_").append(fieldName).append(" = false;\n"); script.append("for (field : ").append(fieldName).append(") {\n"); for (QueryParser.QueryTerm t : qt) { if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) { script.append("\tif (_").append(fieldName).append(" == false && field ").append(t.getOperator()) .append(" ").append(t.getValue()).append(") { \n"); } else { script.append("\tif (_").append(fieldName).append(" == false && ") .append(t.getValue().toString().replace(fieldName, "field")).append(") { \n"); } script.append("\t\t_").append(fieldName).append(" = true;\n"); script.append("\t}\n"); } script.append("}\n"); // Add the script to the beginning of the criteria query.insert(0, script.toString()); StringBuilder newPredicate = new StringBuilder(); newPredicate.append("_").append(fieldName).append(" == true"); for (QueryParser.QueryTerm t : qt) { // Find the location of this term in the criteria StringBuilder predicate = new StringBuilder(); int start = 0; if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) { predicate.append(fieldName).append(" ").append(t.getOperator()).append(" ").append(t.getValue()); start = query.indexOf(predicate.toString()); } else { predicate.append(t.getValue().toString()); // need to find the second occurence of the string. start = query.indexOf(predicate.toString()); } if (-1 == start) { log.warn("Unable to find predicate: " + predicate.toString() + " in rewritten criteria: " + query.toString()); } int length = predicate.length(); // Now modify the criteria to check the value of my.fieldName query.replace(start, start + length, newPredicate.toString()); } if (log.isDebugEnabled()) { log.debug("leaving rewriteQuery with: " + query.toString()); } return query; }
From source file:raptor.connector.ics.IcsConnector.java
public String[] breakUpMessage(StringBuilder message) { // There are two limits. Max communication size (400 on fics) for tells, // etc, and Max message communication size (800 on fics) for sending // messages.//from ww w . java2s . c om // This algorithm handles breaking up text that is too long for each. if (message.length() <= MAX_SEND_MESSAGE_LENGTH) { return new String[] { message + "\n" }; } else { int firstSpace = message.indexOf(" "); int messageLimit = MAX_SEND_MESSAGE_LENGTH; if (firstSpace != -1) { String command = message.substring(0, firstSpace); if (command.equalsIgnoreCase("message") || command.equalsIgnoreCase("mess") || command.equalsIgnoreCase("mes")) { messageLimit = MAX_MESSAGE_MESSAGE_LENGTH; } } if (message.length() <= messageLimit) { return new String[] { message + "\n" }; } List<String> result = new ArrayList<String>(5); if (firstSpace != -1) { int secondSpace = message.indexOf(" ", firstSpace + 1); if (secondSpace != -1) { String beginingText = message.substring(0, secondSpace + 1); String wrappedText = WordUtils.wrap(message.toString(), messageLimit, "\n", true); String[] wrapped = wrappedText.split("\n"); result.add(wrapped[0] + "\n"); for (int i = 1; i < wrapped.length; i++) { result.add(beginingText + wrapped[i] + "\n"); } } else { result.add(message.substring(0, messageLimit) + "\n"); publishEvent(new ChatEvent(null, ChatType.INTERNAL, L10n.getInstance().getString("icsConnal") + result.get(0))); } } else { result.add(message.substring(0, messageLimit) + "\n"); publishEvent(new ChatEvent(null, ChatType.INTERNAL, L10n.getInstance().getString("icsConnal") + result.get(0))); } return result.toArray(new String[0]); } }