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.temenos.interaction.core.rim.TestHeaderHelper.java
@Test public void testEncodeQueryParameters() { MultivaluedMap<String, String> values = new MultivaluedMapImpl<String>(); values.add("customerName", "Jack"); values.add("customerName", "Jill"); values.add("transaction", "101"); String queryParam = HeaderHelper.encodeMultivalueQueryParameters(values); assertThat(queryParam, allOf(containsString("customerName=Jack"), containsString("customerName=Jill"), containsString("transaction=101"))); assertThat(StringUtils.countMatches(queryParam, "&"), equalTo(2)); assertThat(StringUtils.countMatches(queryParam, "?"), equalTo(0)); }
From source file:com.ge.research.semtk.edc.client.ResultsClient.java
/** * Store Table. fullResult is csv. sample is shorter csv. * @param contents//from w ww. jav a 2 s . c o m * @throws Exception */ @SuppressWarnings("unchecked") public void execStoreTableResults(String jobId, Table table) throws ConnectException, EndpointNotFoundException, Exception { // chunk up the table by size and then send all the chunks. // hopefully, this will avoid sending anything too large to the results service int tableRowsDone = 0; int totalRows = table.getNumRows(); int segment = 0; long startTime = 0, endTime = 0; double prepSec = 0.0; double sendSec = 0.0; boolean timerFlag = false; Thread thread = null; if (totalRows == 0) { // just create and send the header row. StringBuilder resultsSoFar = new StringBuilder(); for (int i1 = 0; i1 < table.getNumColumns(); i1 += 1) { resultsSoFar.append((table.getColumnNames())[i1]); if (i1 < table.getNumColumns() - 1) { resultsSoFar.append(","); } } resultsSoFar.append("\n"); conf.setServiceEndpoint("results/storeIncrementalCsvResults"); this.parametersJSON.put("contents", resultsSoFar.toString()); this.parametersJSON.put("jobId", jobId); this.parametersJSON.put("segmentNumber", segment); thread = new Thread(this); thread.run(); } else { // write out all the results, y'know? while (tableRowsDone < totalRows) { if (timerFlag) { startTime = System.nanoTime(); } int tableRowsAtStart = tableRowsDone; // get the next few rows. StringBuilder resultsSoFar = new StringBuilder(); //String lastResults = ""; // get the next allocation of rows. for (int i = 0; i < this.ROWS_TO_PROCESS; i += 1) { try { // Make sure we include a header row. if (tableRowsDone == 0) { // first record... for (int i1 = 0; i1 < table.getNumColumns(); i1 += 1) { resultsSoFar.append((table.getColumnNames())[i1]); if (i1 < table.getNumColumns() - 1) { resultsSoFar.append(","); } } } // get the next row into a comma separated string. String curr = new StringBuilder(table.getRow(tableRowsDone).toString()).toString(); // ArrayList.toString() is fast // but if any element contained commas, then can't use ArrayList.toString() if (StringUtils.countMatches(curr, ",") != (table.getNumColumns() - 1)) { // escape double quotes (using "" for csv files), then enclose each element in double quotes curr = table .getRow(tableRowsDone).stream().map(s -> (new StringBuilder()).append("\"") .append(s.replace("\"", "\"\"")).append("\"").toString()) .collect(Collectors.joining(",")); } else { // ArrayList.toString() added surrounding brackets and spaces after each comma - remove these curr = StringUtils.substring(curr, 1, curr.length() - 1); curr = StringUtils.replace(curr, ", ", ","); } tableRowsDone += 1; // add to the existing results we want to send. //lastResults = resultsSoFar.toString(); // PEC changed resultsSoFar.append("\n"); resultsSoFar.append(curr); // TODO when this was using +=, it would have triggered the batch-too-big behavior, but now that it's a StringBuilder, not sure } catch (IndexOutOfBoundsException eek) { // we have run out of rows. the remaining rows were fewer than the block size. just note this and move on. i = this.ROWS_TO_PROCESS; } // TODO review with Justin. Removing the "revert to slightly smaller batch size" for now because saving the lastBatch after every row // was slowing the performance. We can reintroduce it in a better way later. For now, let any exceptions flow up // catch(Exception eee){ // // the send size would have been too large. // tableRowsDone = tableRowsDone - 1; // // System.out.println("*** caught an exception trying to process a result: " + tableRowsDone); // System.out.println(eee.getMessage()); // // i = this.ROWS_TO_PROCESS; // remove the one that broke things. this way, we reprocess it // //resultsSoFar = new StringBuilder(lastResults); // reset the values. // } } // fail if tableRowsDone has not changed. this implies that even the first result was too large. if ((tableRowsDone == tableRowsAtStart) && (tableRowsDone < totalRows)) { throw new Exception( "unable to write results. there is a row size which is too large. row number was " + tableRowsDone + " of a total " + totalRows + "."); } if (timerFlag) { endTime = System.nanoTime(); prepSec += ((endTime - startTime) / 1000000000.0); System.err.println(String.format("tot prep=%.2f sec", prepSec)); startTime = endTime; } // take care of last run if (thread != null) { thread.join(); ((SimpleResultSet) this.getRunRes()).throwExceptionIfUnsuccessful(); if (this.getRunException() != null) { throw this.getRunException(); } segment += 1; conf.setServiceEndpoint(null); this.parametersJSON.remove("contents"); this.parametersJSON.remove("jobId"); } // send the current one: conf.setServiceEndpoint("results/storeIncrementalCsvResults"); this.parametersJSON.put("contents", resultsSoFar.toString()); this.parametersJSON.put("jobId", jobId); this.parametersJSON.put("segmentNumber", segment); thread = new Thread(this); thread.run(); if (timerFlag) { endTime = System.nanoTime(); sendSec += ((endTime - startTime) / 1000000000.0); System.err.println(String.format("tot send=%.2f sec", sendSec)); startTime = endTime; } } // end of while loop. } // cleanup // take care of last run if (thread != null) { thread.join(); ((SimpleResultSet) this.getRunRes()).throwExceptionIfUnsuccessful(); if (this.getRunException() != null) { throw this.getRunException(); } } if (timerFlag) { System.err.println(String.format("prep=%.2f sec send=%.2f sec", prepSec, sendSec)); } return; }
From source file:com.viettel.ttbankplus.servicegw.hibernate.dao.transaction.TransCPDAO.java
public List<Transaction> getTrans(String where, HashMap param) { List lst = new ArrayList(); try {/* w w w .j a v a 2s . c om*/ String sql = "select cp.trans_id transId, cp.content_provider_id contentproviderid, to_char(cp.request_date, 'dd/MM/yyyy hh24:mi:ss') requestDate, " + "(case nvl(bp.error_code,'null')\n" + "when '00' then TO_CHAR(2)\n" + "when '32' then \n" + "(case nvl(bp.correct_code,'null')\n" + "when '00' then TO_CHAR(2)\n" + "when 'null' then TO_CHAR(1)\n" + "else TO_CHAR(4) end)\n" + "when 'null' then\n" + "(case nvl(bp.correct_code,'null')\n" + "when '00' then TO_CHAR(2)\n" + "when 'null' then TO_CHAR(1)\n" + "else TO_CHAR(4) end\n" + ")\n" + "when 'null' then\n" + "(case nvl(bp.correct_code,'null')\n" + "when '00' then TO_CHAR(2)\n" + "when 'null' then TO_CHAR(1)\n" + "else TO_CHAR(4) end\n" + ")\n" + "else TO_CHAR(4)\n" + "end\n" + ")" + " transStatus, " + "cp.confirm_status confirmStatus, cp.billing_code billingCode, cp.order_id orderId, cp.amount, " + "cp.order_info orderInfo, cp.trans_type transType, bp.bank_code bankCode, bp.cp_code cpCode, bp.msisdn, p.cp_name cpName, bp.customer_name customerName, bp.error_code || bp.correct_code errorCode from trans_cp cp join trans_bankplus bp on cp.trans_cp_id = bp.trans_cp_id " + " join content_provider p on p.content_provider_id = cp.content_provider_id "; // sql += where; // sql += " order by cp.request_date desc"; // log.debug(sql); //Rebuild where param int numparam = StringUtils.countMatches(where, ":"); // log.info("NUM PARAM: " + numparam); ArrayList<Object> arrParam = new ArrayList<Object>(); arrParam.add(0, ""); for (int i = 0; i < numparam; i++) { for (Object object : param.keySet()) { String key = object.toString(); Object val = param.get(key); int index = where.indexOf(":"); int indexCheck = where.indexOf(":" + key); if (index == indexCheck) { if (val instanceof ArrayList) { ArrayList arr = (ArrayList) val; String add = ""; for (int j = 0; j < arr.size(); j++) { arrParam.add(arr.get(j)); add += ",?"; } add = add.substring(1); where = where.substring(0, index) + add + where.substring(index + (":" + key).length()); } else if (val instanceof Date) { Date d = (Date) val; String date = new SimpleDateFormat("dd/MM/yyyy HH-mm-ss").format(d); arrParam.add(date); where = where.substring(0, index) + "to_date(?,'dd/MM/yyyy hh24-mi-ss')" + where.substring(index + (":" + key).length()); } else { arrParam.add(val); where = where.substring(0, index) + "?" + where.substring(index + (":" + key).length()); } // arrParam.add(val); // where = where.substring(0, index) + "?" + where.substring(index + (":" + key).length()); break; } } } numparam = arrParam.size() - 1; sql += where; sql += " order by cp.request_date desc"; // log.debug(sql); log.info("WHERE CLAUSE: " + where); log.info("LIST PARAM VALUE: " + arrParam); Session sess = DAOFactory.getNewSession(); // SQLQuery query = sess.createSQLQuery(sql); Connection conn = sess.connection(); PreparedStatement pstm = null; ResultSet rs = null; try { pstm = conn.prepareStatement(sql); for (int i = 0; i < numparam; i++) { Object objVal = arrParam.get(i + 1); if (objVal instanceof ArrayList) { ArrayList arrlist = (ArrayList) objVal; java.sql.Array sqlArray = null; // oracle.jdbc.OracleConnection oracleConnection = conn.unwrap(OracleConnection.class); if (arrlist.get(0) instanceof String) { // sqlArray = oracleConnection.createArrayOf("VARCHAR", arrlist.toArray()); // sqlArray = conn.createArrayOf("VARCHAR", arrlist.toArray()); } else { // sqlArray = conn.createArrayOf("NUMERIC", arrlist.toArray()); // sqlArray = oracleConnection.createArrayOf("INTEGER", arrlist.toArray()); } pstm.setArray(i + 1, sqlArray); } else if (objVal instanceof String) { pstm.setString(i + 1, objVal.toString()); // java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); // log.info("set string: " + (i + 1) + " - " + objVal.toString()); } else if (objVal instanceof Date) { Date d = (Date) objVal; // String date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d); java.sql.Timestamp sqlDate = new java.sql.Timestamp(d.getTime()); // log.info("set date: " + (i + 1) + " - " + sqlDate); pstm.setTimestamp(i + 1, sqlDate); // pstm.setString(i + 1, date); } else { pstm.setLong(i + 1, Long.parseLong(objVal.toString())); // log.info("set long: " + (i + 1) + " - " + Long.parseLong(objVal.toString())); } } // log.info("PREP: " + pstm.toString()); rs = pstm.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int numCol = rsmd.getColumnCount(); String[] arrCol = new String[numCol]; String coltemp = ""; for (int i = 0; i < numCol; i++) { arrCol[i] = rsmd.getColumnName(i + 1); coltemp += rsmd.getColumnName(i + 1) + "#"; } // log.info("CCCCCC:" + coltemp); while (rs.next()) { // log.info("AAAAAAAAAAAAA:" + rs.getString(1)); Transaction trans = new Transaction(); for (int i = 0; i < numCol; i++) { // String data = rs.getString(arrCol[i]); Object data = rs.getObject(arrCol[i]); if (data != null) { callSetFunction(trans, "set" + arrCol[i], data); } } lst.add(trans); } } catch (Exception ex) { log.error("", ex); } finally { // log.info("================>finally"); if (rs != null) { rs.close(); } if (pstm != null) { pstm.close(); } if (sess != null) { sess.close(); } } // query.setResultTransformer(Transformers.aliasToBean(Transaction.class)); // for (Object object : param.keySet()) { // String key = object.toString(); // Object val = param.get(key); // if (val instanceof ArrayList) { //For select in // query.setParameterList(key, (ArrayList) val); // } else { // query.setParameter(key, param.get(key)); // } // } // log.info(query.toString()); // lst = query.list(); // ScrollableResults resultset = query.scroll(ScrollMode.FORWARD_ONLY); // resultset.beforeFirst(); // while (resultset.next()) { // Object[] objres = resultset.get(); // log.info(objres); // } // resultset.close(); } catch (Exception ex) { log.error("getTrans: ", ex); } finally { // DAOFactory.commitCurrentSessions(); } return lst; }
From source file:ch.ksfx.web.services.seriesbrowser.SeriesBrowser.java
public String getMarkupForNode(ComponentResources componentResources, List<String> nodes, List<String> filteredSeriesNames) { List<String> openedNodes = new ArrayList<String>(); StringBuilder markup = new StringBuilder(); for (String key : rootNodes.keySet()) { Integer depth = 0;//ww w. j a va 2 s . co m NavigationTreeNode rootNtn = rootNodes.get(key); if (nodes != null && nodes.contains(rootNtn.getLocator())) { markup.append(snip.replaceAll("#MARGIN#", (new Integer(depth * margin)).toString()).replaceAll( "#NAME#", "<a href='" + componentResources.createEventLink("closeNode", rootNtn.getName()).toURI() + "'><span class=\"glyphicon glyphicon-folder-open\"></span> " + rootNtn.getName() + "</a> " + getCategoryTitleMarkupForLocator(rootNtn.getLocator()))); for (TimeSeries ts : rootNtn.getSeries()) { if (filteredSeriesNames == null || filteredSeriesNames.isEmpty() || filteredSeriesNames.contains(ts.getName())) { markup.append(snip .replaceAll("#MARGIN#", (new Integer( margin * (StringUtils.countMatches(rootNtn.getLocator(), "-") + 1))) .toString()) .replaceAll("#NAME#", "<a href='" + pageRenderLinkSource.createPageRenderLinkWithContext( "viewTimeSeries", ts.getId()).toURI() + "'><span class=\"glyphicon glyphicon-th-list\"></span> " + ts.getName() + "</a>")); } } } else { markup.append(snip.replaceAll("#MARGIN#", (new Integer(depth * margin)).toString()).replaceAll( "#NAME#", "<a href='" + componentResources.createEventLink("openNode", rootNtn.getName()).toURI() + "'><span class=\"glyphicon glyphicon-folder-close\"></span> " + rootNtn.getName() + "</a> " + getCategoryTitleMarkupForLocator(rootNtn.getLocator()))); } if (nodes != null) { for (String node : nodes) { NavigationTreeNode ntn = rootNtn; String[] parts = null; if (node != null && !node.isEmpty()) { parts = node.split("-"); } if (parts != null && ntn.getName().equals(parts[0])) { for (Integer i = 1; i < parts.length; i++) { ntn = ntn.getChildrenForName(parts[i]); } if (ntn != null && !openedNodes.contains(ntn.getLocator())) { openNode(ntn, markup, componentResources, nodes, filteredSeriesNames, openedNodes); } } } } } return markup.toString(); }
From source file:com.github.rnewson.couchdb.lucene.LuceneServlet.java
private void doGetInternal(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException, JSONException { switch (StringUtils.countMatches(req.getRequestURI(), "/")) { case 1://from w w w .j a v a 2s .co m handleWelcomeReq(req, resp); return; case 5: final DatabaseIndexer indexer = getIndexer(req); if (indexer == null) { ServletUtils.sendJsonError(req, resp, 500, "error_creating_index"); return; } if (req.getParameter("q") == null) { indexer.info(req, resp); } else { indexer.search(req, resp); } return; } ServletUtils.sendJsonError(req, resp, 400, "bad_request"); }
From source file:com.amalto.core.server.routing.DefaultRoutingEngine.java
/** * Check that a rule actually matches a document * //ww w .j a va 2 s. c om * @return true if it matches * @throws XtentisException */ private static boolean ruleExpressionMatches(ItemPOJO itemPOJO, RoutingRuleExpressionPOJO exp) throws XtentisException { Integer contentInt, expInt; String expXpath = exp.getXpath(); if (expXpath.startsWith(itemPOJO.getConceptName())) { expXpath = StringUtils.substringAfter(expXpath, itemPOJO.getConceptName() + '/'); } try { String[] contents = Util.getTextNodes(itemPOJO.getProjection(), expXpath); if (contents.length == 0 && exp.getOperator() == RoutingRuleExpressionPOJO.IS_NULL) { return true; } boolean match = false; for (String content : contents) { if (match) { break; } switch (exp.getOperator()) { case RoutingRuleExpressionPOJO.CONTAINS: match = StringUtils.contains(content, exp.getValue()); break; case RoutingRuleExpressionPOJO.EQUALS: match = StringUtils.equals(content, exp.getValue()); break; case RoutingRuleExpressionPOJO.GREATER_THAN: expInt = safeParse(exp.getValue()); contentInt = safeParse(content); if (expInt == null || contentInt == null) { continue; } if (contentInt > expInt) { match = true; } break; case RoutingRuleExpressionPOJO.GREATER_THAN_OR_EQUAL: expInt = safeParse(exp.getValue()); contentInt = safeParse(content); if (expInt == null || contentInt == null) { continue; } if (contentInt >= expInt) { match = true; } break; case RoutingRuleExpressionPOJO.IS_NOT_NULL: match = content != null; break; case RoutingRuleExpressionPOJO.LOWER_THAN: expInt = safeParse(exp.getValue()); contentInt = safeParse(content); if (expInt == null || contentInt == null) { continue; } if (contentInt < expInt) { match = true; } break; case RoutingRuleExpressionPOJO.LOWER_THAN_OR_EQUAL: expInt = safeParse(exp.getValue()); contentInt = safeParse(content); if (expInt == null || contentInt == null) { continue; } if (contentInt <= expInt) { match = true; } break; case RoutingRuleExpressionPOJO.MATCHES: match = StringUtils.countMatches(content, exp.getValue()) > 0; break; case RoutingRuleExpressionPOJO.NOT_EQUALS: match = !StringUtils.equals(content, exp.getValue()); break; case RoutingRuleExpressionPOJO.STARTSWITH: if (content != null) { match = content.startsWith(exp.getValue()); } break; } } return match; } catch (TransformerException e) { String err = "Subscription rule expression match: unable extract xpath '" + exp.getXpath() + "' from Item '" + itemPOJO.getItemPOJOPK().getUniqueID() + "': " + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }
From source file:com.github.adejanovski.cassandra.jdbc.CassandraStatement.java
private void doExecute(String cql) throws SQLException { List<ResultSetFuture> futures = new ArrayList<ResultSetFuture>(); try {/*from w w w .ja v a 2 s.c o m*/ String[] cqlQueries = cql.split(semiColonRegex); if (cqlQueries.length > 1 && !(cql.trim().toLowerCase().startsWith("begin") && cql.toLowerCase().contains("batch") && cql.toLowerCase().contains("apply"))) { // several statements in the query to execute asynchronously ArrayList<com.datastax.driver.core.ResultSet> results = Lists.newArrayList(); if (cqlQueries.length > MAX_ASYNC_QUERIES * 1.1) { // Protect the cluster from receiving too many queries at once and force the dev to split the load throw new SQLNonTransientException("Too many queries at once (" + cqlQueries.length + "). You must split your queries into more batches !"); } StringBuilder prevCqlQuery = new StringBuilder(); for (String cqlQuery : cqlQueries) { if ((cqlQuery.contains("'") && ((StringUtils.countMatches(cqlQuery, "'") % 2 == 1 && prevCqlQuery.length() == 0) || (StringUtils.countMatches(cqlQuery, "'") % 2 == 0 && prevCqlQuery.length() > 0))) || (prevCqlQuery.toString().length() > 0 && !cqlQuery.contains("'"))) { prevCqlQuery.append(cqlQuery + ";"); } else { prevCqlQuery.append(cqlQuery); if (logger.isTraceEnabled() || this.connection.debugMode) logger.debug("CQL:: " + prevCqlQuery.toString()); SimpleStatement stmt = new SimpleStatement(prevCqlQuery.toString()); stmt.setConsistencyLevel(this.connection.defaultConsistencyLevel); stmt.setFetchSize(this.fetchSize); ResultSetFuture resultSetFuture = this.connection.getSession().executeAsync(stmt); futures.add(resultSetFuture); prevCqlQuery = new StringBuilder(); } } //ListenableFuture<List<com.datastax.driver.core.ResultSet>> res = Futures.allAsList(futures); for (ResultSetFuture future : futures) { com.datastax.driver.core.ResultSet rows = future.getUninterruptibly(); results.add(rows); } currentResultSet = new CassandraResultSet(this, results); } else { // Only one statement to execute so we go synchronous if (logger.isTraceEnabled() || this.connection.debugMode) logger.debug("CQL:: " + cql); SimpleStatement stmt = new SimpleStatement(cql); stmt.setConsistencyLevel(this.connection.defaultConsistencyLevel); stmt.setFetchSize(this.fetchSize); currentResultSet = new CassandraResultSet(this, this.connection.getSession().execute(stmt)); } } catch (Exception e) { for (ResultSetFuture future : futures) { try { future.cancel(true); } catch (Exception e1) { } } throw new SQLTransientException(e); } }
From source file:com.temenos.interaction.core.rim.TestHeaderHelper.java
@Test public void testEncodeQueryParametersDropsDuplicateKeyValues() { MultivaluedMap<String, String> values = new MultivaluedMapImpl<String>(); values.add("customerName", "Jack"); values.add("customerName", "Jack"); values.add("transaction", "101"); values.add("transaction", "102"); String queryParam = HeaderHelper.encodeMultivalueQueryParameters(values); assertThat(queryParam, allOf(containsString("customerName=Jack"), containsString("transaction=101"), containsString("transaction=102"))); assertThat(StringUtils.countMatches(queryParam, "customerName=Jack"), equalTo(1)); assertThat(StringUtils.countMatches(queryParam, "&"), equalTo(2)); }
From source file:com.sap.prd.mobile.ios.ota.lib.OtaPlistGeneratorTest.java
@Test public void testGenerateURL() throws IOException { URL url = OtaPlistGenerator.generatePlistRequestUrl(new URL(long_service), buildMap(KEY_REFERER, long_referer, KEY_TITLE, long_title, KEY_BUNDLE_IDENTIFIER, long_identifier, KEY_BUNDLE_VERSION, long_version, KEY_IPA_CLASSIFIER, ipaClassifier, KEY_OTA_CLASSIFIER, otaClassifier));/*from w w w . j a v a2 s .com*/ assertEquals(10, StringUtils.countMatches(url.toExternalForm(), "/")); System.out.println("Length: " + url.toExternalForm().length() + " - " + url.toExternalForm()); assertTrue(url.toExternalForm().startsWith(long_service)); assertContains("/" + LibUtils.encode("Referer=" + long_referer) + "/", url.toExternalForm()); assertContains("/" + LibUtils.encode("title=" + long_title) + "/", url.toExternalForm()); assertContains("/" + LibUtils.encode("bundleIdentifier=" + long_identifier) + "/", url.toExternalForm()); assertContains("/" + LibUtils.encode("bundleVersion=" + long_version), url.toExternalForm()); assertContains("/" + LibUtils.encode("ipaClassifier=" + ipaClassifier), url.toExternalForm()); assertContains("/" + LibUtils.encode("otaClassifier=" + otaClassifier), url.toExternalForm()); url = OtaPlistGenerator.generatePlistRequestUrl(new URL(long_service), buildMap(KEY_REFERER, long_referer, KEY_TITLE, long_title, KEY_BUNDLE_IDENTIFIER, long_identifier, KEY_BUNDLE_VERSION, long_version)); assertEquals(8, StringUtils.countMatches(url.toExternalForm(), "/")); url = OtaPlistGenerator.generatePlistRequestUrl(new URL(long_service), buildMap(KEY_REFERER, long_referer, KEY_TITLE, long_title, KEY_BUNDLE_IDENTIFIER, long_identifier, KEY_BUNDLE_VERSION, long_version, KEY_OTA_CLASSIFIER, otaClassifier)); assertEquals(9, StringUtils.countMatches(url.toExternalForm(), "/")); }
From source file:com.haulmont.cuba.gui.export.ExcelExporter.java
public void exportTable(Table<Entity> table, List<Table.Column> columns, Boolean exportExpanded, ExportDisplay display, List<String> filterDescription, String fileName, ExportMode exportMode) { if (display == null) { throw new IllegalArgumentException("ExportDisplay is null"); }/*from w w w . j a v a2 s. co m*/ createWorkbookWithSheet(); createFonts(); createFormats(); int r = 0; if (filterDescription != null) { for (r = 0; r < filterDescription.size(); r++) { String line = filterDescription.get(r); HSSFRow row = sheet.createRow(r); if (r == 0) { HSSFRichTextString richTextFilterName = new HSSFRichTextString(line); richTextFilterName.applyFont(boldFont); row.createCell(0).setCellValue(richTextFilterName); } else { row.createCell(0).setCellValue(line); } } r++; } HSSFRow row = sheet.createRow(r); createAutoColumnSizers(columns.size()); float maxHeight = sheet.getDefaultRowHeightInPoints(); CellStyle headerCellStyle = wb.createCellStyle(); headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); for (Table.Column column : columns) { String caption = column.getCaption(); int countOfReturnSymbols = StringUtils.countMatches(caption, "\n"); if (countOfReturnSymbols > 0) { maxHeight = Math.max(maxHeight, (countOfReturnSymbols + 1) * sheet.getDefaultRowHeightInPoints()); headerCellStyle.setWrapText(true); } } row.setHeightInPoints(maxHeight); for (int c = 0; c < columns.size(); c++) { Table.Column column = columns.get(c); String caption = column.getCaption(); HSSFCell cell = row.createCell(c); HSSFRichTextString richTextString = new HSSFRichTextString(caption); richTextString.applyFont(boldFont); cell.setCellValue(richTextString); ExcelAutoColumnSizer sizer = new ExcelAutoColumnSizer(); sizer.notifyCellValue(caption, boldFont); sizers[c] = sizer; cell.setCellStyle(headerCellStyle); } CollectionDatasource datasource = table.getDatasource(); if (exportMode == ExportMode.SELECTED_ROWS && table.getSelected().size() > 0) { Set<Entity> selected = table.getSelected(); List<Entity> ordered = ((Collection<Entity>) datasource.getItems()).stream().filter(selected::contains) .collect(Collectors.toList()); for (Entity item : ordered) { createRow(table, columns, 0, ++r, item.getId()); } } else { if (table instanceof TreeTable) { TreeTable treeTable = (TreeTable) table; HierarchicalDatasource ds = treeTable.getDatasource(); if (table.isAggregatable()) { r = createAggregatableRow(table, columns, ++r, 1, datasource); } for (Object itemId : ds.getRootItemIds()) { r = createHierarhicalRow(treeTable, columns, exportExpanded, r, itemId); } } else if (table instanceof GroupTable && datasource instanceof GroupDatasource && ((GroupDatasource) datasource).hasGroups()) { GroupDatasource ds = (GroupDatasource) datasource; if (table.isAggregatable()) { r = createAggregatableRow(table, columns, ++r, 1, datasource); } for (Object item : ds.rootGroups()) { r = createGroupRow((GroupTable) table, columns, ++r, (GroupInfo) item, 0); } } else { if (table.isAggregatable()) { r = createAggregatableRow(table, columns, ++r, 1, datasource); } for (Object itemId : datasource.getItemIds()) { createRow(table, columns, 0, ++r, itemId); } } } for (int c = 0; c < columns.size(); c++) { sheet.setColumnWidth(c, sizers[c].getWidth() * COL_WIDTH_MAGIC); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { wb.write(out); } catch (IOException e) { throw new RuntimeException("Unable to write document", e); } if (fileName == null) { fileName = messages.getTools().getEntityCaption(datasource.getMetaClass()); } display.show(new ByteArrayDataProvider(out.toByteArray()), fileName + ".xls", ExportFormat.XLS); }