List of usage examples for java.util List set
E set(int index, E element);
From source file:com.free.exception.NestableDelegate.java
/** * Trims the stack frames. The first set is left untouched. The rest of the * frames are truncated from the bottom by comparing with one just on top. * //from w w w . j av a 2 s .c o m * @param stacks * The list containing String[] elements * @since 2.0 */ protected void trimStackFrames(List<String[]> stacks) { for (int size = stacks.size(), i = size - 1; i > 0; i--) { String[] curr = (String[]) stacks.get(i); String[] next = (String[]) stacks.get(i - 1); List<String> currList = new ArrayList<String>(Arrays.asList(curr)); List<String> nextList = new ArrayList<String>(Arrays.asList(next)); ExceptionHelper.removeCommonFrames(currList, nextList); int trimmed = curr.length - currList.size(); if (trimmed > 0) { currList.add("\t... " + trimmed + " more"); stacks.set(i, currList.toArray(new String[currList.size()])); } } }
From source file:com.insprise.common.lang.StringUtilities.java
/** * Returns a properly formatted string representation of the given table (a list of lists of strings). * <p><code><pre>{@code List<List<Object>> lists = new ArrayList<List<Object>>(); * List<Object> list = new ArrayList<Object>(); * list.add("ID");/*from ww w . j a va 2 s . c o m*/ * list.add("Name"); * list.add("Remarks"); * lists.add(list); * * list = new ArrayList<Object>(); * list.add("A"); * list.add("Jack"); * list.add("Employee group"); * list.add("8"); * lists.add(list); * * System.out.println(StringUtilities.displayTable(lists, true, 10)); * * [Results] * +----+------+------------+-------+ * | ID | Name | Remarks | Score | * +----+------+------------+-------+ * | A | Jack | Employee | 8 | * | | | group | | * +----+------+------------+-------+}</pre></code> * @param table * @param firstRowHeadRead is the first row the head read? * if set to <code>true</code>, a line separator will be inserted after the first line. * @param maxColumnLength the max. length of a column. If the data is longer, it will be wrapped. * @return a properly formatted string representation of the given table (a list of lists of strings). */ public static String displayTable(List<List<Object>> table, boolean firstRowHeadRead, int maxColumnLength) { List<Integer> lengths = new ArrayList<Integer>(); // first, find column length. for (int r = 0; r < table.size(); r++) { // for each row for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col String s = null; if (table.get(r).get(c) != null) { s = table.get(r).get(c).toString(); } Integer oldLength = null; if (lengths.size() > c) { oldLength = lengths.get(c); } else { lengths.add(null); } if (s != null) { if (oldLength == null) { lengths.set(c, Math.min(s.length(), maxColumnLength)); } else { lengths.set(c, Math.min(maxColumnLength, Math.max(s.length(), oldLength))); } } else if (oldLength == null || oldLength == 0) { lengths.set(c, 0); } } } StringBuilder sb = new StringBuilder("\n"); // always starts with a new line to avoid misplacement. Formatter formatter = new Formatter(sb); // ------ starts print separator line. for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ------ finishes print separator line. HashMap<Integer, String[]> wraps = new HashMap<Integer, String[]>(); // used to contain wraps. for (int r = 0; r < table.size(); r++) { // for each row int rowHeight = 1; wraps.clear(); for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col int colLength = lengths.get(c); if (c == 0) { sb.append("\n"); // first col. } sb.append(c == 0 && (!firstRowHeadRead || (firstRowHeadRead && r != 0)) ? "> " : "| "); String s = null; if (table.get(r).get(c) != null) { s = table.get(r).get(c).toString(); } if (s == null) { formatter.format("%-" + colLength + "s", ""); } else { if (s.length() > colLength) { String[] wrap = wrap(s, colLength, true); rowHeight = Math.max(rowHeight, wrap.length); wraps.put(c, wrap); formatter.format("%-" + colLength + "s", wrap[0]); } else { formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", s); } } sb.append(" "); // margin. if (c == table.get(r).size() - 1) { // last row sb.append("|"); } } for (int k = 1; k < rowHeight; k++) { // rowHeight > 1 for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col int colLength = lengths.get(c); if (c == 0) { sb.append("\n"); // first col. } sb.append("| "); String s = null; String[] wrap = wraps.get(c); if (wrap != null && wrap.length > k) { s = wrap[k]; } if (s == null) { formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", ""); } else { formatter.format("%-" + colLength + "s", s); } sb.append(" "); // margin. if (c == table.get(r).size() - 1) { // last row sb.append("|"); } } } // end for // rowHeight > 1. if (firstRowHeadRead && r == 0) { // ------ starts print separator line. sb.append("\n"); for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ------ finishes print separator line. } } // end for each row // ------ starts print separator line. sb.append("\n"); for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ends // ------ finishes print separator line. return sb.toString(); }
From source file:fingerprint.MyStructureFingerprint.java
public List<Integer> computeHistogramAminoAcidsTypes() { List<List<String>> equivalentResidues = SequenceTools.generateEquivalentResidues(); List<Integer> histogramAminoAcidsTypes = new ArrayList<>(); for (int i = 0; i < equivalentResidues.size(); i++) { histogramAminoAcidsTypes.add(0); }/*from w w w . j a va 2 s.co m*/ for (MyChainIfc chain : myStructure.getAllChainsRelevantForShapeBuilding()) { for (MyMonomerIfc monomer : chain.getMyMonomers()) { String threeLetterCode = String.valueOf(monomer.getThreeLetterCode()); List<Integer> bins = returnBins(equivalentResidues, threeLetterCode); for (Integer binValue : bins) { int currentVaue = histogramAminoAcidsTypes.get(binValue); histogramAminoAcidsTypes.set(binValue, currentVaue + 1); } } } return histogramAminoAcidsTypes; }
From source file:es.bsc.autonomic.powermodeller.DataSet.java
public DataSet addColumns(String newColName, List<String> colNames) { if (!header.containsAll(colNames)) { logger.error("Not all the columns to be added belonged to this DataSet."); throw new DataSetException("Not all the columns to be added belonged to this DataSet."); }/* w ww. j a v a2 s . c o m*/ List<String> newColumns = new ArrayList<String>(header); newColumns.removeAll(colNames); List<Double> sumatoryColumn = new ArrayList<Double>(); if (colNames.size() > 0) { sumatoryColumn = getCol(colNames.get(0)); if (colNames.size() > 1) { for (int i = 1; i < colNames.size(); i++) { List<Double> addingColumn = getCol(colNames.get(i)); for (int j = 0; j < sumatoryColumn.size(); j++) { sumatoryColumn.set(j, sumatoryColumn.get(j) + addingColumn.get(j)); } } } } List<List<Double>> newDataSetColumns = new ArrayList<List<Double>>(); for (String column : newColumns) { newDataSetColumns.add(getCol(column)); } newDataSetColumns.add(sumatoryColumn); newColumns.add(newColName); DataSet ret = new DataSet(newDataSetColumns, newColumns); if (colNames.contains(this.getIndependent())) { ret.setIndependent(newColName); logger.debug( "Changing independent variable column from " + this.getIndependent() + " to " + newColName); } else { ret.setIndependent(this.getIndependent()); } return ret; }
From source file:bazaar4idea.command.BzrPushCommand.java
public BzrStandardResult execute() { List<String> arguments = new LinkedList<String>(); if (StringUtils.isNotBlank(revision)) { arguments.add("-r"); arguments.add(revision);/* www .ja va2s . c o m*/ } arguments.add(destination); BzrStandardResult result = ShellCommandService.getInstance(project).execute2(repo, "push", arguments); if (BzrErrorUtil.isAbort(result) && BzrErrorUtil.isAuthorizationRequiredAbort(result)) { try { BzrUrl hgUrl = new BzrUrl(destination); if (hgUrl.supportsAuthentication()) { BzrUsernamePasswordDialog dialog = new BzrUsernamePasswordDialog(project); dialog.setUsername(hgUrl.getUsername()); dialog.show(); if (dialog.isOK()) { hgUrl.setUsername(dialog.getUsername()); hgUrl.setPassword(String.valueOf(dialog.getPassword())); arguments.set(arguments.size() - 1, hgUrl.asString()); result = ShellCommandService.getInstance(project).execute2(repo, "push", arguments); } } } catch (URISyntaxException e) { VcsImplUtil.showErrorMessage(project, "Invalid destination: " + destination, "Error"); } } project.getMessageBus().syncPublisher(BzrVcs.OUTGOING_TOPIC).update(project); return result; }
From source file:com.jaeksoft.searchlib.parser.ParserFieldTarget.java
@Override final public void addFieldValueItems(List<FieldValueItem> fieldValueItems, IndexDocument targetDocument) throws IOException { if (fieldValueItems == null) return;/*from ww w. jav a 2s .co m*/ List<String> values = new ArrayList<String>(0); if (captureRegexpPattern == null) { for (FieldValueItem fieldValueItem : fieldValueItems) values.add(fieldValueItem.getValue()); } else { synchronized (captureRegexpPattern) { for (FieldValueItem fieldValueItem : fieldValueItems) for (String value : RegExpUtils.getGroups(captureRegexpPattern, fieldValueItem.getValue())) values.add(value); } } if (removeTag || convertHtmlEntities) { int pos = 0; for (String value : values) { if (removeTag) value = StringUtils.removeTag(value); if (convertHtmlEntities) value = StringEscapeUtils.unescapeHtml(value); values.set(pos++, value); } } addValues(values, targetDocument); }
From source file:Repackage.java
public Repackager(String repackageSpecs) { _fromPackages = new ArrayList(); _toPackages = new ArrayList(); List repackages = splitPath(repackageSpecs, ';'); // Sort the repackage spec so that longer from's are first to match // longest package first for (;;) {/*from w ww . ja v a 2 s .c o m*/ boolean swapped = false; for (int i = 1; i < repackages.size(); i++) { String spec1 = (String) repackages.get(i - 1); String spec2 = (String) repackages.get(i); if (spec1.indexOf(':') < spec2.indexOf(':')) { repackages.set(i - 1, spec2); repackages.set(i, spec1); swapped = true; } } if (!swapped) break; } for (int i = 0; i < repackages.size(); i++) { String spec = (String) repackages.get(i); int j = spec.indexOf(':'); if (j < 0 || spec.indexOf(':', j + 1) >= 0) throw new RuntimeException("Illegal repackage specification: " + spec); String from = spec.substring(0, j); String to = spec.substring(j + 1); _fromPackages.add(Repackager.splitPath(from, '.')); _toPackages.add(Repackager.splitPath(to, '.')); } _fromMatchers = new Matcher[_fromPackages.size() * 2]; _toPackageNames = new String[_fromPackages.size() * 2]; addPatterns('.', 0); addPatterns('/', _fromPackages.size()); }
From source file:com.google.dart.java2dart.SyntaxTranslator.java
/** * Replaces "node" with "replacement" in parent of "node". */// ww w. j a v a2s.com public static void replaceNode(ASTNode parent, ASTNode node, ASTNode replacement) { Class<? extends ASTNode> parentClass = parent.getClass(); // try get/set methods try { for (Method getMethod : parentClass.getMethods()) { String getName = getMethod.getName(); if (getName.startsWith("get") && getMethod.getParameterTypes().length == 0 && getMethod.invoke(parent) == node) { String setName = "set" + getName.substring(3); Method setMethod = parentClass.getMethod(setName, getMethod.getReturnType()); setMethod.invoke(parent, replacement); return; } } } catch (Throwable e) { ExecutionUtils.propagate(e); } // special cases if (parent instanceof ListLiteral) { List<Expression> elements = ((ListLiteral) parent).getElements(); int index = elements.indexOf(node); if (index != -1) { elements.set(index, (Expression) replacement); return; } } if (parent instanceof ArgumentList) { List<Expression> arguments = ((ArgumentList) parent).getArguments(); int index = arguments.indexOf(node); if (index != -1) { arguments.set(index, (Expression) replacement); return; } } if (parent instanceof TypeArgumentList) { List<TypeName> arguments = ((TypeArgumentList) parent).getArguments(); int index = arguments.indexOf(node); if (index != -1) { arguments.set(index, (TypeName) replacement); return; } } // not found throw new UnsupportedOperationException("" + parentClass); }
From source file:com.google.gdt.eclipse.designer.model.widgets.cell.AbstractCellTableInfo.java
/** * We set {@link String} objects as rows. But if there is custom <code>Column</code> which expects * some real "row", this can cause {@link ClassCastException}. So, we replace custom * <code>Column</code> with fake. *///from ww w. ja v a2 s. c o m @SuppressWarnings("unchecked") private void replaceCustomColumns() throws ClassNotFoundException, Exception { // prepare object -> model map Map<Object, ColumnInfo> columnModels = Maps.newHashMap(); for (ColumnInfo columnModel : getColumns()) { columnModels.put(columnModel.getObject(), columnModel); } // replace columns ClassLoader classLoader = JavaInfoUtils.getClassLoader(this); List<Object> columns = (List<Object>) ReflectionUtils.getFieldObject(getObject(), "columns"); for (int i = 0; i < columns.size(); i++) { Object column = columns.get(i); String columnClassName = column.getClass().getName(); // replace Column with "fake" if (!Enhancer.isEnhanced(column.getClass()) && !columnClassName.startsWith("com.google.gwt.user.cellview.client.")) { ColumnInfo columnModel = columnModels.get(column); // create new Column instance { String text = CodeUtils.getShortClass(columnClassName); column = GwtInvocationEvaluatorInterceptor.createTextColumn(classLoader, text); columns.set(i, column); } // set new Column object into model if (columnModel != null) { columnModel.setObject(column); } } } // set rows { List<String> rows = ImmutableList.of("1", "2", "3", "4", "5"); ReflectionUtils.invokeMethod(getObject(), "setRowData(java.util.List)", rows); } }
From source file:hoot.services.controllers.wps.MarkItemsReviewedProcessletTest.java
@Test @Category(IntegrationTest.class) public void testMarkItemReviewedAgainstInvalidReviewAgainstItem() throws Exception { //If an item is marked as reviewed against something it wasn't supposed to be reviewed against //in the services database, we don't fail. A warning is logged only. ReviewTestUtils.createPreparedData(resource()); //add an additional reviewed item that is invalid b/c its review against item is incorrect ReviewedItems reviewedItems = ReviewTestUtils.createReviewedItems(); ReviewedItem[] reviewedItemsArr = reviewedItems.getReviewedItems(); List<ReviewedItem> reviewedItemsList = new ArrayList<ReviewedItem>(Arrays.asList(reviewedItemsArr)); ReviewedItem invalidReviewedItem = reviewedItemsList.get(0); //set item to be reviewed against itself invalidReviewedItem.setReviewedAgainstId(ReviewTestUtils.nodeIds.get((long) -64)); invalidReviewedItem.setReviewedAgainstType(ElementType.Node.toString().toLowerCase()); reviewedItemsList.set(0, invalidReviewedItem); reviewedItemsArr = reviewedItemsList.toArray(new ReviewedItem[] {}); reviewedItems.setReviewedItems(reviewedItemsArr); MarkItemsReviewedRequest markItemsReviewedRequest = new MarkItemsReviewedRequest(); markItemsReviewedRequest.setReviewedItems(ReviewTestUtils.createReviewedItems()); markItemsReviewedRequest.setReviewedItemsChangeset( XmlDocumentBuilder.toString(ReviewTestUtils.createReviewedItemsChangeset())); //the request should fail and nothing should be written try {//from w ww. j a va2s.com execMark(String.valueOf(mapId), String.valueOf(false), markItemsReviewedRequest); } catch (UniformInterfaceException e) { System.out.println(e.getResponse().getEntity(String.class)); Assert.assertEquals(Status.BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); Assert.assertTrue(e.getResponse().getEntity(String.class).contains("Error parsing unique ID tag")); ReviewTestUtils.verifyDataNotMarkedAsReviewed(); throw e; } }