List of usage examples for org.apache.commons.lang3 StringUtils countMatches
public static int countMatches(final CharSequence str, final char ch)
Counts how many times the char appears in the given string.
A null or empty ("") String input returns 0 .
StringUtils.countMatches(null, *) = 0 StringUtils.countMatches("", *) = 0 StringUtils.countMatches("abba", 0) = 0 StringUtils.countMatches("abba", 'a') = 2 StringUtils.countMatches("abba", 'b') = 2 StringUtils.countMatches("abba", 'x') = 0
From source file:com.thoughtworks.go.config.GoConfigMigrationIntegrationTest.java
@Test public void shouldRemoveEmptyTags_asPartOfMigration78() throws Exception { String configXml = "<cruise schemaVersion='77'>" + " <pipelines group='first'>" + " <authorization>" + " <view>" + " <user>foo</user>" + " <user />" + " <user> </user>" + " </view>" + " <operate>" + " <user></user>" + " </operate>" + " </authorization>" + " <pipeline name='Test' template='test_template'>" + " <materials>" + " <hg url='../manual-testing/ant_hg/dummy' />" + " </materials>" + " </pipeline>" + " </pipelines>" + "</cruise>"; String migratedXml = migrateXmlString(configXml, 77); assertThat(StringUtils.countMatches(migratedXml, "<user>")).isEqualTo(1); }
From source file:gobblin.source.extractor.extract.jdbc.JdbcExtractor.java
/** * Parse query provided in pull file Set input column projection - column * projection in the input query Set columnAlias map - column and its alias * mentioned in input query/* w w w. ja v a 2 s.c om*/ * * @param query input query */ private void parseInputQuery(String query) { List<String> projectedColumns = new ArrayList<>(); if (StringUtils.isNotBlank(query)) { String queryLowerCase = query.toLowerCase(); int startIndex = queryLowerCase.indexOf("select ") + 7; int endIndex = queryLowerCase.indexOf(" from "); if (startIndex >= 0 && endIndex >= 0) { String columnProjection = query.substring(startIndex, endIndex); this.setInputColumnProjection(columnProjection); // parse the select list StringBuffer sb = new StringBuffer(); int bracketCount = 0; for (int i = 0; i < columnProjection.length(); i++) { char c = columnProjection.charAt(i); if (c == '(') { bracketCount++; } if (c == ')') { bracketCount--; } if (bracketCount != 0) { sb.append(c); } else { if (c != ',') { sb.append(c); } else { projectedColumns.add(sb.toString()); sb = new StringBuffer(); } } } projectedColumns.add(sb.toString()); } } if (this.isSelectAllColumns()) { List<String> columnList = this.getMetadataColumnList(); for (String columnName : columnList) { ColumnAttributes col = new ColumnAttributes(); col.setColumnName(columnName); col.setAliasName(columnName); col.setSourceColumnName(columnName); this.addToColumnAliasMap(col); } } else { for (String projectedColumn : projectedColumns) { String column = projectedColumn.trim(); String alias = null; String sourceColumn = column; int spaceOccurences = StringUtils.countMatches(column.trim(), " "); if (spaceOccurences > 0) { // separate column and alias if they are separated by "as" // or space int lastSpaceIndex = column.toLowerCase().lastIndexOf(" as "); sourceColumn = column.substring(0, lastSpaceIndex); alias = column.substring(lastSpaceIndex + 4); } // extract column name if projection has table name in it String columnName = sourceColumn; if (sourceColumn.contains(".")) { columnName = sourceColumn.substring(sourceColumn.indexOf(".") + 1); } ColumnAttributes col = new ColumnAttributes(); col.setColumnName(columnName); col.setAliasName(alias); col.setSourceColumnName(sourceColumn); this.addToColumnAliasMap(col); } } }
From source file:MSUmpire.SearchResultParser.PepXMLParseHandler.java
private void UpdateFromLuciphor(PSM psmid, String modseq) throws NumberFormatException { if (singleLCMSID.LuciphorResult != null && singleLCMSID.LuciphorResult.containsKey(psmid.SpecNumber)) { String line = singleLCMSID.LuciphorResult.get(psmid.SpecNumber); if (Integer.parseInt(line.split("\t")[5]) < Integer.parseInt(line.split("\t")[6])) { for (int i = 0; i < 2; i++) { boolean isdecoy = line.split("\t")[12 + i].equals("1"); if (!isdecoy) { String lumodseq = line.split("\t")[2 + i]; String resultseq = modseq.replace("[79.96637(S)]", "").replace("[79.96637(Y)]", "") .replace("[79.96633(T)]", ""); while (lumodseq.contains("[167]")) { int aaindex = StringUtils.countMatches(lumodseq.substring(0, lumodseq.indexOf("[167]")) .replaceAll("\\[(.*?)\\]", "$1"), "S"); int cont = 0; for (int idx = 0; idx < resultseq.length(); idx++) { if ("S".equals(String.valueOf(resultseq.charAt(idx)))) { cont++;/*from w w w . jav a 2 s . c o m*/ if (cont == aaindex) { resultseq = resultseq.substring(0, idx) + "[79.96637(S)]" + resultseq.substring(idx); } } } lumodseq = lumodseq.substring(0, lumodseq.indexOf("[167]")) + lumodseq.substring(lumodseq.indexOf("[167]") + 5); } while (lumodseq.contains("[181]")) { int aaindex = StringUtils.countMatches(lumodseq.substring(0, lumodseq.indexOf("[181]")) .replaceAll("\\[(.*?)\\]", "$1"), "T"); int cont = 0; for (int idx = 0; idx < resultseq.length(); idx++) { if ("T".equals(String.valueOf(resultseq.charAt(idx)))) { cont++; if (cont == aaindex) { resultseq = resultseq.substring(0, idx) + "[79.96633(T)]" + resultseq.substring(idx); } } } lumodseq = lumodseq.substring(0, lumodseq.indexOf("[181]")) + lumodseq.substring(lumodseq.indexOf("[181]") + 5); } while (lumodseq.contains("[243]")) { int aaindex = StringUtils.countMatches(lumodseq.substring(0, lumodseq.indexOf("[243]")) .replaceAll("\\[(.*?)\\]", "$1"), "Y"); int cont = 0; for (int idx = 0; idx < resultseq.length(); idx++) { if ("Y".equals(String.valueOf(resultseq.charAt(idx)))) { cont++; if (cont == aaindex) { resultseq = resultseq.substring(0, idx) + "[79.96637(Y)]" + resultseq.substring(idx); } } } lumodseq = lumodseq.substring(0, lumodseq.indexOf("[243]")) + lumodseq.substring(lumodseq.indexOf("[243]") + 5); } psmid.LuciphorLFLR = Float.parseFloat(line.split("\t")[7].replace("NA", "1")); psmid.LuciphorFLR = Float.parseFloat(line.split("\t")[8].replace("NA", "1")); psmid.LuciphorScore = Float.parseFloat(line.split("\t")[10 + i].replace("NA", "0")); psmid.ModSeq = resultseq; psmid.TPPModSeq = lumodseq; return; } } } } }
From source file:com.seleniumtests.it.reporter.TestSeleniumTestsReporter2.java
/** * Check that manual steps create all steps in report * manual step option is set inside the StubTestClassManualSteps.testOk() method * check the failed test case where step should be marked as KO * Also, error in step should be presented * @throws Exception//from w w w .ja v a 2s .c o m */ @Test(groups = { "it" }) public void testManualSteps() throws Exception { executeSubTest(new String[] { "com.seleniumtests.it.stubclasses.StubTestClassManualSteps" }); // check content of summary report file String mainReportContent = readSummaryFile(); Assert.assertTrue(mainReportContent.matches(".*<a href\\='testOk/TestReport\\.html'.*?>testOk</a>.*")); Assert.assertTrue(mainReportContent .matches(".*<a href\\='testWithAssert/TestReport\\.html'.*?>testWithAssert</a>.*")); // check that without soft assertion, 'add' step is skipped String detailedReportContent1 = readTestMethodResultFile("testOk"); Assert.assertTrue(detailedReportContent1.contains("</button> Test start")); Assert.assertTrue(detailedReportContent1.contains("</button> add some values")); Assert.assertTrue(detailedReportContent1.contains("</button> minus 2")); Assert.assertTrue(detailedReportContent1.contains("</button> do nothing")); Assert.assertTrue(detailedReportContent1.contains("</button> Test end")); // check that configuration steps are automatically added Assert.assertTrue(detailedReportContent1.contains("</button> Pre test step: set - ")); Assert.assertTrue(detailedReportContent1.contains("</button> Post test step: teardown -")); // assert automatic steps are not present Assert.assertFalse(detailedReportContent1.contains("</button> add with args")); // check we also get actions Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "doNothing on HtmlElement none"), 3); // ----- check manual steps errors ------ String detailedReportContent2 = readTestMethodResultFile("testWithAssert"); // check execution logs are in error Assert.assertTrue(detailedReportContent2.contains( "<div class=\"box collapsed-box failed\"><div class=\"box-header with-border\"><button type=\"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button> Execution logs")); // test first step is OK and second one is failed (this shows indirectly that internal step is marked as failed Assert.assertTrue(detailedReportContent2.contains( "<div class=\"box collapsed-box success\"><div class=\"box-header with-border\"><button type=\"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button> Test start")); Assert.assertTrue(detailedReportContent2.contains( "<div class=\"box collapsed-box failed\"><div class=\"box-header with-border\"><button type=\"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button> assert exception")); // check exception is present in step Assert.assertTrue(detailedReportContent2.contains( "<div class=\"message-log\">Test is KO with error: false error expected [true] but found [false]</div>")); }
From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java
private String resolveDoReferenceId(String rawReferenceId, Map<String, String> imports, String namespace) { int numberOfDelimiters = StringUtils.countMatches(rawReferenceId, NAMESPACE_DELIMITER); String resolvedReferenceId;/*from w ww .j a va 2s. c o m*/ if (numberOfDelimiters == 0) { // implicit namespace resolvedReferenceId = namespace + NAMESPACE_DELIMITER + rawReferenceId; } else { String prefix = StringUtils.substringBefore(rawReferenceId, NAMESPACE_DELIMITER); String suffix = StringUtils.substringAfter(rawReferenceId, NAMESPACE_DELIMITER); if (MapUtils.isNotEmpty(imports) && imports.containsKey(prefix)) { // expand alias resolvedReferenceId = imports.get(prefix) + NAMESPACE_DELIMITER + suffix; } else { // full path without alias expanding resolvedReferenceId = rawReferenceId; } } return resolvedReferenceId; }
From source file:com.seleniumtests.it.reporter.TestSeleniumTestsReporter2.java
/** * Check all steps are present in detailed report file * Test OK//from w ww .j a v a2 s . c o m * @throws Exception */ @Test(groups = { "it" }) public void testReportDetailsSteps() throws Exception { executeSubTest(1, new String[] { "com.seleniumtests.it.stubclasses.StubTestClass" }, ParallelMode.METHODS, new String[] { "testAndSubActions", "testInError", "testWithException" }); String detailedReportContent = readTestMethodResultFile("testAndSubActions"); // Check each step is recorded in file: 2 test steps + test end + logs Assert.assertTrue(detailedReportContent.contains( "<div class=\"box collapsed-box failed\"><div class=\"box-header with-border\"><button type=\"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button> step 1 - ")); Assert.assertTrue(detailedReportContent.contains( "<div class=\"box collapsed-box success\"><div class=\"box-header with-border\"><button type=\"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button> step 2 - ")); Assert.assertTrue(detailedReportContent.contains( "<div class=\"box collapsed-box success\"><div class=\"box-header with-border\"><button type=\"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button> Test end - ")); Assert.assertTrue(detailedReportContent.contains( "<div class=\"box collapsed-box success\"><div class=\"box-header with-border\"><button type=\"button\" class=\"btn btn-box-tool\" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button> Execution logs")); Assert.assertTrue(detailedReportContent.contains("<div class=\"message-log\">Test is OK</div>")); // check logs are written only once Assert.assertEquals(StringUtils.countMatches(detailedReportContent, "[main] TestLogging: Test is OK</div>"), 1); }
From source file:com.entertailion.android.launcher.Dialogs.java
/** * Display dialog to the user for the browser bookmarks. Allow the user to add a * browser bookmark to an existing row or a new row. * //from w w w .j a v a2 s .co m * @param context */ public static void displayAddBrowserBookmark(final Launcher context) { final Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.add_browser_bookmarks_list); final EditText nameEditText = (EditText) dialog.findViewById(R.id.rowName); final RadioButton currentRadioButton = (RadioButton) dialog.findViewById(R.id.currentRadio); currentRadioButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // hide the row name edit field if the current row radio button // is selected nameEditText.setVisibility(View.GONE); } }); final RadioButton newRadioButton = (RadioButton) dialog.findViewById(R.id.newRadio); newRadioButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // show the row name edit field if the new radio button is // selected nameEditText.setVisibility(View.VISIBLE); nameEditText.requestFocus(); } }); ListView listView = (ListView) dialog.findViewById(R.id.list); final ArrayList<BookmarkInfo> bookmarks = loadBookmarks(context); Collections.sort(bookmarks, new Comparator<BookmarkInfo>() { @Override public int compare(BookmarkInfo lhs, BookmarkInfo rhs) { return lhs.getTitle().toLowerCase().compareTo(rhs.getTitle().toLowerCase()); } }); listView.setAdapter(new BookmarkAdapter(context, bookmarks)); listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { // run in thread since network logic needed to get bookmark icon new Thread(new Runnable() { public void run() { // if the new row radio button is selected, the user must enter // a name for the new row String name = nameEditText.getText().toString().trim(); if (newRadioButton.isChecked() && name.length() == 0) { nameEditText.requestFocus(); displayAlert(context, context.getString(R.string.dialog_new_row_name_alert)); return; } boolean currentRow = !newRadioButton.isChecked(); try { BookmarkInfo bookmark = (BookmarkInfo) parent.getAdapter().getItem(position); int rowId = 0; int rowPosition = 0; if (currentRow) { rowId = context.getCurrentGalleryId(); ArrayList<ItemInfo> items = ItemsTable.getItems(context, rowId); rowPosition = items.size(); // in last // position // for selected // row } else { rowId = (int) RowsTable.insertRow(context, name, 0, RowInfo.FAVORITE_TYPE); rowPosition = 0; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(bookmark.getUrl())); Uri uri = Uri.parse(bookmark.getUrl()); Log.d(LOG_TAG, "host=" + uri.getScheme() + "://" + uri.getHost()); String icon = Utils.getWebSiteIcon(context, "http://" + uri.getHost()); Log.d(LOG_TAG, "icon1=" + icon); if (icon == null) { // try base host address int count = StringUtils.countMatches(uri.getHost(), "."); if (count > 1) { int index = uri.getHost().indexOf('.'); String baseHost = uri.getHost().substring(index + 1); icon = Utils.getWebSiteIcon(context, "http://" + baseHost); Log.d(LOG_TAG, "icon2=" + icon); } } ItemsTable.insertItem(context, rowId, rowPosition, bookmark.getTitle(), intent, icon, DatabaseHelper.SHORTCUT_TYPE); } catch (Exception e) { Log.e(LOG_TAG, "displayAddBrowserBookmark", e); } // need to do this on UI thread context.getHandler().post(new Runnable() { public void run() { context.showCover(false); dialog.dismiss(); context.reloadAllGalleries(); } }); if (currentRow) { Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK); } else { Analytics.logEvent(Analytics.ADD_BROWSER_BOOKMARK_WITH_ROW); } } }).start(); } }); listView.setDrawingCacheEnabled(true); listView.setOnKeyListener(onKeyListener); dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { context.showCover(false); } }); context.showCover(true); dialog.show(); Analytics.logEvent(Analytics.DIALOG_ADD_BROWSER_BOOKMARK); }
From source file:com.joyent.manta.http.MantaHttpHeaders.java
/** * Translates the range request header into two values. The first value * is the starting bytes of the binary file to read and the second value * is the ending bytes of the file to read. If the range indicates the * end of a file (unlimited), then the end value will be set to null. * Likewise, if the start position is unknown, it will be set to null. * * This method may eventually be deprecated in favor of {@link HttpRange#parseRequestRange(String)} but * that refactoring is being deferred./*w w w . ja v a 2s . c o m*/ * * @return two value array containing the start and the end of a byte range as Long * * @see HttpRange#parseRequestRange(String) */ public Long[] getByteRange() { final String rangeString = getRange(); Validate.notNull(rangeString, "Range value must not be null"); String[] rangeValuesStrings = StringUtils.split(rangeString, "bytes="); Validate.isTrue(rangeValuesStrings.length == 1, "Range header value doesn't begin with string: bytes="); final String byteRange = rangeValuesStrings[0]; Validate.isTrue(StringUtils.split(byteRange, ",").length == 1, "Multi-range requests are not supported"); String[] rangeParts = StringUtils.split(byteRange, "-"); Validate.isTrue(StringUtils.countMatches(byteRange, "-") < 2, "Cannot end or start with a negative number"); Long startPos = null; Long endPos = null; if (StringUtils.startsWith(byteRange, "-")) { endPos = Long.parseLong(byteRange); } else if (StringUtils.endsWith(byteRange, "-")) { startPos = Long.parseLong(byteRange.split("-")[0]); } else if (rangeParts.length == 2) { startPos = Long.parseUnsignedLong(rangeParts[0]); endPos = Long.parseUnsignedLong(rangeParts[1]); } else { throw new IllegalArgumentException("range must exist with - separator"); } return new Long[] { startPos, endPos }; }
From source file:com.neatresults.mgnltweaks.json.JsonBuilderTest.java
/** * Lists specified properties only for expanded nodes but not for the parent nodes. *//*from w ww.jav a2 s . co m*/ @Test public void testMultiExpandNodePropertyListing() throws Exception { Node node = session.getNode("/home/section2/article/mgnl:apex"); node.addNode("blah", "mgnl:content"); catNode.setProperty("fooId", "123"); Session catSession = catNode.getSession(); Node cn2 = catSession.getRootNode().addNode("foo2name", "category"); cn2.setProperty("fooId", "456"); Node cn3 = catSession.getRootNode().addNode("foo3name", "category"); cn3.setProperty("fooId", "789"); catSession.save(); node.setProperty("foo1", "123"); node.setProperty("foo2", "456"); node.setProperty("foo3", "789"); node.save(); session.getWorkspace().copy(node.getPath(), node.getParent().getPath() + "/test2"); session.getWorkspace().copy(node.getPath(), node.getParent().getPath() + "/test3"); // WHEN String json = JsonTemplatingFunctions.from(node).expand("foo.", "category", "fooId").add("name", "@name") .down(1).print(); // THEN assertThat(json, startsWith("{")); assertThat(json, not(containsString("\"jcr:created\" : "))); assertThat(json, not(containsString("\"foobar\" : {"))); assertThat(json, containsString("\"@name\" : \"foo\"")); assertThat(json, containsString("\"@name\" : \"foo2name\"")); assertThat(json, containsString("\"@name\" : \"foo3name\"")); assertEquals(1, StringUtils.countMatches(json, "foo3name")); assertThat(json, endsWith("}")); }
From source file:com.seleniumtests.it.reporter.TestSeleniumTestsReporter2.java
/** * Check all actions done with driver are correctly displayed. This indirectly test the LogAction aspect * We check /* w w w . jav a 2 s . c o m*/ * - all HtmlElement action logging * - all composite actions logging * - all PictureElement action logging * * @throws Exception */ @Test(groups = { "it" }) public void testReportContainsDriverActions() throws Exception { executeSubTest(1, new String[] { "com.seleniumtests.it.stubclasses.StubTestClassForDriverTest" }, ParallelMode.METHODS, new String[] { "testDriver", "testDriverNativeActions", "testDriverNativeActionsWithoutOverride", "testDriverWithHtmlElementWithoutOverride" }); // read 'testDriver' report. This contains calls to HtmlElement actions String detailedReportContent1 = readTestMethodResultFile("testDriver"); Assert.assertTrue(detailedReportContent1.contains( "<li>sendKeys on TextFieldElement Text, by={By.id: text2} with args: (true, true, [a text,], )</li>")); Assert.assertTrue( detailedReportContent1.contains("<li>click on ButtonElement Reset, by={By.id: button2} </li>")); Assert.assertTrue(detailedReportContent1 .contains("<div class=\"message-snapshot\">Output: Current Window: Test page: <a href=")); // check that only on reference to 'click' is present for this buttonelement. This means that only the replayed action has been logged, not the ButtonElement.click() one Assert.assertEquals(StringUtils.countMatches(detailedReportContent1, "click on"), 1); // read the 'testDriverNativeActions' test result to see if native actions are also logged (overrideSeleniumNativeAction is true) String detailedReportContent2 = readTestMethodResultFile("testDriverNativeActions"); Assert.assertTrue(detailedReportContent2.contains( "<li>sendKeys on HtmlElement , by={By.id: text2} with args: (true, true, [some text,], )</li>")); Assert.assertTrue(detailedReportContent2.contains("<li>click on HtmlElement , by={By.id: button2} </li>")); // read the 'testDriverNativeActionsWithoutOverride' test result to see if native actions are not logged (overrideSeleniumNativeAction is false) String detailedReportContent3 = readTestMethodResultFile("testDriverNativeActionsWithoutOverride"); // logging is not done via HtmlElement Assert.assertFalse(detailedReportContent3.contains( "<li>sendKeys on HtmlElement , by={By.id: text2} with args: (true, true, [some text,], )</li>")); Assert.assertFalse(detailedReportContent3.contains("<li>click on HtmlElement , by={By.id: button2} </li>")); // check that without override, native actions are logged Assert.assertTrue(detailedReportContent3.contains( "<ul><li>sendKeys on Element located by id: text2 with args: ([some text,], )</li></ul>")); Assert.assertTrue( detailedReportContent3.contains("<ul><li>click on Element located by id: button2 </li></ul>")); Assert.assertTrue(detailedReportContent3 .contains("<ul><li>selectByVisibleText on Select with args: (option1, )</li></ul>")); // check composite actions. We must have the moveToElement, click and sendKeys actions Assert.assertTrue(detailedReportContent1.contains( "<ul><li>moveToElement with args: (TextFieldElement Text, by={By.id: text2}, )</li><li>sendKeys with args: ([composite,], )</li><li>moveToElement with args: (ButtonElement Reset, by={By.id: button2}, )</li><li>click </li></ul>")); // check PictureElement action is logged Assert.assertTrue(detailedReportContent1.contains( "<ul><li>clickAt on Picture picture from resource tu/images/logo_text_field.png with args: (0, -30, )</li>")); // check that when logging PictureElement action which uses composite actions, those are not logged Assert.assertFalse(detailedReportContent1.contains( "<ul><li>clickAt on Picture picture from resource tu/images/logo_text_field.png with args: (0, -30, )</li><li>moveToElement with args:")); // no action is logged when step fails (findElement exception). Ok because logging is done on action, not search // check that seleniumRobot actions are logged only once when overrideNativeAction is enabled (issue #88) String detailedReportContent4 = readTestMethodResultFile("testDriverWithHtmlElementWithoutOverride"); Assert.assertEquals(StringUtils.countMatches(detailedReportContent4, "<li>click on ButtonElement Reset, by={By.id: button2} </li>"), 1); // TODO: spliter ce test en plusieurs }