List of usage examples for java.util ArrayList indexOf
public int indexOf(Object o)
From source file:SimpleGui.QueryGenerator.java
/** * following piece of code is to check how many distinct queries that are present in the list * It should present only single query in this case. Count should be 3000 *///from www . ja v a2s. c o m public void countQueries(int epoch) throws IOException { int independentQuery = -1; Query_Count[] distinctQueries = new Query_Count[10000]; ArrayList<String> queryList = new ArrayList<>(); ArrayList arrivalTimes = new ArrayList(); ArrayList userLocations = new ArrayList(); try (BufferedReader br = new BufferedReader( new FileReader("//home//santhilata//Dropbox//CacheLearning//QGen//src//main//java//QueryInput//" + epoch + "_queryRepeat_10.csv"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { String[] query = sCurrentLine.split(Pattern.quote("@(")); queryList.add("(" + query[1]); //each line contain <arrivalTime, userLocation, query> ==<int, int, string> arrivalTimes.add(query[0].split(Pattern.quote("@"))[0]); userLocations.add(query[0].split(Pattern.quote("@"))[1]); } } catch (IOException e) { e.printStackTrace(); } for (String query : queryList) { boolean present = false; int z = 0; while (z <= independentQuery) { if (query.equals(distinctQueries[z].getQuery())) { distinctQueries[z].addCount(1); present = true; break; } else { z++; } // System.out.println("z = "+z); } if (!present) { independentQuery++; distinctQueries[independentQuery] = new Query_Count(query, queryList.indexOf(query)); } } String fileOut = "//home//santhilata//Desktop//QueryOutput//CountQueries//test.csv"; File outFile11 = new File(fileOut); FileWriter writer1 = new FileWriter(outFile11); writer1.flush(); writer1.append("QueryNumber,QRepetitions"); writer1.append('\n'); int total = 0; for (int i = 0; i < independentQuery; i++) { if (distinctQueries[i].getCount() > 0) { System.out.println(distinctQueries[i].getIndex() + " " + distinctQueries[i].getQuery() + " " + distinctQueries[i].getCount()); writer1.append(distinctQueries[i].getIndex() + "," + distinctQueries[i].getCount() + "\n"); total += distinctQueries[i].getCount(); } } System.out.println("total queries " + total); writer1.close(); String arrivalTime = "//home//santhilata//Desktop//QueryOutput//CountQueries//arrivalTimes.csv"; File aTFile = new File(arrivalTime); FileWriter Atwriter = new FileWriter(aTFile); Atwriter.flush(); Atwriter.append("ArrivalTimes,noOfTimes" + "\n"); int noOfTimes = 1; Collections.sort(arrivalTimes); for (int i = 0; i < arrivalTimes.size(); i++) { if (i > 0) { if (Integer.parseInt((String) arrivalTimes.get(i)) == Integer .parseInt((String) arrivalTimes.get(i - 1))) { noOfTimes++; } else { Atwriter.append(arrivalTimes.get(i - 1) + "," + noOfTimes + "\n"); noOfTimes = 1; } } } for (int i = 0; i < queryList.size(); i++) { if (!arrivalTimes.contains(i + "")) { Atwriter.append(i + "," + 0 + "\n"); } } Atwriter.close(); }
From source file:fr.cirad.mgdb.exporting.individualoriented.DARwinExportHandler.java
@Override public void exportData(OutputStream outputStream, String sModule, Collection<File> individualExportFiles, boolean fDeleteSampleExportFilesOnExit, ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms, Map<String, InputStream> readyToExportFiles) throws Exception { MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule); GenotypingProject aProject = mongoTemplate.findOne( new Query(Criteria.where(GenotypingProject.FIELDNAME_PLOIDY_LEVEL).exists(true)), GenotypingProject.class); if (aProject == null) LOG.warn("Unable to find a project containing ploidy level information! Assuming ploidy level is 2."); int ploidy = aProject == null ? 2 : aProject.getPloidyLevel(); File warningFile = File.createTempFile("export_warnings_", ""); FileWriter warningFileWriter = new FileWriter(warningFile); int markerCount = markerCursor.count(); ZipOutputStream zos = new ZipOutputStream(outputStream); if (readyToExportFiles != null) for (String readyToExportFile : readyToExportFiles.keySet()) { zos.putNextEntry(new ZipEntry(readyToExportFile)); InputStream inputStream = readyToExportFiles.get(readyToExportFile); byte[] dataBlock = new byte[1024]; int count = inputStream.read(dataBlock, 0, 1024); while (count != -1) { zos.write(dataBlock, 0, count); count = inputStream.read(dataBlock, 0, 1024); }// ww w . j a va2 s . c o m } String exportName = sModule + "_" + markerCount + "variants_" + individualExportFiles.size() + "individuals"; StringBuffer donFileContents = new StringBuffer( "@DARwin 5.0 - DON -" + LINE_SEPARATOR + individualExportFiles.size() + "\t" + 1 + LINE_SEPARATOR + "N" + "\t" + "individual" + LINE_SEPARATOR); int count = 0; String missingGenotype = ""; for (int j = 0; j < ploidy; j++) missingGenotype += "\tN"; zos.putNextEntry(new ZipEntry(exportName + ".var")); zos.write(("@DARwin 5.0 - ALLELIC - " + ploidy + LINE_SEPARATOR + individualExportFiles.size() + "\t" + markerCount * ploidy + LINE_SEPARATOR + "N").getBytes()); DBCursor markerCursorCopy = markerCursor.copy(); // dunno how expensive this is, but seems safer than keeping all IDs in memory at any time short nProgress = 0, nPreviousProgress = 0; int avgObjSize = (Integer) mongoTemplate .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize"); int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize; markerCursorCopy.batchSize(nChunkSize); int nMarkerIndex = 0; while (markerCursorCopy.hasNext()) { DBObject exportVariant = markerCursorCopy.next(); Comparable markerId = (Comparable) exportVariant.get("_id"); if (markerSynonyms != null) { Comparable syn = markerSynonyms.get(markerId); if (syn != null) markerId = syn; } for (int j = 0; j < ploidy; j++) zos.write(("\t" + markerId).getBytes()); } TreeMap<Integer, Comparable> problematicMarkerIndexToNameMap = new TreeMap<Integer, Comparable>(); ArrayList<String> distinctAlleles = new ArrayList<String>(); // the index of each allele will be used as its code int i = 0; for (File f : individualExportFiles) { BufferedReader in = new BufferedReader(new FileReader(f)); try { String individualId, line = in.readLine(); // read sample id if (line != null) individualId = line; else throw new Exception("Unable to read first line of temp export file " + f.getName()); donFileContents.append(++count + "\t" + individualId + LINE_SEPARATOR); zos.write((LINE_SEPARATOR + count).getBytes()); nMarkerIndex = 0; while ((line = in.readLine()) != null) { List<String> genotypes = MgdbDao.split(line, "|"); HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes int highestGenotypeCount = 0; String mostFrequentGenotype = null; for (String genotype : genotypes) { if (genotype.length() == 0) continue; /* skip missing genotypes */ int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype); if (gtCount > highestGenotypeCount) { highestGenotypeCount = gtCount; mostFrequentGenotype = genotype; } genotypeCounts.put(genotype, gtCount); } if (genotypeCounts.size() > 1) { warningFileWriter.write("- Dissimilar genotypes found for variant __" + nMarkerIndex + "__, individual " + individualId + ". Exporting most frequent: " + mostFrequentGenotype + "\n"); problematicMarkerIndexToNameMap.put(nMarkerIndex, ""); } String codedGenotype = ""; if (mostFrequentGenotype != null) for (String allele : mostFrequentGenotype.split(" ")) { if (!distinctAlleles.contains(allele)) distinctAlleles.add(allele); codedGenotype += "\t" + distinctAlleles.indexOf(allele); } else codedGenotype = missingGenotype.replaceAll("N", "-1"); // missing data is coded as -1 zos.write(codedGenotype.getBytes()); nMarkerIndex++; } } catch (Exception e) { LOG.error("Error exporting data", e); progress.setError("Error exporting data: " + e.getClass().getSimpleName() + (e.getMessage() != null ? " - " + e.getMessage() : "")); return; } finally { in.close(); } if (progress.hasAborted()) return; nProgress = (short) (++i * 100 / individualExportFiles.size()); if (nProgress > nPreviousProgress) { // LOG.debug("============= doDARwinExport (" + i + "): " + nProgress + "% ============="); progress.setCurrentStepProgress(nProgress); nPreviousProgress = nProgress; } if (!f.delete()) { f.deleteOnExit(); LOG.info("Unable to delete tmp export file " + f.getAbsolutePath()); } } zos.putNextEntry(new ZipEntry(exportName + ".don")); zos.write(donFileContents.toString().getBytes()); // now read variant names for those that induced warnings nMarkerIndex = 0; markerCursor.batchSize(nChunkSize); while (markerCursor.hasNext()) { DBObject exportVariant = markerCursor.next(); if (problematicMarkerIndexToNameMap.containsKey(nMarkerIndex)) { Comparable markerId = (Comparable) exportVariant.get("_id"); if (markerSynonyms != null) { Comparable syn = markerSynonyms.get(markerId); if (syn != null) markerId = syn; } for (int j = 0; j < ploidy; j++) zos.write(("\t" + markerId).getBytes()); problematicMarkerIndexToNameMap.put(nMarkerIndex, markerId); } } warningFileWriter.close(); if (warningFile.length() > 0) { zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt")); int nWarningCount = 0; BufferedReader in = new BufferedReader(new FileReader(warningFile)); String sLine; while ((sLine = in.readLine()) != null) { for (Integer aMarkerIndex : problematicMarkerIndexToNameMap.keySet()) sLine = sLine.replaceAll("__" + aMarkerIndex + "__", problematicMarkerIndexToNameMap.get(aMarkerIndex).toString()); zos.write((sLine + "\n").getBytes()); in.readLine(); nWarningCount++; } LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount); in.close(); } warningFile.delete(); zos.close(); progress.setCurrentStepProgress((short) 100); }
From source file:webserver.WebResource.java
@Path("index/img/{filename}") @GET/*from www. ja va2 s . com*/ public Response image(@PathParam("filename") String filename) { ArrayList<String> imgs = new ArrayList<String>(); imgs.addAll(Arrays.asList(imgsArray)); int imgnum = imgs.indexOf(filename); if (imgnum == -1) { return error404(request, null); } File file = new File("web/img/" + imgs.get(imgnum)); String type = ""; switch (getFileExtention(imgs.get(imgnum))) { case "png": type = "image/png"; break; case "gif": type = "image/gif"; break; case "jpg": type = "image/jpeg"; break; } if (file.exists()) { return Response.ok(file, type).build(); } else { return error404(request, null); } }
From source file:org.sakaiproject.tool.assessment.qti.helper.ExtractionHelper.java
/** * Respondus questions//from w w w . j a v a2s .c o m */ private boolean isCorrectAnswer2(String answerText, ArrayList correctLabels) { if (answerText == null || correctLabels == null) { return false; } else { String[] data = answerText.split(":::"); if (correctLabels.indexOf(data[0]) == -1) { return false; } } return true; }
From source file:mp.teardrop.SongTimeline.java
/** * Run the given query and add the results to the song timeline. * * @param context A context to use./*w w w. jav a 2 s.c o m*/ * @param query The query to be run. The mode variable must be initialized * to one of SongTimeline.MODE_*. The type and data variables may also need * to be initialized depending on the given mode. * @return The number of songs that were added. */ public int addSongs(Context context, QueryTask query) { Cursor cursor = query.runQuery(context.getContentResolver()); if (cursor == null) { return 0; } int count = cursor.getCount(); if (count == 0) { return 0; } int mode = query.mode; int type = query.type; long data = query.data; ArrayList<Song> timeline = mSongs; synchronized (this) { saveActiveSongs(); switch (mode) { case MODE_ENQUEUE: case MODE_ENQUEUE_POS_FIRST: case MODE_ENQUEUE_ID_FIRST: break; case MODE_PLAY_NEXT: timeline.subList(mCurrentPos + 1, timeline.size()).clear(); break; case MODE_PLAY: case MODE_PLAY_POS_FIRST: case MODE_PLAY_ID_FIRST: timeline.clear(); mCurrentPos = 0; break; default: throw new IllegalArgumentException("Invalid mode: " + mode); } int start = timeline.size(); Song jumpSong = null; for (int j = 0; j != count; ++j) { cursor.moveToPosition(j); Song song = new Song(-1); song.populate(cursor); timeline.add(song); if (jumpSong == null) { if ((mode == MODE_PLAY_POS_FIRST || mode == MODE_ENQUEUE_POS_FIRST) && j == data) { jumpSong = song; } else if (mode == MODE_PLAY_ID_FIRST || mode == MODE_ENQUEUE_ID_FIRST) { long id; switch (type) { /* case MediaUtils.TYPE_ARTIST: id = song.artistId; break; case MediaUtils.TYPE_ALBUM: id = song.albumId; break; case MediaUtils.TYPE_SONG: id = song.id; break; */ default: throw new IllegalArgumentException("Unsupported id type: " + type); } /* if (id == data) jumpSong = song; */ } } } if (mShuffleMode != SHUFFLE_NONE) MediaUtils.shuffle(timeline.subList(start, timeline.size()), mShuffleMode == SHUFFLE_ALBUMS); if (jumpSong != null) { int jumpPos = timeline.indexOf(jumpSong); if (jumpPos != start) { // Get the sublist twice to avoid a ConcurrentModificationException. timeline.addAll(timeline.subList(start, jumpPos)); timeline.subList(start, jumpPos).clear(); } } broadcastChangedSongs(); } changed(); return count; }
From source file:ffx.autoparm.Potential2.java
/** * <p>// w w w.j av a 2s . c om * output_keyfile</p> * * @param mpoles an array of double. * @param outfname a {@link java.lang.String} object. * @throws java.io.IOException if any. */ public void output_keyfile(double[] mpoles, String outfname) throws IOException { File outf = new File(outfname); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outf))); int r = 0; DecimalFormat myFormatter = new DecimalFormat(" ##########0.00000;-##########0.00000"); ArrayList<Integer> types = new ArrayList<Integer>(); // for(int i = 0; i < mpoles.length; i++){ // System.out.println(mpoles[i]); // } int pos; int polelen = 10; //for traceless manipulations int a = 4, b = 5, c = 6; if (!pme.fitmpl) { polelen = polelen - 1; a -= 1; b -= 1; c -= 1; } if (!pme.fitdpl) { polelen = polelen - 3; a -= 3; b -= 3; c -= 3; } if (!pme.fitqdpl) { polelen = polelen - 5; } //maintain traceless quadrupole at each multipole site if (pme.fitqdpl) { double sum = 0; double big = 0; for (int i = 0; i < (mpoles.length) / polelen; i++) { sum = mpoles[(i * polelen) + a] + mpoles[(i * polelen) + b] + mpoles[(i * polelen) + c]; big = Math.max(Math.abs(mpoles[(i * polelen) + a]), Math.max(Math.abs(mpoles[(i * polelen) + b]), Math.abs(mpoles[(i * polelen) + c]))); int k = 0; if (big == Math.abs(mpoles[(i * polelen) + a])) { k = a; } else if (big == Math.abs(mpoles[(i * polelen) + b])) { k = b; } else if (big == Math.abs(mpoles[(i * polelen) + c])) { k = c; } if (k != 0) { mpoles[(i * polelen) + k] = mpoles[(i * polelen) + k] - sum; } } } for (int i = 0; i < nAtoms; i++) { Atom ai = atoms[i]; if (!types.contains(ai.getType())) { types.add(ai.getType()); } } for (int i = 0; i < key.size(); i++) { if (!key.get(i).toUpperCase().contains("MULTIPOLE")) { bw.write(key.get(i) + "\n"); } else if (key.get(i).toUpperCase().contains("MULTIPOLE")) { pos = types.indexOf(Integer.parseInt(key.get(i).trim().split(" +")[1])); if (pme.fitmpl) { bw.write(key.get(i).trim().split(" +")[0] + " " + key.get(i).trim().split(" +")[1] + " " + key.get(i).trim().split(" +")[2] + " " + key.get(i).trim().split(" +")[3] + " " + myFormatter.format(mpoles[pos * polelen + r]) + "\n"); r = r + 1; } else { bw.write(key.get(i) + "\n"); } if (pme.fitdpl) { bw.write(" " + myFormatter.format(mpoles[pos * polelen + r] / BOHR) + " " + myFormatter.format(mpoles[pos * polelen + r + 1] / BOHR) + " " + myFormatter.format(mpoles[pos * polelen + r + 2] / BOHR) + "\n"); r = r + 3; } else { bw.write(key.get(i + 1) + "\n"); } if (pme.fitqdpl) { bw.write(" " + myFormatter.format(mpoles[pos * polelen + r] / (BOHR * BOHR)) + "\n"); bw.write(" " + myFormatter.format(mpoles[pos * polelen + r + 3] / (BOHR * BOHR)) + " " + myFormatter.format(mpoles[pos * polelen + r + 1] / (BOHR * BOHR)) + "\n"); bw.write(" " + myFormatter.format(mpoles[pos * polelen + r + 4] / (BOHR * BOHR)) + " " + myFormatter.format(mpoles[pos * polelen + r + 5] / (BOHR * BOHR)) + " " + myFormatter.format(mpoles[pos * polelen + r + 2] / (BOHR * BOHR)) + "\n"); r = r + 6; } else { bw.write(key.get(i + 2) + "\n"); bw.write(key.get(i + 3) + "\n"); bw.write(key.get(i + 4) + "\n"); } i = i + 4; r = 0; } } bw.close(); System.out.println("Keyfile written to " + outfname); }
From source file:de.main.sessioncreator.DesktopApplication1View.java
public void showReviewPanel() { reviewtaReview.getDocument().addDocumentListener(new reviewTaReviewListener()); sessionWizardMenuItem.setEnabled(true); reviewVieMenuItem.setEnabled(false); sessionReportMenuItem.setEnabled(true); wizardPanel.setVisible(false);/* www . java 2 s. c o m*/ mainPanel.validate(); reportPanel.setVisible(false); mainPanel.validate(); viewReviewsPanel.setVisible(true); mainPanel.validate(); this.getFrame().setTitle("SessionCreator - Review"); swingHelper.setTab1EnableAt(reviewSessionsTabp, 0); reviewbtnNext.setEnabled(true); reviewbtnMove.setEnabled(false); reviewbtntopMove.setEnabled(false); reviewbtnSave.setVisible(false); final File directory = new File(wizardTfPathSubmitted.getText()); reviewCmbxSessiontoReview.removeAllItems(); reviewCmbxSessiontoReview.addItem("Please select a session"); fileHelper.charterList.clear(); if (fileHelper.getFilesWithCharter(directory, false)) { for (String toReview : fileHelper.charterList) { reviewCmbxSessiontoReview.addItem(toReview); } fileHelper.getSessionList(wizardTfPathSubmitted.getText()); reviewtoReviewPanel.removeAll(); ArrayList<String> Tester = new ArrayList<String>(); Tester = fileHelper.getTester(); int[] counter = new int[Tester.size()]; for (String s : fileHelper.sessionList) { for (String n : Tester) { if (s.contains(n.substring(0, 3))) { counter[Tester.indexOf(n)]++; break; } } } for (String n : Tester) { reviewtoReviewPanel.add(new JLabel(n.substring(4) + ": " + counter[Tester.indexOf(n)])); reviewtoReviewPanel.revalidate(); listofLabels.add(new JLabel(n.substring(4) + ": " + counter[Tester.indexOf(n)])); reviewtoReviewPanel.repaint(); } } else { JOptionPane.showMessageDialog(null, "Directory '" + directory + "' does not exsits!\nPlease edit in the config.txt the 'Submitted'-Path and try again.", "Error", JOptionPane.ERROR_MESSAGE); } }
From source file:noThreads.ParseLevel2.java
/** * * @param theLinks//from w ww . ja va 2s . c o m * @throws IOException */ public void getSecondLinks(ArrayList<String> theLinks) throws IOException { float num = 0; String temp, attrOfScr, subString; Document doc; boolean flag; for (String sLink : theLinks) { if ((sLink.endsWith(".asx") == true) || (sLink.endsWith(".swf") == true)) { stationLinks2.add(sLink); print("Written to file: %s", sLink); } else { //iframeCase(sLink); doc = parseUrl(sLink, 0); if (doc != null) { Elements media = doc.select("[src]"); print("Fetching %s --> ", sLink); flag = false; for (Element src : media) { if (src.tagName().equals("embed") == true) { flag = true; temp = src.attr("abs:src"); if (temp.endsWith(".swf") == true) { attrOfScr = src.attr("abs:flashvars"); // System.out.println("\nThis is src of embed tag: " // +temp // +"\nThis is attribute flashvars of embed tag: " // +attrOfScr); int start = attrOfScr.indexOf("http://", attrOfScr.indexOf("http://") + 1); int end = attrOfScr.indexOf("&"); char a_char = attrOfScr.charAt(end - 1); if (start != -1 && end != -1) { if (a_char == ';') { subString = attrOfScr.substring(start, end - 1); } else { subString = attrOfScr.substring(start, end); } //System.out.println("\nthis is the result subString: "+subString); stationLinks2.add(subString); } else { //something's wrong, do not process the link flag = false; } break;//link found } stationLinks2.add(temp); break;//link found, load next url } } //end nested for if (flag == false) {//the code has no embed tag stationLinks2.add(sLink); } } } num = (float) (theLinks.indexOf(sLink)) / (float) (theLinks.size()) * WEIGHT_IN_COMPUTATION + curProgress.getCurProgressPart1(); curProgress.setCurProgress((int) num); } //end outer for writeLinksToFile(links2FileName, stationLinks2); print("Written %s to file, second links.", stationLinks2.size()); }
From source file:com.amalto.workbench.dialogs.AnnotationOrderedListsDialog.java
@Override protected Control createDialogArea(Composite parent) { // Should not really be here but well,.... parent.getShell().setText(this.title); Composite composite = (Composite) super.createDialogArea(parent); GridLayout layout = (GridLayout) composite.getLayout(); layout.numColumns = 3;/*from w w w .jav a2 s. com*/ layout.makeColumnsEqualWidth = false; // layout.verticalSpacing = 10; if (actionType == AnnotationWrite_ActionType || actionType == AnnotationHidden_ActionType) { textControl = new CCombo(composite, SWT.BORDER | SWT.READ_ONLY); // roles=Util.getCachedXObjectsNameSet(this.xObject, TreeObject.ROLE); roles = getAllRolesStr(); ((CCombo) textControl).setItems(roles.toArray(new String[roles.size()])); } else if (actionType == AnnotationLookupField_ActionType || actionType == AnnotationPrimaKeyInfo_ActionType) { textControl = new CCombo(composite, SWT.BORDER | SWT.READ_ONLY); // roles=Util.getCachedXObjectsNameSet(this.xObject, TreeObject.ROLE); roles = getConceptElements(); ((CCombo) textControl).setItems(roles.toArray(new String[roles.size()])); } else { if (actionType == AnnotationOrderedListsDialog.AnnotationSchematron_ActionType) { textControl = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); } else { textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); } } if (actionType == AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType) { textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); } else { if (actionType == AnnotationOrderedListsDialog.AnnotationSchematron_ActionType) { textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 7)); } else { textControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); } } ((GridData) textControl.getLayoutData()).minimumWidth = 400; textControl.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { if ((e.stateMask == 0) && (e.character == SWT.CR)) { xPaths.add(AnnotationOrderedListsDialog.getControlText(textControl)); viewer.refresh(); fireXPathsChanges(); } } }); if (actionType == AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType) { Button xpathButton = new Button(composite, SWT.PUSH | SWT.CENTER); xpathButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); xpathButton.setText("...");//$NON-NLS-1$ xpathButton.setToolTipText(Messages.AnnotationOrderedListsDialog_SelectXpath); xpathButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { XpathSelectDialog dlg = getNewXpathSelectDialog(parentPage, dataModelName); dlg.setLock(lock); dlg.setBlockOnOpen(true); dlg.open(); if (dlg.getReturnCode() == Window.OK) { ((Text) textControl).setText(dlg.getXpath()); dlg.close(); } } }); } Button addLabelButton = new Button(composite, SWT.PUSH); addLabelButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); // addLabelButton.setText("Set"); addLabelButton.setImage(ImageCache.getCreatedImage(EImage.ADD_OBJ.getPath())); addLabelButton.setToolTipText(Messages.AnnotationOrderedListsDialog_Add); addLabelButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { boolean exist = false; for (String string : xPaths) { if (string.equals(getControlText(textControl))) { exist = true; } } if (!exist && getControlText(textControl) != null && getControlText(textControl) != "") { xPaths.add(getControlText(textControl)); } viewer.refresh(); fireXPathsChanges(); }; }); final String COLUMN = columnName; viewer = new TableViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); ((GridData) viewer.getControl().getLayoutData()).heightHint = 100; // Set up the underlying table Table table = viewer.getTable(); // table.setLayoutData(new GridData(GridData.FILL_BOTH)); new TableColumn(table, SWT.CENTER).setText(COLUMN); table.getColumn(0).setWidth(500); for (int i = 1, n = table.getColumnCount(); i < n; i++) { table.getColumn(i).pack(); } table.setHeaderVisible(true); table.setLinesVisible(true); // Create the cell editors --> We actually discard those later: not natural for an user CellEditor[] editors = new CellEditor[1]; if (actionType == AnnotationOrderedListsDialog.AnnotationWrite_ActionType || actionType == AnnotationOrderedListsDialog.AnnotationHidden_ActionType || actionType == AnnotationLookupField_ActionType || actionType == AnnotationPrimaKeyInfo_ActionType) { editors[0] = new ComboBoxCellEditor(table, roles.toArray(new String[] {}), SWT.READ_ONLY); } else { editors[0] = new TextCellEditor(table); } viewer.setCellEditors(editors); // set the content provider viewer.setContentProvider(new IStructuredContentProvider() { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public Object[] getElements(Object inputElement) { @SuppressWarnings("unchecked") ArrayList<String> xPaths = (ArrayList<String>) inputElement; ArrayList<DescriptionLine> lines = new ArrayList<DescriptionLine>(); for (String xPath : xPaths) { DescriptionLine line = new DescriptionLine(xPath); lines.add(line); } // we return an instance line made of a Sring and a boolean return lines.toArray(new DescriptionLine[lines.size()]); } }); // set the label provider viewer.setLabelProvider(new ITableLabelProvider() { public boolean isLabelProperty(Object element, String property) { return false; } public void dispose() { } public void addListener(ILabelProviderListener listener) { } public void removeListener(ILabelProviderListener listener) { } public String getColumnText(Object element, int columnIndex) { // System.out.println("getColumnText() "+columnIndex); DescriptionLine line = (DescriptionLine) element; switch (columnIndex) { case 0: return line.getLabel(); } return "";//$NON-NLS-1$ } public Image getColumnImage(Object element, int columnIndex) { return null; } }); // Set the column properties viewer.setColumnProperties(new String[] { COLUMN }); // set the Cell Modifier viewer.setCellModifier(new ICellModifier() { public boolean canModify(Object element, String property) { // if (INSTANCE_ACCESS.equals(property)) return true; Deactivated return true; // return false; } public void modify(Object element, String property, Object value) { TableItem item = (TableItem) element; DescriptionLine line = (DescriptionLine) item.getData(); String orgValue = line.getLabel(); if (actionType != AnnotationWrite_ActionType && actionType != AnnotationHidden_ActionType && actionType != AnnotationLookupField_ActionType && actionType != AnnotationPrimaKeyInfo_ActionType) { int targetPos = xPaths.indexOf(value.toString()); if (targetPos < 0) { line.setLabel(value.toString()); int index = xPaths.indexOf(orgValue); xPaths.remove(index); xPaths.add(index, value.toString()); viewer.update(line, null); } else if (targetPos >= 0 && !value.toString().equals(orgValue)) { MessageDialog.openInformation(null, Messages.Warning, Messages.AnnotationOrderedListsDialog_ValueAlreadyExists); } } else { String[] attrs = roles.toArray(new String[] {}); int index = Integer.parseInt(value.toString()); if (index == -1) { return; } value = attrs[index]; int pos = xPaths.indexOf(value.toString()); if (pos >= 0 && !(orgValue.equals(value))) { MessageDialog.openInformation(null, Messages.Warning, Messages.AnnotationOrderedListsDialog_); return; } else if (pos < 0) { line.setLabel(value.toString()); xPaths.set(index, value.toString()); viewer.update(line, null); } } fireXPathsChanges(); } public Object getValue(Object element, String property) { DescriptionLine line = (DescriptionLine) element; String value = line.getLabel(); if (actionType == AnnotationWrite_ActionType || actionType == AnnotationHidden_ActionType || actionType == AnnotationLookupField_ActionType || actionType == AnnotationPrimaKeyInfo_ActionType) { String[] attrs = roles.toArray(new String[] {}); return Arrays.asList(attrs).indexOf(value); } else { return value; } } }); // Listen for changes in the selection of the viewer to display additional parameters viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line != null) { if (textControl instanceof CCombo) { ((CCombo) textControl).setText(line.getLabel()); } if (textControl instanceof Text) { ((Text) textControl).setText(line.getLabel()); } } } }); // display for Delete Key events to delete an instance viewer.getTable().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { // System.out.println("Table keyReleased() "); if ((e.stateMask == 0) && (e.character == SWT.DEL) && (viewer.getSelection() != null)) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); @SuppressWarnings("unchecked") ArrayList<String> xPaths = (ArrayList<String>) viewer.getInput(); xPaths.remove(line.getLabel()); viewer.refresh(); } } }); viewer.setInput(xPaths); viewer.refresh(); Composite rightButtonsComposite = new Composite(composite, SWT.NULL); rightButtonsComposite.setLayout(new GridLayout(1, true)); rightButtonsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); Button upButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER); upButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); upButton.setImage(ImageCache.getCreatedImage(EImage.PREV_NAV.getPath())); upButton.setToolTipText(Messages.AnnotationOrderedListsDialog_MoveUpTheItem); upButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line == null) { return; } int i = 0; for (String xPath : xPaths) { if (xPath.equals(line.getLabel())) { if (i > 0) { xPaths.remove(i); xPaths.add(i - 1, xPath); viewer.refresh(); viewer.getTable().setSelection(i - 1); viewer.getTable().showSelection(); fireXPathsChanges(); } return; } i++; } }; }); Button downButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER); downButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); downButton.setImage(ImageCache.getCreatedImage(EImage.NEXT_NAV.getPath())); downButton.setToolTipText(Messages.AnnotationOrderedListsDialog_MoveDownTheItem); downButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line == null) { return; } int i = 0; for (String xPath : xPaths) { if (xPath.equals(line.getLabel())) { if (i < xPaths.size() - 1) { xPaths.remove(i); xPaths.add(i + 1, xPath); viewer.refresh(); viewer.getTable().setSelection(i + 1); viewer.getTable().showSelection(); fireXPathsChanges(); } return; } i++; } }; }); Button delButton = new Button(rightButtonsComposite, SWT.PUSH | SWT.CENTER); delButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); delButton.setImage(ImageCache.getCreatedImage(EImage.DELETE_OBJ.getPath())); delButton.setToolTipText(Messages.AnnotationOrderedListsDialog_DelTheItem); delButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); if (line != null) { @SuppressWarnings("unchecked") ArrayList<String> xPaths = (ArrayList<String>) viewer.getInput(); xPaths.remove(line.getLabel()); viewer.refresh(); fireXPathsChanges(); } }; }); textControl.setFocus(); if (actionType != AnnotationOrderedListsDialog.AnnotationForeignKeyInfo_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationTargetSystems_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationSchematron_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationLookupField_ActionType && actionType != AnnotationOrderedListsDialog.AnnotationPrimaKeyInfo_ActionType) { checkBox = new Button(composite, SWT.CHECK); checkBox.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, 2, 1)); checkBox.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { recursive = checkBox.getSelection(); }; }); checkBox.setSelection(recursive); checkBox.setText(Messages.AnnotationOrderedListsDialog_SetRoleRecursively); // Label label = new Label(composite, SWT.LEFT); // label.setText("set role recursively"); // label.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true, // 1, 1)); } if (actionType == AnnotationForeignKeyInfo_ActionType) { createFKInfoFormatComp(composite); addDoubleClickListener(); } return composite; }
From source file:org.matrix.androidsdk.fragments.MatrixMessageListFragment.java
@Override public void onReceiptEvent(List<String> senderIds) { // avoid useless refresh boolean shouldRefresh = true; try {/*from w w w . j a v a2s . com*/ IMXStore store = mSession.getDataHandler().getStore(); int firstPos = mMessageListView.getFirstVisiblePosition(); int lastPos = mMessageListView.getLastVisiblePosition(); ArrayList<String> senders = new ArrayList<>(); ArrayList<String> eventIds = new ArrayList<>(); for (int index = firstPos; index <= lastPos; index++) { MessageRow row = mAdapter.getItem(index); senders.add(row.getEvent().getSender()); eventIds.add(row.getEvent().eventId); } shouldRefresh = false; // check if the receipt will trigger a refresh for (String sender : senderIds) { if (!TextUtils.equals(sender, mSession.getMyUserId())) { ReceiptData receipt = store.getReceipt(mRoom.getRoomId(), sender); // sanity check if (null != receipt) { // test if the event is displayed int pos = eventIds.indexOf(receipt.eventId); // if displayed if (pos >= 0) { // the sender is not displayed as a reader (makes sense...) shouldRefresh = !TextUtils.equals(senders.get(pos), sender); if (shouldRefresh) { break; } } } } } } catch (Exception e) { Log.e(LOG_TAG, "onReceiptEvent failed with " + e.getLocalizedMessage()); } if (shouldRefresh) { mAdapter.notifyDataSetChanged(); } }