List of usage examples for java.lang StringBuilder indexOf
@Override public int indexOf(String str)
From source file:org.medici.bia.common.search.SimpleSearchPlace.java
/** * {@inheritDoc}/* w w w. ja va 2 s .c o m*/ */ @Override public String toJPAQuery() { StringBuilder jpaQuery = new StringBuilder("FROM Place "); if (!empty()) { //MD: We need to re-convert the alias text = text.replace("\\\"", "\""); String toSearch = text; List<String> exactWords = new ArrayList<String>(); //MD: This code is to identify the words between double quotes while (toSearch.contains("\"")) { //First double quote int from = toSearch.indexOf('\"'); //Second double quote int to = toSearch.indexOf('\"', from + 1); //If there is the second double quote or not if (to != -1) { //Add the exact words to the list and remove them from the string exactWords.add(toSearch.substring(from + 1, to)); toSearch = toSearch.substring(0, from) + toSearch.substring(to + 1, toSearch.length()); } else { toSearch = toSearch.replace("\"", " "); } } String[] words = RegExUtils.splitPunctuationAndSpaceChars(toSearch); if (words.length > 0 || exactWords.size() > 0) { jpaQuery.append(" WHERE "); } for (int i = 0; i < exactWords.size(); i++) { jpaQuery.append("((placeNameFull LIKE '% "); jpaQuery.append(exactWords.get(i).trim().replace("'", "''")); jpaQuery.append(" %') OR (termAccent LIKE '% "); jpaQuery.append(exactWords.get(i).trim().replace("'", "''")); jpaQuery.append(" %'))"); if (i < exactWords.size() - 1) { jpaQuery.append(" AND "); } } if (exactWords.size() > 0 && words.length > 0) { jpaQuery.append(" AND "); } for (int i = 0; i < words.length; i++) { jpaQuery.append("((placeNameFull like '%"); jpaQuery.append(words[i].replace("'", "''")); jpaQuery.append("%') OR termAccent like '%"); jpaQuery.append(words[i].replace("'", "''")); jpaQuery.append("%')"); if (i < words.length - 1) { jpaQuery.append(" AND "); } } //To discard record deleted if (jpaQuery.indexOf("WHERE") != -1) { jpaQuery.append(" AND logicalDelete = false"); } } else { jpaQuery.append(" WHERE logicalDelete = false"); } return jpaQuery.toString(); }
From source file:org.infoglue.deliver.invokers.PageInvoker.java
protected String decorateHeadAndPageWithVarsFromComponents(String pageString) { pageString = this.getTemplateController().decoratePage(pageString); StringBuilder sb = null; Timer t = new Timer(); this.generateExtensionBundles( this.getTemplateController().getDeliveryContext().getScriptExtensionHeadBundles(), "text/javascript", "head"); this.generateExtensionBundles( this.getTemplateController().getDeliveryContext().getScriptExtensionBodyBundles(), "text/javascript", "body"); this.generateExtensionBundles(this.getTemplateController().getDeliveryContext().getCSSExtensionBundles(), "text/css", "head"); List htmlHeadItems = this.getTemplateController().getDeliveryContext().getHtmlHeadItems(); if (htmlHeadItems != null && htmlHeadItems.size() > 0) { int indexOfHeadEndTag = pageString.indexOf("</head"); if (indexOfHeadEndTag == -1) indexOfHeadEndTag = pageString.indexOf("</HEAD"); if (indexOfHeadEndTag != -1) { sb = new StringBuilder(pageString); String headerItems = ""; Iterator htmlHeadItemsIterator = htmlHeadItems.iterator(); while (htmlHeadItemsIterator.hasNext()) { String value = (String) htmlHeadItemsIterator.next(); //logger.info("headItem:" + value); headerItems = headerItems + value + "\n"; }//w w w.ja va2 s. c o m sb.insert(indexOfHeadEndTag, headerItems); //pageString = sb.toString(); } } List<String> htmlBodyEndItems = this.getTemplateController().getDeliveryContext().getHtmlBodyEndItems(); if (htmlBodyEndItems != null && htmlBodyEndItems.size() > 0) { if (sb == null) sb = new StringBuilder(pageString); int indexOfBodyEndTag = sb.indexOf("</body"); if (indexOfBodyEndTag == -1) indexOfBodyEndTag = sb.indexOf("</BODY"); if (indexOfBodyEndTag != -1) { String bodyItems = ""; Iterator htmlBodyItemsIterator = htmlBodyEndItems.iterator(); while (htmlBodyItemsIterator.hasNext()) { String value = (String) htmlBodyItemsIterator.next(); //logger.info("headItem:" + value); bodyItems = bodyItems + value + "\n"; } sb.insert(indexOfBodyEndTag, bodyItems); //pageString = sb.toString(); } } RequestAnalyser.getRequestAnalyser().registerComponentStatistics("pageInvoker", t.getElapsedTime()); try { int lastModifiedDateTimeIndex; if (sb == null) lastModifiedDateTimeIndex = pageString.indexOf("<ig:lastModifiedDateTime"); else lastModifiedDateTimeIndex = sb.indexOf("<ig:lastModifiedDateTime"); //logger.info("OOOOOOOOOOOOO lastModifiedDateTimeIndex:" + lastModifiedDateTimeIndex); if (lastModifiedDateTimeIndex > -1) { if (sb == null) sb = new StringBuilder(pageString); int lastModifiedDateTimeEndIndex = sb.indexOf("</ig:lastModifiedDateTime>", lastModifiedDateTimeIndex); String tagInfo = sb.substring(lastModifiedDateTimeIndex, lastModifiedDateTimeEndIndex); //logger.info("tagInfo:" + tagInfo); String dateFormat = "yyyy-MM-dd HH:mm"; int formatStartIndex = tagInfo.indexOf("format"); if (formatStartIndex > -1) { int formatEndIndex = tagInfo.indexOf("\"", formatStartIndex + 8); if (formatEndIndex > -1) dateFormat = tagInfo.substring(formatStartIndex + 8, formatEndIndex); } //logger.info("dateFormat:" + dateFormat); String dateString = vf.formatDate( this.getTemplateController().getDeliveryContext().getLastModifiedDateTime(), this.getTemplateController().getLocale(), dateFormat); //logger.info("dateString:" + dateString); sb.replace(lastModifiedDateTimeIndex, lastModifiedDateTimeEndIndex + "</ig:lastModifiedDateTime>".length(), dateString); //logger.info("Replaced:" + lastModifiedDateTimeIndex + " to " + lastModifiedDateTimeEndIndex + "</ig:lastModifiedDateTime>".length() + " with " + dateString); } } catch (Exception e) { logger.error("Problem setting lastModifiedDateTime:" + e.getMessage(), e); } if (sb != null) pageString = sb.toString(); return pageString; }
From source file:eu.faircode.adblocker.ServiceSinkhole.java
private void showAccessNotification(int uid) { String name = TextUtils.join(", ", Util.getApplicationNames(uid, ServiceSinkhole.this)); Intent main = new Intent(ServiceSinkhole.this, ActivityMain.class); main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid)); PendingIntent pi = PendingIntent.getActivity(ServiceSinkhole.this, uid + 10000, main, PendingIntent.FLAG_UPDATE_CURRENT); TypedValue tv = new TypedValue(); getTheme().resolveAttribute(R.attr.colorOn, tv, true); int colorOn = tv.data; getTheme().resolveAttribute(R.attr.colorOff, tv, true); int colorOff = tv.data; NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_cloud_upload_white_24dp).setGroup("AccessAttempt") .setContentTitle(getString(R.string.app_name)).setContentText(getString(R.string.msg_access, name)) .setContentIntent(pi).setColor(colorOff).setOngoing(false).setAutoCancel(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET); }/*from w ww . j a v a 2 s .co m*/ DateFormat df = new SimpleDateFormat("dd HH:mm"); NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder); String sname = getString(R.string.msg_access, name); int pos = sname.indexOf(name); Spannable sp = new SpannableString(sname); sp.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); notification.addLine(sp); Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessUnset(uid, 7); int colDAddr = cursor.getColumnIndex("daddr"); int colTime = cursor.getColumnIndex("time"); int colAllowed = cursor.getColumnIndex("allowed"); while (cursor.moveToNext()) { StringBuilder sb = new StringBuilder(); sb.append(df.format(cursor.getLong(colTime))).append(' '); String daddr = cursor.getString(colDAddr); if (Util.isNumericAddress(daddr)) try { daddr = InetAddress.getByName(daddr).getHostName(); } catch (UnknownHostException ignored) { } sb.append(daddr); int allowed = cursor.getInt(colAllowed); if (allowed >= 0) { pos = sb.indexOf(daddr); sp = new SpannableString(sb); ForegroundColorSpan fgsp = new ForegroundColorSpan(allowed > 0 ? colorOn : colorOff); sp.setSpan(fgsp, pos, pos + daddr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } notification.addLine(sp); } cursor.close(); NotificationManagerCompat.from(this).notify(uid + 10000, notification.build()); }
From source file:edu.hawaii.soest.kilonalu.ctd.SBE37Source.java
/** * A method that executes the streaming of data from the source to the RBNB * server after all configuration of settings, connections to hosts, and * thread initiatizing occurs. This method contains the detailed code for * streaming the data and interpreting the stream. *//*from w w w .j ava 2 s . co m*/ protected boolean execute() { logger.debug("SBE37Source.execute() called."); // do not execute the stream if there is no connection if (!isConnected()) return false; boolean failed = false; // while data are being sent, read them into the buffer try { this.socketChannel = getSocketConnection(); // create four byte placeholders used to evaluate up to a four-byte // window. The FIFO layout looks like: // ------------------------- // in ---> | One | Two |Three|Four | ---> out // ------------------------- byte byteOne = 0x00, // set initial placeholder values byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00; // Create a buffer that will store the sample bytes as they are read ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize()); // create a byte buffer to store bytes from the TCP stream ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize()); // create a character string to store characters from the TCP stream StringBuilder responseString = new StringBuilder(); // add a channel of data that will be pushed to the server. // Each sample will be sent to the Data Turbine as an rbnb frame. ChannelMap rbnbChannelMap = new ChannelMap(); int channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); // wake the instrument with an initial take sample command this.command = this.commandPrefix + getInstrumentID() + "TS" + this.commandSuffix; this.sentCommand = queryInstrument(this.command); // verify the instrument ID is correct while (getInstrumentID() == null) { // allow time for the instrument response streamingThread.sleep(2000); buffer.clear(); // send the command and update the sentCommand status this.sentCommand = queryInstrument(this.command); // read the response into the buffer. Note that the streamed bytes // are 8-bit, not 16-bit Unicode characters. Use the US-ASCII // encoding instead. while (this.socketChannel.read(buffer) != -1 || buffer.position() > 0) { buffer.flip(); while (buffer.hasRemaining()) { String nextCharacter = new String(new byte[] { buffer.get() }, "US-ASCII"); responseString.append(nextCharacter); } // look for the command line ending if (responseString.toString().indexOf("S>") > 0) { // parse the ID from the idCommand response int idStartIndex = responseString.indexOf("=") + 2; int idStopIndex = responseString.indexOf("=") + 4; String idString = responseString.substring(idStartIndex, idStopIndex); // test that the ID is a valid number and set the instrument ID if ((new Integer(idString)).intValue() > 0) { setInstrumentID(idString); buffer.clear(); logger.debug("Instrument ID is " + getInstrumentID() + "."); break; } else { logger.debug("Instrument ID \"" + idString + "\" was not set."); } } else { break; } buffer.compact(); if (getInstrumentID() != null) { break; } } } // instrumentID is set // allow time for the instrument response streamingThread.sleep(5000); this.command = this.commandPrefix + getInstrumentID() + this.takeSampleCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); // while there are bytes to read from the socket ... while (this.socketChannel.read(buffer) != -1 || buffer.position() > 0) { // prepare the buffer for reading buffer.flip(); // while there are unread bytes in the ByteBuffer while (buffer.hasRemaining()) { byteOne = buffer.get(); //logger.debug("b1: " + new String(Hex.encodeHex((new byte[]{byteOne}))) + "\t" + // "b2: " + new String(Hex.encodeHex((new byte[]{byteTwo}))) + "\t" + // "b3: " + new String(Hex.encodeHex((new byte[]{byteThree}))) + "\t" + // "b4: " + new String(Hex.encodeHex((new byte[]{byteFour}))) + "\t" + // "sample pos: " + sampleBuffer.position() + "\t" + // "sample rem: " + sampleBuffer.remaining() + "\t" + // "sample cnt: " + sampleByteCount + "\t" + // "buffer pos: " + buffer.position() + "\t" + // "buffer rem: " + buffer.remaining() + "\t" + // "state: " + state //); // Use a State Machine to process the byte stream. // Start building an rbnb frame for the entire sample, first by // inserting a timestamp into the channelMap. This time is merely // the time of insert into the data turbine, not the time of // observations of the measurements. That time should be parsed out // of the sample in the Sink client code switch (state) { case 0: // sample line is begun by S> // note bytes are in reverse order in the FIFO window if (byteOne == 0x3E && byteTwo == 0x53) { // we've found the beginning of a sample, move on state = 1; break; } else { break; } case 1: // read the rest of the bytes to the next EOL characters // sample line is terminated by S> // note bytes are in reverse order in the FIFO window if (byteOne == 0x3E && byteTwo == 0x53) { sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract just the length of the sample bytes (less 2 bytes // to exclude the 'S>' prompt characters) out of the // sample buffer, and place it in the channel map as a // byte array. Then, send it to the data turbine. byte[] sampleArray = new byte[sampleByteCount - 2]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); // send the sample to the data turbine rbnbChannelMap.PutTimeAuto("server"); String sampleString = new String(sampleArray, "US-ASCII"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, sampleString); getSource().Flush(rbnbChannelMap); logger.info("Sample: " + sampleString); logger.info("flushed data to the DataTurbine. "); byteOne = 0x00; byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; sampleBuffer.clear(); sampleByteCount = 0; //rbnbChannelMap.Clear(); //logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap."); //state = 0; // Once the sample is flushed, take a new sample if (getInstrumentID() != null) { // allow time for the instrument response streamingThread.sleep(2000); this.command = this.commandPrefix + getInstrumentID() + this.takeSampleCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); } } else { // not 0x0A0D // still in the middle of the sample, keep adding bytes sampleByteCount++; // add each byte found if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); logger.debug("Compacting sampleBuffer ..."); sampleBuffer.put(byteOne); } break; } // end if for 0x0A0D EOL } // end switch statement // shift the bytes in the FIFO window byteFour = byteThree; byteThree = byteTwo; byteTwo = byteOne; } //end while (more unread bytes) // prepare the buffer to read in more bytes from the stream buffer.compact(); } // end while (more socket bytes to read) this.socketChannel.close(); } catch (IOException e) { // handle exceptions // In the event of an i/o exception, log the exception, and allow execute() // to return false, which will prompt a retry. failed = true; e.printStackTrace(); return !failed; } catch (SAPIException sapie) { // In the event of an RBNB communication exception, log the exception, // and allow execute() to return false, which will prompt a retry. failed = true; sapie.printStackTrace(); return !failed; } catch (java.lang.InterruptedException ie) { ie.printStackTrace(); } return !failed; }
From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java
public StringBuilder replaceForMultiSet(StringBuilder inQuery, List reportParams) { if (reportParams == null) { return inQuery; }/*from w ww . j a va 2 s .co m*/ Iterator iter = reportParams.iterator(); // loop through all the parameters and find in query for replacement while (iter.hasNext()) { // get the paremeter and associated parameter definition ReportParam rp = (ReportParam) iter.next(); ReportDefinitionParam rdp = rp.getReportDefinitionParam(); if (ReportDefinitionParam.VALUE_TYPE_MULTI_OF_SET.equals(rdp.getValueType()) || ReportDefinitionParam.VALUE_TYPE_MULTI_OF_QUERY.equals(rdp.getValueType())) { if (rp.getListValue().size() > 1) { int index = inQuery.indexOf("(?)"); inQuery.delete(index, index + 3); StringBuilder tempString = new StringBuilder("("); for (int i = 0; i < rp.getListValue().size(); i++) { tempString.append("?,"); } tempString.delete(tempString.length() - 1, tempString.length()); tempString.append(") "); inQuery.insert(index, tempString); } } } return inQuery; }
From source file:edu.usu.sdl.openstorefront.service.OrientPersistenceService.java
@Override public <T> List<T> queryByExample(Class<T> exampleClass, QueryByExample queryByExample) { StringBuilder queryString = new StringBuilder(); switch (queryByExample.getQueryType()) { case SELECT://from w w w. j av a 2 s .c o m queryString.append("select "); break; default: throw new OpenStorefrontRuntimeException("Query Type unsupported: " + queryByExample.getQueryType(), "Only supports select"); } 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())); } if (queryByExample.getLikeExample() != null) { String likeClause = generateWhereClause(queryByExample.getLikeExample(), new ComplexFieldStack(), queryByExample.getLikeExampleOption()); if (StringUtils.isNotBlank(likeClause)) { if (StringUtils.isNotBlank(whereClause)) { queryString.append(" AND "); } else { queryString.append(" where "); } queryString.append(likeClause); mappedParams.putAll(mapParameters(queryByExample.getLikeExample())); } } 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())); } }); if (queryByExample.getGroupBy() != null) { String names = generateExampleNames(queryByExample.getGroupBy()); if (StringUtils.isNotBlank(names)) { queryString.append(" group by ").append(names); } } if (queryByExample.getOrderBy() != null) { String names = generateExampleNames(queryByExample.getOrderBy()); if (StringUtils.isNotBlank(names)) { queryString.append(" order by ").append(names).append(" ") .append(queryByExample.getSortDirection()); } } if (queryByExample.getFirstResult() != null && queryByExample.getFirstResult() > 0) { queryString.append(" SKIP ").append(queryByExample.getFirstResult()); } if (queryByExample.getMaxResults() != null && queryByExample.getMaxResults() > 0) { queryString.append(" LIMIT ").append(queryByExample.getMaxResults()); } if (queryByExample.getTimeout() != null) { queryString.append(" TIMEOUT ").append(queryByExample.getTimeout()).append(" ") .append(queryByExample.getTimeoutStrategy()); } if (queryByExample.isParallelQuery()) { queryString.append(" PARALLEL "); } List<T> results = query(queryString.toString(), mappedParams, exampleClass, queryByExample.isReturnNonProxied()); return results; }
From source file:edu.usu.sdl.openstorefront.service.PersistenceService.java
public <T> List<T> queryByExample(Class<T> exampleClass, QueryByExample queryByExample) { StringBuilder queryString = new StringBuilder(); switch (queryByExample.getQueryType()) { case SELECT:/*from w w w . j a v a2s . c om*/ queryString.append("select "); break; default: throw new OpenStorefrontRuntimeException("Query Type unsupported: " + queryByExample.getQueryType(), "Only supports select"); } 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())); } if (queryByExample.getLikeExample() != null) { GenerateStatementOption generateStatementOption = new GenerateStatementOption(); generateStatementOption.setOperation(GenerateStatementOption.OPERATION_LIKE); String likeClause = generateWhereClause(queryByExample.getLikeExample(), new ComplexFieldStack(), generateStatementOption); if (StringUtils.isNotBlank(likeClause)) { if (StringUtils.isNotBlank(whereClause)) { queryString.append(" AND "); } else { queryString.append(" where "); } queryString.append(likeClause); mappedParams.putAll(mapParameters(queryByExample.getLikeExample())); } } 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())); } }); if (queryByExample.getGroupBy() != null) { String names = generateExampleNames(queryByExample.getGroupBy()); if (StringUtils.isNotBlank(names)) { queryString.append(" group by ").append(names); } } if (queryByExample.getOrderBy() != null) { String names = generateExampleNames(queryByExample.getOrderBy()); if (StringUtils.isNotBlank(names)) { queryString.append(" order by ").append(names).append(" ") .append(queryByExample.getSortDirection()); } } if (queryByExample.getFirstResult() != null && queryByExample.getFirstResult() > 0) { queryString.append(" SKIP ").append(queryByExample.getFirstResult()); } if (queryByExample.getMaxResults() != null && queryByExample.getMaxResults() > 0) { queryString.append(" LIMIT ").append(queryByExample.getMaxResults()); } if (queryByExample.getTimeout() != null) { queryString.append(" TIMEOUT ").append(queryByExample.getTimeout()).append(" ") .append(queryByExample.getTimeoutStrategy()); } if (queryByExample.isParallelQuery()) { queryString.append(" PARALLEL "); } List<T> results = query(queryString.toString(), mappedParams, exampleClass, queryByExample.isReturnNonProxied()); return results; }
From source file:org.apache.hive.beeline.BeeLine.java
/** * This is an internal method used to create !connect command when -p option is used without * providing the password on the command line. Connect command returned should be ; separated * key-value pairs along with the url. We cannot use space separated !connect url user [password] * [driver] here since both password and driver are optional and there would be no way to * distinguish if the last string is password or driver * * @param url connection url passed using -u argument on the command line * @param user username passed through command line * @param driver driver passed through command line -d option * @param stripPasswd when set to true generates a !connect command which strips the password for * logging purposes/*from w ww . j av a 2s . com*/ * @return !connect command */ private String constructCmdUrl(String url, String user, String driver, boolean stripPasswd) { StringBuilder command = new StringBuilder("!connect "); command.append(url); //if the url does not have a database name add the trailing '/' if (isTrailingSlashNeeded(url)) { command.append('/'); } command.append(';'); // if the username is not already available in the URL add the one provided if (Utils.parsePropertyFromUrl(url, JdbcConnectionParams.AUTH_USER) == null) { command.append(JdbcConnectionParams.AUTH_USER); command.append('='); command.append((user == null || user.length() == 0 ? "''" : user)); } if (stripPasswd) { // if password is available in url it needs to be striped int startIndex = command.indexOf(JdbcConnectionParams.AUTH_PASSWD + "=") + JdbcConnectionParams.AUTH_PASSWD.length() + 2; if (startIndex != -1) { int endIndex = command.toString().indexOf(";", startIndex); command.replace(startIndex, (endIndex == -1 ? command.length() : endIndex), BeeLine.PASSWD_MASK); } } // if the driver is not already available in the URL add the one provided if (Utils.parsePropertyFromUrl(url, JdbcConnectionParams.PROPERTY_DRIVER) == null && driver != null) { command.append(';'); command.append(JdbcConnectionParams.PROPERTY_DRIVER); command.append("="); command.append(driver); } return command.toString(); }
From source file:org.medici.bia.common.search.SimpleSearchVolume.java
/** * {@inheritDoc}// ww w.java 2 s .c o m */ @Override public String toJPAQuery() { StringBuilder jpaQuery = new StringBuilder("FROM Volume "); if (!empty()) { //MD: We need to re-convert the alias text = text.replace("\\\"", "\""); String[] words = RegExUtils.splitPunctuationAndSpaceChars(text); if (words.length > 0) { jpaQuery.append(" WHERE "); } for (int i = 0; i < words.length; i++) { if (NumberUtils.isNumber(words[i])) { jpaQuery.append("(volNum = "); jpaQuery.append(words[i]); jpaQuery.append(')'); } else { if (words[i].length() == 1) { jpaQuery.append("(volLetExt like '"); jpaQuery.append(words[i].replace("'", "''")); jpaQuery.append("')"); } else if (words[i].matches("^\\d{1,5}[a-zA-Z]{1}")) { jpaQuery.append("(volNum = "); jpaQuery.append(words[i].substring(0, words[i].length() - 1).replace("'", "''")); jpaQuery.append(" AND volLetExt LIKE '"); jpaQuery.append(words[i].charAt(words[i].length() - 1)); jpaQuery.append("')"); } else { jpaQuery.append("((ccondition like '%"); jpaQuery.append(words[i].replace("'", "''") + "%') OR "); jpaQuery.append("(ccontext like '%"); jpaQuery.append(words[i].replace("'", "''") + "%') OR "); jpaQuery.append("(orgNotes like '%"); jpaQuery.append(words[i].replace("'", "''") + "%') OR "); jpaQuery.append("(recips like '%"); jpaQuery.append(words[i].replace("'", "''") + "%') OR "); jpaQuery.append("(senders like '%"); jpaQuery.append(words[i].replace("'", "''") + "%') OR "); jpaQuery.append("(serieList.title like '%"); jpaQuery.append(words[i].replace("'", "''") + "%') OR "); jpaQuery.append("(serieList.subTitle1 like '%"); jpaQuery.append(words[i].replace("'", "''") + "%') OR "); jpaQuery.append("(serieList.subTitle2 like '%"); jpaQuery.append(words[i].replace("'", "''") + "%'))"); } } if (i < (words.length - 1)) { jpaQuery.append(" AND "); } } //To discard record deleted if (jpaQuery.indexOf("WHERE") != -1) { jpaQuery.append(" AND logicalDelete = false"); } } else { jpaQuery.append(" WHERE logicalDelete = false"); } return jpaQuery.toString(); }
From source file:org.exoplatform.calendar.ws.RestEventQuery.java
@Override public String getQueryStatement() throws Exception { // events from user, groups, public calendars, and events that contains // specific participant StringBuilder sql = new StringBuilder("SELECT " + Utils.EXO_ID + " FROM "); sql.append(Utils.EXO_CALENDAR_EVENT); sql.append(" WHERE"); // if (getCalendarPath() != null) { // sql.append(" jcr:path LIKE '").append(getCalendarPath()).append("/%' AND NOT jcr:path LIKE '"); // sql.append(getCalendarPath()).append("/%/%'"); // }/*from w w w.j a v a 2 s .c o m*/ if (getCalendarId() != null || getParticipants() != null) { sql.append(" AND ("); // calendarIds: public and groups, shared calendars if (getCalendarId() != null) { for (String calId : getCalendarId()) { sql.append(" OR ").append(Utils.EXO_CALENDAR_ID).append(" = '").append(calId).append("'"); } } // participant if (getParticipants() != null) { for (String participant : getParticipants()) { //workaround for case calendarRestApi.findEventsByCalendar if (getCalendarPath() != null) { sql.append(" AND "); } else { sql.append(" OR "); } if (CalendarEvent.TYPE_TASK.equals(getEventType())) { sql.append("CONTAINS(").append(Utils.EXO_TASK_DELEGATOR); sql.append(",'").append(participant).append("')"); } else { sql.append(Utils.EXO_PARTICIPANT).append(" = '").append(participant).append("'"); } } } sql.append(")"); } // date time if (getFromDate() != null) { sql.append(" AND (").append(Utils.EXO_FROM_DATE_TIME).append(" >= TIMESTAMP '") .append(ISO8601.format(getFromDate())).append("')"); } if (getToDate() != null) { sql.append(" AND (").append(Utils.EXO_TO_DATE_TIME).append(" <= TIMESTAMP '") .append(ISO8601.format(getToDate())).append("')"); } // category String[] categoryIds = getCategoryId(); if (categoryIds != null && categoryIds.length > 0) { sql.append(" AND ("); for (int i = 0; i < categoryIds.length; i++) { sql.append(Utils.EXO_EVENT_CATEGORYID); sql.append(" = '").append(categoryIds[i]).append("'"); if (i < categoryIds.length - 1) { sql.append(" OR "); } } sql.append(")"); } // event or task if (!Utils.isEmpty(getEventType())) { sql.append(" AND ").append(Utils.EXO_EVENT_TYPE).append("='"); sql.append(getEventType()).append("'"); } int i = sql.indexOf("WHERE AND"); if (i != -1) { sql.replace(i, i + 9, "WHERE"); } if ((i = sql.indexOf("( OR")) != -1) { sql.replace(i, i + 4, "("); } if ((i = sql.indexOf("( AND")) != -1) { sql.replace(i, i + 5, "("); } String[] orderBy = getOrderBy(); String orderType = " " + getOrderType(); if (orderBy != null && orderBy.length > 0) { sql.append(" ORDER BY "); for (int j = 0; j < orderBy.length; j++) { orderBy[j] = orderBy[j] + orderType; } sql.append(StringUtils.join(orderBy, ",")); } return sql.toString(); }