List of usage examples for org.apache.commons.lang StringUtils countMatches
public static int countMatches(String str, String sub)
Counts how many times the substring appears in the larger String.
From source file:com.redsqirl.workflow.server.action.dictionary.JdbcDictionary.java
@Override protected String runConditionalOperation(String expr, FieldList fields, Set<String> fieldAggreg) throws Exception { String cleanUp = removeBracketContent(expr); if (cleanUp.startsWith("CASE") && cleanUp.endsWith("END")) { return runCaseWhen(expr, fields, fieldAggreg); }//from w w w .jav a 2 s .c o m int i = 0; String[] fct = null; String[][] analyticFct = functionsMap.get(analyticMethods); boolean found = false; String firstArgs = getFirstBracketContent(expr).trim(); logger.debug(firstArgs); int nbArgGiven = 0; if (firstArgs != null && !firstArgs.isEmpty()) { nbArgGiven = getArguments(firstArgs, ",").length; } for (; i < analyticFct.length && !found; ++i) { String cur = removeBracketContent(analyticFct[i][0]); logger.debug("Compare " + cleanUp + " with " + cur); found = cleanUp.startsWith(cur); if (found) { int nbArg = 0; if (analyticFct[i][1] != null && !analyticFct[i][1].isEmpty()) { nbArg = StringUtils.countMatches(analyticFct[i][1], ",") + 1; } if (nbArgGiven != nbArg) { logger.debug("Argument number unexpected: " + nbArgGiven + " " + nbArg); found = false; } else { fct = new String[3]; fct[0] = new String(analyticFct[i][0]); fct[1] = analyticFct[i][1]; fct[2] = analyticFct[i][2]; fct[0] = removeBracketContent(fct[0].substring(0, fct[0].indexOf("OVER"))); } } } if (!found) { return null; } String arg = getFirstBracketContent(expr); if (fct[2].isEmpty() && !arg.isEmpty()) { throw new Exception("Function " + fct[0] + " expects arguments"); } else if (!fct[2].isEmpty() && !arg.isEmpty() && !check(fct, getArguments(arg, ","), fields)) { throw new Exception("Expression " + expr + " unrecognized function arguments"); } String tmpExpr = expr.replaceFirst(escapeString(arg), ""); String overExpr = tmpExpr.substring(tmpExpr.indexOf(")") + 1).trim(); if (!overExpr.toUpperCase().startsWith("OVER")) { throw new Exception("This function should be followed by a 'OVER' clause."); } String orderByExpr = overExpr.substring(4).trim(); if (!(orderByExpr.startsWith("(") && orderByExpr.endsWith(")"))) { throw new Exception("An OVER clause should be contained within brackets."); } orderByExpr = orderByExpr.substring(1, orderByExpr.lastIndexOf(")")).trim(); String partitionExpr = null; if (orderByExpr.toUpperCase().startsWith("PARTITION BY ")) { partitionExpr = orderByExpr.substring("PARTITION BY ".length(), orderByExpr.indexOf("ORDER BY")).trim(); orderByExpr = orderByExpr.substring(orderByExpr.indexOf("ORDER BY")).trim(); } logger.debug(orderByExpr); if (orderByExpr.toUpperCase().startsWith("ORDER BY ")) { orderByExpr = orderByExpr.substring("ORDER BY ".length()); } if (orderByExpr != null && !orderByExpr.isEmpty()) { String[] args = orderByExpr.split(","); for (int j = 0; j < args.length; ++j) { String argOrderCur = args[j]; if (argOrderCur.endsWith(" DESC")) { argOrderCur = argOrderCur.substring(0, argOrderCur.lastIndexOf(" DESC")); } else if (argOrderCur.endsWith(" ASC")) { argOrderCur = argOrderCur.substring(0, argOrderCur.lastIndexOf(" ASC")); } if (getReturnType(argOrderCur, fields, fieldAggreg) == null) { throw new Exception("Error in expression " + args[j]); } } } if (partitionExpr != null && !partitionExpr.isEmpty()) { String[] args = partitionExpr.split(","); for (int j = 0; j < args.length; ++j) { if (getReturnType(args[j], fields, fieldAggreg) == null) { throw new Exception("Error in expression " + args[j]); } } } return fct[2]; }
From source file:com.photon.phresco.impl.HtmlApplicationProcessor.java
@Override public boolean themeBuilderSave(ApplicationInfo appInfo, String jsonString) throws PhrescoException { boolean success = true; try {/*from www. ja v a 2 s . c o m*/ String themeFileExtension = getThemeFileExtension(appInfo); org.codehaus.jettison.json.JSONObject jsonObj = new org.codehaus.jettison.json.JSONObject(jsonString); String themeName = jsonObj.getString(Constants.THEME_NAME); String themePath = jsonObj.getString(Constants.THEME_PATH); StringBuilder themeLocation = new StringBuilder(themePath).append(themeName + themeFileExtension); boolean filesCopied = fetchImageUrlsToCopy(appInfo, jsonObj);//move selected images to the path specified in pom property if (filesCopied) { File cssFile = new File(themeLocation.toString()); if (!cssFile.exists()) { cssFile.createNewFile(); } CascadingStyleSheet css = ThemeBuilderReadCSS.readCSS30(cssFile); if (css != null) { List<ICSSTopLevelRule> allRules = css.getAllRules(); for (ICSSTopLevelRule icssTopLevelRule : allRules) { css.removeRule(icssTopLevelRule); } } JSONArray jsonArray = jsonObj.getJSONArray(Constants.THEME_CSS); for (int i = 0; i < jsonArray.length(); i++) {//iterate each rule from result json CSSStyleRule styleRule = new CSSStyleRule(); CSSSelector aSelector = new CSSSelector(); org.codehaus.jettison.json.JSONObject item = jsonArray.getJSONObject(i); String selector = item.getString(Constants.THEME_SELECTOR); ICSSSelectorMember icssmm = new CSSSelectorSimpleMember(selector); aSelector.addMember(icssmm); styleRule.addSelector(aSelector);//set selector JSONArray propertiesArray = item.getJSONArray(Constants.THEME_PROPERTIES); for (int j = 0; j < propertiesArray.length(); j++) { CSSExpression aExpression = new CSSExpression(); org.codehaus.jettison.json.JSONObject properties = propertiesArray.getJSONObject(j); String property = properties.getString(Constants.THEME_PROPERTY); String value = properties.getString(Constants.THEME_VALUE); String type = properties.getString(Constants.THEME_TYPE); if (Constants.THEME_IMAGE.equals(type)) {//if the type is image, then construct the url path String image = properties.getString(Constants.THEME_IMAGE); String imagePath = getThemeBuilderImagePath(appInfo); String[] splittedPath = themePath.split(Constants.SRC_MAIN_WEBAPP); int slashCount = StringUtils.countMatches(splittedPath[1], "/"); StringBuilder sb = new StringBuilder(); for (int k = 1; k <= slashCount; k++) {//append no of slashes based on the slashCount sb.append("../"); } String[] appendImageLocation = imagePath.split(Constants.SRC_MAIN_WEBAPP); sb.append(appendImageLocation[1])//append image location after ../ .append(File.separator).append(image); value = sb.toString().replace(File.separator, "/"); aExpression.addURI(value); } else { aExpression.addTermSimple(value);//set value } CSSDeclaration aDeclaration = new CSSDeclaration(property, aExpression, false);//declare property styleRule.addDeclaration(aDeclaration);//add declaration to CSSStyleRule object } css.addRule(styleRule); } ThemeBuilderWriteCSS.writeCSS30(css, cssFile); } else { success = false; } } catch (Exception e) { success = false; } return success; }
From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java
/** * Calculates the entity model for a nested property, recursively up till a certain depth * /*from w w w. ja va 2 s. c om*/ * @param model * the attribute model */ private void setNestedEntityModel(AttributeModelImpl model) { EntityModel<?> em = model.getEntityModel(); if (StringUtils.countMatches(em.getReference(), ".") < RECURSIVE_MODEL_DEPTH) { Class<?> type = null; // only needed for master and detail attributes if (AttributeType.MASTER.equals(model.getAttributeType())) { type = model.getType(); } else if (AttributeType.DETAIL.equals(model.getAttributeType())) { type = model.getMemberType(); } if (type != null) { String ref = null; if (StringUtils.isEmpty(em.getReference())) { ref = em.getEntityClass() + "." + model.getName(); } else { ref = em.getReference() + "." + model.getName(); } if (type.equals(em.getEntityClass()) || !hasEntityModel(type, ref)) { EntityModel<?> nem = getModel(ref, type); model.setNestedEntityModel(nem); } } } }
From source file:com.etak.csrTestFirefox.steps.DashboardSteps.java
@Step public void checkCustWithNoTT() { int totalTT = countTT(); String table = dashboardPage.getDriver().getPageSource(); String tableProd = table.substring(table.indexOf("dashboard_TTtable"), table.indexOf("</table>")); String prodPg = tableProd.substring(tableProd.indexOf("<tbody>"), tableProd.indexOf("</tbody>")); int count = StringUtils.countMatches(prodPg, "<tr"); logger.info("Expected: " + totalTT + ". Actual: " + count); if (totalTT == 0 && count == 0) { assert true; } else {//from w ww . ja va2 s .co m killSession(); assert false; } }
From source file:com.novartis.opensource.yada.test.ServiceTest.java
/** * Tests many aspects of {@code harmonyMap} or {@code h} YADA parameter results including * for CSV: column counts, header values, row counts, row/column content; and for JSON: * singular result set, correct mapped/unmapped keys and values, record count. * @param query the query to execute/*from ww w . j av a 2s. c om*/ * @throws YADAQueryConfigurationException when request creation fails * @throws YADAResponseException when the test result is invalid */ @Test(enabled = true, dataProvider = "QueryTests", groups = { "options" }) @QueryFile(list = {}) public void testHarmonizer(String query) throws YADAQueryConfigurationException, YADAResponseException { String[] allKeys = { COL_INTEGER, COL_INTEGER_LC, COL_HM_INT, COL_NUMBER, COL_NUMBER_LC, COL_HM_FLOAT, COL_DATE, COL_DATE_LC, COL_HM_DATE, COL_TIME, COL_TIME_LC, COL_HM_TIME }; String[] intKeys = { COL_INTEGER, COL_INTEGER_LC, COL_HM_INT }; String[] floatKeys = { COL_NUMBER, COL_NUMBER_LC, COL_HM_FLOAT }; String[] dateKeys = { COL_DATE, COL_DATE_LC, COL_HM_DATE }; String[] timeKeys = { COL_TIME, COL_TIME_LC, COL_HM_TIME }; Service svc = prepareTest(query); YADARequest req = svc.getYADARequest(); req.setPageSize(new String[] { "-1" }); JSONArray spec = req.getHarmonyMap(); String result = svc.execute(); int qCount = StringUtils.countMatches(query, "qname") + StringUtils.countMatches(query, "q="); String line = null; int lineCount = 0; if (req.getFormat().equals(YADARequest.FORMAT_CSV)) { logStringResult(result); Pattern rx = Pattern.compile( "^(\"([A-Z,]+)\"),(\"([0-9]+)\")?,(\"([0-9.]+)\")?,?(\"(201[3-5]-0[0-9]-[0-9]{2}(\\s00:00:00)?|1362373200|1396584000)\")?,?(\"(201[3-5]-0[0-9]-[0-9]{2} ([0-9]{2}:){2}[0-9]{2}|1441500273000)(\\.0)?\")?$"); // count columns // check for correct values in mapped columns try (BufferedReader br = new BufferedReader(new StringReader(result))) { while ((line = br.readLine()) != null) { if (lineCount > 0) { Matcher m = rx.matcher(line); Assert.assertTrue(m.matches()); // first query only returns three columns if (lineCount < 9) { Assert.assertTrue(validateInteger(m.group(4))); // col 2 Assert.assertTrue(validateNumber(m.group(6))); // col 3 Assert.assertNull(m.group(8)); // col 4 Assert.assertNull(m.group(11)); // col 5 } else if (lineCount > 8 && lineCount < 17) // 2nd query { Assert.assertNull(m.group(4)); // col 2 Assert.assertNull(m.group(6)); // col 3 Assert.assertTrue(validateDate(m.group(8))); // col4 Assert.assertTrue(validateTime(m.group(11))); // col5 } else // 3rd query { Assert.assertNull(m.group(4)); // col 2 Assert.assertNull(m.group(6)); // col 3 Assert.assertNull(m.group(8)); // col 4 Assert.assertTrue(validateTime(m.group(11))); // col5 } } lineCount++; } } catch (IOException e) { throw new YADAResponseException("Result was unreadable.", e); } catch (ParseException e) { throw new YADAResponseException("Result was unparsable.", e); } //TODO confirm correct mapped/unmapped column headers // count rows Assert.assertEquals(lineCount - 1, qCount * 8); //TODO check for "empty values" in unmapped columns } else if (req.getFormat().equals(YADARequest.FORMAT_XML)) { //TODO harmony map xml validation logMarkupResult(result); } else if (req.getFormat().equals(YADARequest.FORMAT_HTML)) { logMarkupResult(result); Pattern rx = Pattern.compile( "^<tr>(<td>([A-Z,]+)</td>)(<td>([0-9]+)?</td>)(<td>([0-9.]+)?</td>)(<td>(201[3-5]-0[0-9]-[0-9]{2}(\\s00:00:00)?|1362373200|1396584000)?</td>)?(<td>((201[3-5]-0[0-9]-[0-9]{2} ([0-9]{2}:){2}[0-9]{2}|1441500273000)(\\.0)?)?</td>)?</tr>$"); Pattern end = Pattern.compile("^</tbody>|</table>|</body>|</html>$"); try (BufferedReader br = new BufferedReader(new StringReader(result))) { while ((line = br.readLine()) != null) { Matcher mEnd = end.matcher(line); if (lineCount > 9 && !mEnd.matches()) { Matcher m = rx.matcher(line); Assert.assertTrue(m.matches()); // first query only returns three columns if (lineCount < 18) { Assert.assertTrue(validateInteger(m.group(4))); // col 2 Assert.assertTrue(validateNumber(m.group(6))); // col 3 Assert.assertNull(m.group(8)); // col 4 Assert.assertNull(m.group(11)); // col 5 } else if (lineCount > 17 && lineCount < 26) // 2nd query { Assert.assertNull(m.group(4)); // col 2 Assert.assertNull(m.group(6)); // col 3 Assert.assertTrue(validateDate(m.group(8))); // col4 Assert.assertTrue(validateTime(m.group(11))); // col5 } else // 3rd query { Assert.assertNull(m.group(4)); // col 2 Assert.assertNull(m.group(6)); // col 3 Assert.assertNull(m.group(8)); // col 4 Assert.assertTrue(validateTime(m.group(11))); // col5 } } else { //TODO confirm correct mapped/unmapped column headers } lineCount++; } } catch (IOException e) { throw new YADAResponseException("Result was unreadable.", e); } catch (ParseException e) { throw new YADAResponseException("Result was unparsable.", e); } // count rows Assert.assertEquals(lineCount - 1, (qCount * 8) + 13); // adding 13 for non-data row html tags } else // JSON { JSONParamsEntry q; YADAParam p; qCount = 1; int resultCount = 8; if (YADAUtils.useJSONParams(req)) { JSONParams jp = req.getJsonParams(); String[] qnameKeys = jp.getKeys(); qCount = qnameKeys.length; for (String qname : qnameKeys) { q = jp.get(qname); p = q.getParam(YADARequest.PS_HARMONYMAP); if (null == spec) spec = new JSONArray(); if (null != p) spec.put(new JSONObject(p.getValue())); } } JSONObject jo = new JSONObject(result); logJSONResult(jo); // confirm singular result set Assert.assertNull(jo.optJSONObject(RESULTSETS)); Assert.assertTrue(jo.has(RESULTSET)); // // check record count int actualRecCount = jo.getJSONObject(RESULTSET).getInt(RECORDS); int expectRecCount = qCount * resultCount; Assert.assertEquals(actualRecCount, expectRecCount, "Result count invalid for query: " + query); // confirm correct mapped/unmapped keys JSONArray rows = jo.getJSONObject(RESULTSET).getJSONArray(ROWS); // For each query, find the hmap // test 8 records corresponding to query index // NOTE: This does not test for presence of unmapped keys, but does test all values for (int i = 0; i < rows.length() / 8; i++) // 1-3 sets of 8 { JSONObject currentSpec = new JSONObject(); // the hmap spec if (spec.length() == 1) currentSpec = spec.getJSONObject(0); // it's a global request param else { for (int j = spec.length() - 1; j >= 0; j--) { currentSpec = spec.getJSONObject(j); // it's an embedded param, and JSONArray returns in reverse order } } // Deconstruct spec into keys and vals String[] currentSpecKeys = new String[currentSpec.length()]; String[] currentSpecVals = new String[currentSpec.length()]; int j = 0; if (currentSpec.length() > 0) { for (String key : JSONObject.getNames(currentSpec)) { currentSpecKeys[j] = key; currentSpecVals[j] = currentSpec.getString(key); j++; } } // check results for (j = 0; j < resultCount; j++) // for each set of results { JSONObject row = rows.getJSONObject(j); // the "row" String[] rowKeys = JSONObject.getNames(row); for (String key : rowKeys) // iterate over the row keys { if (key.matches("[A-Z]+")) // upper case are spec vals Assert.assertTrue(ArrayUtils.contains(currentSpecVals, key)); // row key is in current spec vals else { Assert.assertFalse(ArrayUtils.contains(currentSpecVals, key)); // row key is not current spec vals Assert.assertFalse(ArrayUtils.contains(currentSpecKeys, key)); // row key is in current spec keys } } for (String col : allKeys) // confirm datatype of values { if (row.has(col)) { try { if (ArrayUtils.contains(intKeys, col)) Assert.assertTrue(validateInteger(row.getString(col))); else if (ArrayUtils.contains(floatKeys, col)) Assert.assertTrue(validateNumber(row.getString(col))); else if (ArrayUtils.contains(dateKeys, col)) Assert.assertTrue(validateDate(row.getString(col))); else if (ArrayUtils.contains(timeKeys, col)) Assert.assertTrue(validateTime(row.getString(col))); } catch (ParseException e) { String msg = "Unable to validate result."; throw new YADAResponseException(msg, e); } } } } } } }
From source file:com.stratelia.silverpeas.silverStatisticsPeas.control.SilverStatisticsPeasSessionController.java
/** * Retrieve statistics on axis/*from ww w .ja v a2 s . com*/ * * @param statsFilter an axis stats filter * @return a Statistic value object */ public List<StatisticVO> getAxisStats(AxisStatsFilter statsFilter) { // Result list List<StatisticVO> stats = new ArrayList<StatisticVO>(); // Retrieve all the list of components List<String> components = buildCustomComponentListWhereToSearch(); // Global silver content declaration List<GlobalSilverContent> gSC = null; int curAxisId = statsFilter.getAxisId(); try { // Build day query String firstDayStr = statsFilter.getYearBegin() + "/" + statsFilter.getMonthBegin() + "/01"; String lastDayStr = statsFilter.getYearEnd() + "/" + statsFilter.getMonthEnd() + "/31"; // Retrieve statistics on componentIds List<AccessPublicationVO> accessPublis = SilverStatisticsPeasDAO.getListPublicationAccess(firstDayStr, lastDayStr); if (curAxisId == 0) { // Retrieve publication axis List<AxisHeader> axis = getPdcBm().getAxisByType("P"); // Retrieve publications on axis for (AxisHeader axisHeader : axis) { String axisId = axisHeader.getPK().getId(); int nbAxisAccess = 0; // String axisVlue = axisHeader.get gSC = getPdCPublications(axisId, "/0/", components); nbAxisAccess = computeAxisAccessStatistics(accessPublis, gSC); StatisticVO curStat = new StatisticVO(axisId, axisHeader.getName(), axisHeader.getDescription(), nbAxisAccess); stats.add(curStat); } } else { String axisValue = statsFilter.getAxisValue(); boolean axisFilter = false; int curLevel = 1; if (StringUtil.isDefined(axisValue)) { axisFilter = true; // Retrieve current value level + 1 curLevel = StringUtils.countMatches(axisValue, "/") - 1; } List<Value> values = getPdcBm().getAxisValues(statsFilter.getAxisId()); for (Value curValue : values) { String curAxisValue = curValue.getFullPath(); int nbAxisAccess = 0; // Check axis level number if (axisFilter && curAxisValue.startsWith(axisValue) && curValue.getLevelNumber() == curLevel) { // Retrieve all the current axis publications gSC = getPdCPublications(Integer.toString(curAxisId), curAxisValue, components); nbAxisAccess = computeAxisAccessStatistics(accessPublis, gSC); // Create a new statistic value object StatisticVO curStat = new StatisticVO(Integer.toString(curAxisId), curValue.getName(), curValue.getDescription(), nbAxisAccess); curStat.setAxisValue(curValue.getFullPath()); curStat.setAxisLevel(curValue.getLevelNumber()); // Add this statistic to list stats.add(curStat); } else if (!axisFilter && curValue.getLevelNumber() == 1) { // Retrieve all the current axis publications gSC = getPdCPublications(Integer.toString(curAxisId), curAxisValue, components); nbAxisAccess = computeAxisAccessStatistics(accessPublis, gSC); // Create a new statistic value object StatisticVO curStat = new StatisticVO(Integer.toString(curAxisId), curValue.getName(), curValue.getDescription(), nbAxisAccess); curStat.setAxisValue(curValue.getFullPath()); curStat.setAxisLevel(curValue.getLevelNumber()); // Add this statistic to list stats.add(curStat); } } } } catch (PdcException e) { SilverTrace.error("SilverStatisticsPeas", SilverStatisticsPeasSessionController.class.getName() + ".getAxisStats", "Problem to access the PDC"); } catch (SQLException sqlEx) { SilverTrace.error("SilverStatisticsPeas", SilverStatisticsPeasSessionController.class.getName() + ".getAxisStats", "Problem to retrieve statistics on axis."); } return stats; }
From source file:com.ibm.bi.dml.parser.python.PydmlSyntacticValidator.java
private ConvertedDMLSyntax convertPythonBuiltinFunctionToDMLSyntax(String namespace, String functionName, ArrayList<ParameterExpression> paramExpression, List<ParameterizedExpressionContext> paramCtx, Token fnName, String fileName, int line, int col) { // =========================================================================================== // Check function name, namespace, parameters (#params & possible values) and throw useful hints if (inDefaultNamespace(namespace) && functionName.compareTo("len") == 0) { if (paramExpression.size() != 1) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts 1 arguments", fnName);//w w w . j av a 2s .co m return null; } functionName = "length"; } else if (functionName.compareTo("sum") == 0 || functionName.compareTo("mean") == 0 || functionName.compareTo("avg") == 0 || functionName.compareTo("min") == 0 || functionName.compareTo("max") == 0 || functionName.compareTo("argmax") == 0 || functionName.compareTo("argmin") == 0 || functionName.compareTo("cumsum") == 0 || functionName.compareTo("transpose") == 0 || functionName.compareTo("trace") == 0) { // 0 maps row-wise computation and 1 maps to column-wise computation // can mean sum of all cells or row-wise or columnwise sum if (inDefaultNamespace(namespace) && paramExpression.size() == 1) { // sum(x) => sum(x) // otherwise same function name if (functionName.compareTo("avg") == 0) { functionName = "mean"; } else if (functionName.compareTo("transpose") == 0) { functionName = "t"; } else if (functionName.compareTo("argmax") == 0 || functionName.compareTo("argmin") == 0 || functionName.compareTo("cumsum") == 0) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' for entire matrix is not supported", fnName); return null; } } else if (!inDefaultNamespace(namespace) && paramExpression.size() == 0) { // x.sum() => sum(x) paramExpression = new ArrayList<ParameterExpression>(); paramExpression.add(new ParameterExpression(null, new DataIdentifier(namespace))); // otherwise same function name if (functionName.compareTo("avg") == 0) { functionName = "mean"; } else if (functionName.compareTo("transpose") == 0) { functionName = "t"; } else if (functionName.compareTo("argmax") == 0 || functionName.compareTo("argmin") == 0 || functionName.compareTo("cumsum") == 0) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' for entire matrix is not supported", fnName); return null; } } else if (inDefaultNamespace(namespace) && paramExpression.size() == 2) { // sum(x, axis=1) => rowSums(x) int axis = getAxis(paramCtx.get(1)); if (axis == -1 && (functionName.compareTo("min") == 0 || functionName.compareTo("max") == 0)) { // Do nothing // min(2, 3) } else if (axis == -1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' for given arguments is not supported", fnName); return null; } else { ArrayList<ParameterExpression> temp = new ArrayList<ParameterExpression>(); temp.add(paramExpression.get(0)); paramExpression = temp; functionName = getPythonAggFunctionNames(functionName, axis); if (functionName.compareTo("Not Supported") == 0) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' for given arguments is not supported", fnName); return null; } } } else if (!inDefaultNamespace(namespace) && paramExpression.size() == 1) { // x.sum(axis=1) => rowSums(x) int axis = getAxis(paramCtx.get(0)); if (axis == -1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' for given arguments is not supported", fnName); return null; } else { paramExpression = new ArrayList<ParameterExpression>(); paramExpression.add(new ParameterExpression(null, new DataIdentifier(namespace))); functionName = getPythonAggFunctionNames(functionName, axis); if (functionName.compareTo("Not Supported") == 0) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' for given arguments is not supported", fnName); return null; } } } else { helper.notifyErrorListeners( "Incorrect number of arguments for the builtin function \'" + functionName + "\'.", fnName); return null; } namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("concatenate") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts 2 arguments (Note: concatenate append columns of two matrices)", fnName); return null; } functionName = "append"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("minimum") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts 2 arguments", fnName); return null; } functionName = "min"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("maximum") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts 2 arguments", fnName); return null; } functionName = "max"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (!inDefaultNamespace(namespace) && functionName.compareTo("shape") == 0) { if (paramExpression.size() != 1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts only 1 argument (0 or 1)", fnName); return null; } int axis = getAxis(paramCtx.get(0)); if (axis == -1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts only 1 argument (0 or 1)", fnName); return null; } paramExpression = new ArrayList<ParameterExpression>(); paramExpression.add(new ParameterExpression(null, new DataIdentifier(namespace))); namespace = DMLProgram.DEFAULT_NAMESPACE; if (axis == 0) { functionName = "nrow"; } else if (axis == 1) { functionName = "ncol"; } } else if (inDefaultNamespace(namespace) && functionName.compareTo("random.normal") == 0) { if (paramExpression.size() != 3) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 3 arguments (number of rows, number of columns, sparsity)", fnName); return null; } paramExpression.get(0).setName("rows"); paramExpression.get(1).setName("cols"); paramExpression.get(2).setName("sparsity"); paramExpression.add(new com.ibm.bi.dml.parser.ParameterExpression("pdf", new StringIdentifier("normal", fileName, line, col, line, col))); functionName = "rand"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("random.uniform") == 0) { if (paramExpression.size() != 5) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 5 arguments (number of rows, number of columns, sparsity, min, max)", fnName); return null; } paramExpression.get(0).setName("rows"); paramExpression.get(1).setName("cols"); paramExpression.get(2).setName("sparsity"); paramExpression.get(3).setName("min"); paramExpression.get(4).setName("max"); paramExpression.add(new com.ibm.bi.dml.parser.ParameterExpression("pdf", new StringIdentifier("uniform", fileName, line, col, line, col))); functionName = "rand"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("full") == 0) { if (paramExpression.size() != 3) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 3 arguments (constant double value, number of rows, number of columns)", fnName); return null; } paramExpression.get(1).setName("rows"); paramExpression.get(2).setName("cols"); functionName = "matrix"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("matrix") == 0) { // This can either be string initializer or as.matrix function if (paramExpression.size() != 1) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 1 argument (either string or double value)", fnName); return null; } if (paramExpression.get(0).getExpr() instanceof StringIdentifier) { String initializerString = ((StringIdentifier) paramExpression.get(0).getExpr()).getValue().trim(); if (!initializerString.startsWith("[") || !initializerString.endsWith("]")) { helper.notifyErrorListeners("Incorrect initializer string for builtin function \'" + functionName + "\' (Eg: matrix(\"[1 2 3; 4 5 6]\"))", fnName); return null; } int rows = StringUtils.countMatches(initializerString, ";") + 1; // Make sure user doesnot have pretty string initializerString = initializerString.replaceAll("; ", ";"); initializerString = initializerString.replaceAll(" ;", ";"); initializerString = initializerString.replaceAll("\\[ ", "\\["); initializerString = initializerString.replaceAll(" \\]", "\\]"); // Each row has ncol-1 spaces // #spaces = nrow * (ncol-1) // ncol = (#spaces / nrow) + 1 int cols = (StringUtils.countMatches(initializerString, " ") / rows) + 1; initializerString = initializerString.replaceAll(";", " "); initializerString = initializerString.replaceAll("\\[", ""); initializerString = initializerString.replaceAll("\\]", ""); paramExpression = new ArrayList<ParameterExpression>(); paramExpression.add(new ParameterExpression(null, new StringIdentifier(initializerString, fileName, line, col, line, col))); paramExpression.add( new ParameterExpression("rows", new IntIdentifier(rows, fileName, line, col, line, col))); paramExpression.add( new ParameterExpression("cols", new IntIdentifier(cols, fileName, line, col, line, col))); } else { functionName = "as.matrix"; } namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("scalar") == 0) { if (paramExpression.size() != 1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 1 argument", fnName); return null; } functionName = "as.scalar"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("float") == 0) { if (paramExpression.size() != 1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 1 argument", fnName); return null; } functionName = "as.double"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("int") == 0) { if (paramExpression.size() != 1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 1 argument", fnName); return null; } functionName = "as.integer"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("bool") == 0) { if (paramExpression.size() != 1) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 1 argument", fnName); return null; } functionName = "as.logical"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (!inDefaultNamespace(namespace) && functionName.compareTo("reshape") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 2 arguments (number of rows, number of columns)", fnName); return null; } paramExpression.get(0).setName("rows"); paramExpression.get(1).setName("cols"); ArrayList<ParameterExpression> temp = new ArrayList<ParameterExpression>(); temp.add(new ParameterExpression(null, new DataIdentifier(namespace))); temp.add(paramExpression.get(0)); temp.add(paramExpression.get(1)); paramExpression = temp; functionName = "matrix"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("removeEmpty") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 2 arguments (matrix, axis=0 or 1)", fnName); return null; } int axis = getAxis(paramCtx.get(1)); if (axis == -1) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 2 arguments (matrix, axis=0 or 1)", fnName); return null; } StringIdentifier marginVal = null; if (axis == 0) { marginVal = new StringIdentifier("rows", fileName, line, col, line, col); } else { marginVal = new StringIdentifier("cols", fileName, line, col, line, col); } paramExpression.get(0).setName("target"); paramExpression.get(1).setName("margin"); paramExpression.get(1).setExpr(marginVal); functionName = "removeEmpty"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("replace") == 0) { if (paramExpression.size() != 3) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 3 arguments (matrix, scalar value that should be replaced (pattern), scalar value (replacement))", fnName); return null; } paramExpression.get(0).setName("target"); paramExpression.get(1).setName("pattern"); paramExpression.get(2).setName("replacement"); functionName = "replace"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("range") == 0) { if (paramExpression.size() != 3) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 3 arguments (matrix, scalar value that should be replaced (pattern), scalar value (replacement))", fnName); return null; } functionName = "seq"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("norm.cdf") == 0) { if (paramExpression.size() != 3) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 3 arguments (target, mean, sd)", fnName); return null; } functionName = "cumulativeProbability"; paramExpression.get(0).setName("target"); paramExpression.get(1).setName("mean"); paramExpression.get(2).setName("sd"); paramExpression.add(new ParameterExpression("dist", new StringIdentifier("normal", fileName, line, col, line, col))); namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("expon.cdf") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 2 arguments (target, mean)", fnName); return null; } functionName = "cumulativeProbability"; paramExpression.get(0).setName("target"); paramExpression.get(1).setName("mean"); paramExpression.add( new ParameterExpression("dist", new StringIdentifier("exp", fileName, line, col, line, col))); namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("chi.cdf") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 2 arguments (target, df)", fnName); return null; } functionName = "cumulativeProbability"; paramExpression.get(0).setName("target"); paramExpression.get(1).setName("df"); paramExpression.add( new ParameterExpression("dist", new StringIdentifier("chisq", fileName, line, col, line, col))); namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("f.cdf") == 0) { if (paramExpression.size() != 3) { helper.notifyErrorListeners("The builtin function \'" + functionName + "\' accepts exactly 3 arguments (target, df1, df2)", fnName); return null; } functionName = "cumulativeProbability"; paramExpression.get(0).setName("target"); paramExpression.get(1).setName("df1"); paramExpression.get(2).setName("df2"); paramExpression.add( new ParameterExpression("dist", new StringIdentifier("f", fileName, line, col, line, col))); namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("t.cdf") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 2 arguments (target, df)", fnName); return null; } functionName = "cumulativeProbability"; paramExpression.get(0).setName("target"); paramExpression.get(1).setName("df"); paramExpression.add( new ParameterExpression("dist", new StringIdentifier("t", fileName, line, col, line, col))); namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("percentile") == 0) { if (paramExpression.size() != 2 && paramExpression.size() != 3) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts either 2 or 3 arguments", fnName); return null; } functionName = "quantile"; namespace = DMLProgram.DEFAULT_NAMESPACE; } else if (inDefaultNamespace(namespace) && functionName.compareTo("arcsin") == 0) { functionName = "asin"; } else if (inDefaultNamespace(namespace) && functionName.compareTo("arccos") == 0) { functionName = "acos"; } else if (inDefaultNamespace(namespace) && functionName.compareTo("arctan") == 0) { functionName = "atan"; } else if (inDefaultNamespace(namespace) && functionName.compareTo("load") == 0) { functionName = "read"; } else if (inDefaultNamespace(namespace) && functionName.compareTo("eigen") == 0) { functionName = "eig"; } else if (inDefaultNamespace(namespace) && functionName.compareTo("power") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 2 arguments", fnName); return null; } } else if (inDefaultNamespace(namespace) && functionName.compareTo("dot") == 0) { if (paramExpression.size() != 2) { helper.notifyErrorListeners( "The builtin function \'" + functionName + "\' accepts exactly 2 arguments", fnName); return null; } } ConvertedDMLSyntax retVal = new ConvertedDMLSyntax(); retVal.namespace = namespace; retVal.functionName = functionName; retVal.paramExpression = paramExpression; return retVal; }
From source file:fsi_admin.admon.JAyudaPaginaDlg.java
private String generarIndiceReportes(String t_cuerpo, String remplazo, String interfaz, String color, String href) throws IOException { //carga el archivo de ayuda que contienen la plantilla completa String ps = ""; FileReader file = new FileReader("/usr/local/forseti/bin/forseti_doc/indice_reportes.html"); BufferedReader buff = new BufferedReader(file); boolean eof = false; while (!eof) { String line = buff.readLine(); if (line == null) eof = true;//from w w w .j a va2 s .c om else ps += line + "\n"; } buff.close(); file.close(); buff = null; file = null; // extrae el inicio de la plantilla int ini_index = ps.indexOf("<!--_ini_modulos-->"); String p_inicio = ps.substring(0, ini_index); // extrae los mdulos ini_index += 19; int fin_index = ps.indexOf("<!--_fin_modulos-->"); String p_modulos = ps.substring(ini_index, fin_index); //extrae los submodulos ini_index = ps.indexOf("<!--_ini_submodulos-->") + 22; fin_index = ps.indexOf("<!--_fin_submodulos-->"); String p_submodulos = ps.substring(ini_index, fin_index); //extrae los reportes ini_index = ps.indexOf("<!--_ini_reportes-->") + 20; fin_index = ps.indexOf("<!--_fin_reportes-->"); String p_reportes = ps.substring(ini_index, fin_index); //extrae el fin de la plantilla ini_index = fin_index + 20; String p_final = ps.substring(ini_index); String cuerpo = ""; String nbd = ""; if (interfaz.equals("CEF")) { //System.out.println("Reportes del CEF"); JAdmVariablesSet var = new JAdmVariablesSet(null); var.ConCat(true); var.m_Where = "ID_Variable = 'IDEMPAYUDA'"; var.Open(); JBDSSet set = new JBDSSet(null); set.ConCat(true); set.m_Where = "ID_BD = '" + var.getAbsRow(0).getVEntero() + "'"; set.Open(); if (set.getNumRows() == 0) return JUtil.replace(t_cuerpo, "fsi-cuerpo-todo", " "); if (!set.getAbsRow(0).getSU().equals("3")) return JUtil.replace(t_cuerpo, "fsi-cuerpo-todo", " "); nbd = set.getAbsRow(0).getNombre(); } JUsuariosPermisosCatalogoSet pc = new JUsuariosPermisosCatalogoSet(null); if (interfaz.equals("SAF")) pc.ConCat(true); else { pc.ConCat(3); pc.setBD(nbd); } pc.Open(); for (int p = 0; p < pc.getNumRows(); p++) { if (pc.getAbsRow(p).getID_Permiso().indexOf('_', 0) == -1) { String modulos = p_modulos; modulos = JUtil.replace(modulos, "fsi-color-modulo", color); modulos = JUtil.replace(modulos, "_modulo", pc.getAbsRow(p).getModulo()); cuerpo += modulos + "\n"; JUsuariosPermisosCatalogoSet pct = new JUsuariosPermisosCatalogoSet(null); if (interfaz.equals("SAF")) pct.ConCat(true); else { pct.ConCat(3); pct.setBD(nbd); } pct.m_Where = "ID_Permiso LIKE '" + JUtil.p(pc.getAbsRow(p).getID_Permiso()) + "_%'"; pct.Open(); for (int i = 0; i < pct.getNumRows(); i++) { if (StringUtils.countMatches(pct.getAbsRow(i).getID_Permiso(), "_") == 1) { String submodulos = p_submodulos; submodulos = JUtil.replace(submodulos, "_submodulo", pct.getAbsRow(i).getModulo()); cuerpo += submodulos + "\n"; JReportesSet prm = new JReportesSet(null); if (interfaz.equals("SAF")) prm.ConCat(true); else { prm.ConCat(3); prm.setBD(nbd); } prm.m_OrderBy = "ID_Report ASC"; prm.m_Where = "Tipo = '" + JUtil.p(pct.getAbsRow(i).getID_Permiso()) + "'"; prm.Open(); //System.out.println(prm.getSQL()); for (int k = 0; k < prm.getNumRows(); k++) { String reportes = p_reportes; reportes = JUtil.replace(reportes, "_href_reporte", href + "-" + prm.getAbsRow(k).getID_Report() + ".html"); reportes = JUtil.replace(reportes, "_clave_reporte", Integer.toString(prm.getAbsRow(k).getID_Report())); reportes = JUtil.replace(reportes, "_descripcion_reporte", prm.getAbsRow(k).getDescription()); reportes = JUtil.replace(reportes, "_graficar_reporte", (prm.getAbsRow(k).getGraficar() ? "<img src=\"../forsetidoc/IMG/chart.png\" style=\"border:0px solid;margin:0px;\" />" : " ")); cuerpo += reportes + "\n"; } } } } } String pagina = p_inicio + "\n" + cuerpo + "\n" + p_final; return JUtil.replace(t_cuerpo, "fsi-cuerpo-todo", pagina); }
From source file:com.gtwm.pb.servlets.ServletSchemaMethods.java
public synchronized static void addCalculationToReport(SessionDataInfo sessionData, HttpServletRequest request, DatabaseInfo databaseDefn) throws DisallowedException, MissingParametersException, ObjectNotFoundException, SQLException, CantDoThatException, CodingErrorException { BaseReportInfo baseReport = ServletUtilMethods.getReportForRequest(sessionData, request, databaseDefn, ServletUtilMethods.USE_SESSION); if (!(baseReport instanceof SimpleReportInfo)) { throw new CantDoThatException("You can only add calculations to normal reports, not union reports"); }// w w w .j a va 2 s . c om SimpleReportInfo report = (SimpleReportInfo) baseReport; String internalCalculationName = request.getParameter("internalcalculationname"); String calculationName = request.getParameter("calculationname"); String calculationDefn = request.getParameter("calculationdefn"); String dbType = request.getParameter("databasetype"); if (calculationName == null || calculationDefn == null || dbType == null) { throw new MissingParametersException( "'calculationname', 'calculationdefn' and 'databasetype' parameters needed in request to add a calculation"); } // begin updating model and persisting changes ReportCalcFieldInfo newCalculationField = null; Connection conn = null; try { HibernateUtil.startHibernateTransaction(); conn = databaseDefn.getDataSource().getConnection(); conn.setAutoCommit(false); // create the new field DatabaseFieldType databaseType = DatabaseFieldType.valueOf(dbType.toUpperCase(Locale.UK)); Map<TableInfo, Set<BaseReportInfo>> availableDataStores = databaseDefn.getViewableDataStores(request); newCalculationField = new ReportCalcFieldDefn(report, internalCalculationName, calculationName, calculationDefn, databaseType, availableDataStores); databaseDefn.addCalculationToReport(request, conn, report, newCalculationField); conn.commit(); HibernateUtil.currentSession().getTransaction().commit(); } catch (SQLException sqlex) { rollbackConnections(conn); // remove calculation from memory if (newCalculationField != null) { report.removeField(newCalculationField); } String message = sqlex.getMessage(); int bracketDifference = 0; if (message.contains("syntax error at or near \")\"")) { bracketDifference = -1; } else { bracketDifference = StringUtils.countMatches(message, "(") - StringUtils.countMatches(message, ")"); } if (bracketDifference != 0) { String word; if (Math.abs(bracketDifference) == 1) { word = "is "; } else { word = "are "; } if (bracketDifference > 0) { message = "It looks like brackets may not match - there " + word + bracketDifference + " closing bracket(s) missing"; } else { message = "It looks like brackets may not match - there " + word + bracketDifference + " more closing bracket(s) than opening brackets"; } } throw new CantDoThatException( "Calculation addition failed. " + Helpers.replaceInternalNames(message, report), sqlex); } catch (HibernateException hex) { rollbackConnections(conn); // remove calculation from memory if (newCalculationField != null) { report.removeField(newCalculationField); } throw new CantDoThatException("Calculation addition failed. " + hex.getMessage(), hex); } catch (AgileBaseException pex) { rollbackConnections(conn); // remove calculation from memory if (newCalculationField != null) { report.removeField(newCalculationField); } throw new CantDoThatException("Calculation addition failed. " + pex.getMessage(), pex); } finally { conn.close(); HibernateUtil.closeSession(); } }
From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java
/** * @param oldDBConn//from w w w. j av a 2s.c o m * @param newDBConn */ private LatLonConverter.FORMAT discoverUnitType(final String latLonStr) { LatLonConverter.FORMAT fmt = LatLonConverter.FORMAT.None; if (StringUtils.isNotEmpty(latLonStr)) { int colonCnt = StringUtils.countMatches(latLonStr, ":"); if (colonCnt == 0) { fmt = LatLonConverter.FORMAT.DDDDDD; } else if (colonCnt == 1) { fmt = LatLonConverter.FORMAT.DDMMMM; } else if (colonCnt == 2) { fmt = LatLonConverter.FORMAT.DDMMSS; } } return fmt; }