List of usage examples for java.util LinkedList size
int size
To view the source code for java.util LinkedList size.
Click Source Link
From source file:fr.univlorraine.mondossierweb.views.NotesDetailMobileView.java
@SuppressWarnings("deprecation") public void refresh(Etape etapeToDisplay, String codetuToDisplay) { //On vrifie le droit d'accder la vue if (UI.getCurrent() instanceof MdwTouchkitUI && (userController.isEnseignant() || userController.isEtudiant()) && MdwTouchkitUI.getCurrent() != null && MdwTouchkitUI.getCurrent().getEtudiant() != null) { //On repassera dans la cration que si on n'a pas dej cr la vue if (codetu == null || !codetuToDisplay.equals(codetu)) { codetu = null;/*from w w w . ja va 2 s. c om*/ } //On repassera dans la cration que si on n'a pas dej cr la vue if (etape == null || !etapeToDisplay.getAnnee().equals(etape.getAnnee()) || !etapeToDisplay.getCode().equals(etape.getCode()) || !etapeToDisplay.getVersion().equals(etape.getVersion())) { etape = null; } //On repassera dans la cration que si on n'a pas dej cr la vue if (codetu == null || etape == null) { compteurElp = 0; removeAllComponents(); /* Style */ setMargin(false); setSpacing(false); setSizeFull(); //Test si user enseignant if (userController.isEnseignant()) { //On recupere les notes pour un enseignant etudiantController.renseigneDetailNotesEtResultatsEnseignant(etapeToDisplay); } else { //On rcupre les notes pour un tudiant etudiantController.renseigneDetailNotesEtResultats(etapeToDisplay); } //NAVBAR HorizontalLayout navbar = new HorizontalLayout(); navbar.setSizeFull(); navbar.setHeight("40px"); navbar.setStyleName("navigation-bar"); //Bouton retour returnButton = new Button(); returnButton.setIcon(FontAwesome.ARROW_LEFT); //returnButton.setStyleName(ValoTheme.BUTTON_ICON_ONLY); returnButton.setStyleName("v-nav-button"); returnButton.addClickListener(e -> { MdwTouchkitUI.getCurrent().navigateToResumeNotes(); }); navbar.addComponent(returnButton); navbar.setComponentAlignment(returnButton, Alignment.MIDDLE_LEFT); //Titre Label labelNavBar = new Label(MdwTouchkitUI.getCurrent().getEtudiant().getNom()); labelNavBar.setStyleName("v-label-navbar"); navbar.addComponent(labelNavBar); navbar.setComponentAlignment(labelNavBar, Alignment.MIDDLE_CENTER); navbar.setExpandRatio(labelNavBar, 1); //Significations if (MdwTouchkitUI.getCurrent().getEtudiant().isSignificationResultatsUtilisee()) { significationButton = new Button(); significationButton.setIcon(FontAwesome.INFO_CIRCLE); significationButton.setStyleName("v-nav-button"); significationButton.addClickListener(e -> { //afficher les significations SignificationsMobileWindow w = new SignificationsMobileWindow(true); UI.getCurrent().addWindow(w); }); navbar.addComponent(significationButton); navbar.setComponentAlignment(significationButton, Alignment.MIDDLE_RIGHT); } addComponent(navbar); layoutList = new HashMap<String, LinkedList<HorizontalLayout>>(); etape = etapeToDisplay; codetu = codetuToDisplay; /* Layout */ VerticalLayout layout = new VerticalLayout(); layout.setSizeFull(); layout.setMargin(true); layout.setSpacing(true); layout.setStyleName("v-scrollableelement"); /* Titre */ setCaption(applicationContext.getMessage(NAME + ".title", null, getLocale())); List<ElementPedagogique> lelp = MdwTouchkitUI.getCurrent().getEtudiant().getElementsPedagogiques(); if (lelp != null && lelp.size() > 0) { //Panel notesPanel = new Panel(); //notesPanel.setSizeFull(); VerticalLayout notesLayout = new VerticalLayout(); //notesLayout.setSpacing(true); HorizontalLayout libSessionLayout = new HorizontalLayout(); libSessionLayout.setSizeFull(); libSessionLayout.addComponent(new Label()); HorizontalLayout sessionLayout = new HorizontalLayout(); sessionLayout.setSizeFull(); Label session1 = new Label("Session1"); session1.setStyleName("label-bold-with-bottom"); sessionLayout.addComponent(session1); Label session2 = new Label("Session2"); session2.setStyleName("label-bold-with-bottom"); sessionLayout.addComponent(session2); libSessionLayout.addComponent(sessionLayout); notesLayout.addComponent(libSessionLayout); boolean blueLevel = false; compteurElp = 0; elpPere = ""; HorizontalLayout layoutPere = null; int nbFils = 0; for (ElementPedagogique elp : lelp) { compteurElp++; //Si on est sur un element de niveau 1, diffrent du premier element de la liste (qui est un rappel de l'etape) if (elp.getLevel() == 1 && compteurElp > 1) { blueLevel = !blueLevel; } HorizontalLayout libElpLayout = new HorizontalLayout(); if (compteurElp > 1) { if (elp.getLevel() == 1) { //Si le pere prcdent n'avait aucun fils if (layoutPere != null && nbFils == 0) { layoutPere.setStyleName("layout-bottom-line-separator"); } layoutPere = libElpLayout; nbFils = 0; //Sur un elp de niveau 1, il est sur fond sombre libElpLayout.addStyleName("main-layout-bottom-line-separator"); //ajout dans la hashMap layoutList.put(elp.getCode(), new LinkedList<HorizontalLayout>()); elpPere = elp.getCode(); libElpLayout.setId("layout_pere_" + elp.getCode()); } else { nbFils++; libElpLayout.addStyleName("layout-bottom-line-separator"); libElpLayout.setId(compteurElp + "_" + elp.getCode() + "_layout_fils_" + elpPere); //ajout dans la hashMap layoutList.get(elpPere).add(libElpLayout); } } else { //on affiche la racine (qui est un rappel de l'etape) en blanc sur un fond trs sombre libElpLayout.addStyleName("root-layout-bottom-line-separator"); } libElpLayout.setSizeFull(); libElpLayout.setHeight("100%"); VerticalLayout libVerticalLayout = new VerticalLayout(); Label libElpLabel = new Label(elp.getLibelle()); if (elp.isEpreuve()) { libElpLabel.setStyleName("bold-italic-label"); } else { libElpLabel.setStyleName("bold-label"); } libVerticalLayout.addComponent(libElpLabel); //Si on n'est pas sur le premier elp de la liste (rappel de l'tape) on affiche un indicateur de niveau if (compteurElp > 1) { HorizontalLayout levelMainLayout = new HorizontalLayout(); levelMainLayout.setSizeFull(); levelMainLayout.setSpacing(true); levelMainLayout.setStyleName("level-indicator-layout"); int k = 0; for (int i = 0; i < elp.getLevel(); i++) { //Ajout d'un level k++; Label libLevelLayout = new Label(); libLevelLayout.setSizeFull(); libLevelLayout.setHeight("8px"); if (blueLevel) { libLevelLayout.setStyleName("layout-level-blue-indicator"); } else { libLevelLayout.setStyleName("layout-level-green-indicator"); } levelMainLayout.addComponent(libLevelLayout); } //On pense avoir 7 level maxi for (int j = k; j < 8; j++) { Label libLevelSpaceLayout = new Label(); libLevelSpaceLayout.setSizeFull(); libLevelSpaceLayout.setHeight("8px"); levelMainLayout.addComponent(libLevelSpaceLayout); } libVerticalLayout.addComponent(levelMainLayout); } libElpLayout.addComponent(libVerticalLayout); HorizontalLayout noteLayout = new HorizontalLayout(); noteLayout.setSizeFull(); VerticalLayout vlsession1 = new VerticalLayout(); Label note1 = new Label(elp.getNote1()); if (!StringUtils.hasText(elp.getNote2())) { if (elp.isEpreuve()) { note1.setStyleName("bold-italic-label"); } else { note1.setStyleName("bold-label"); } } vlsession1.addComponent(note1); if (StringUtils.hasText(elp.getRes1())) { Label adm1 = new Label(elp.getRes1()); if (!StringUtils.hasText(elp.getRes2())) { if (elp.isEpreuve()) { adm1.setStyleName("bold-italic-label"); } else { adm1.setStyleName("bold-label"); } } vlsession1.addComponent(adm1); } noteLayout.addComponent(vlsession1); VerticalLayout vlsession2 = new VerticalLayout(); Label note2 = new Label(elp.getNote2()); if (StringUtils.hasText(elp.getNote2())) { if (elp.isEpreuve()) { note2.setStyleName("bold-italic-label"); } else { note2.setStyleName("bold-label"); } } vlsession2.addComponent(note2); if (StringUtils.hasText(elp.getRes2())) { Label adm2 = new Label(elp.getRes2()); if (StringUtils.hasText(elp.getRes2())) { if (elp.isEpreuve()) { adm2.setStyleName("bold-italic-label"); } else { adm2.setStyleName("bold-label"); } } vlsession2.addComponent(adm2); } noteLayout.addComponent(vlsession2); libElpLayout.addComponent(noteLayout); notesLayout.addComponent(libElpLayout); //Au dpart, on cache les lments de niveau suprieur 1 if (compteurElp > 1 && elp.getLevel() > 1) { //libElpLayout.setVisible(false); Page.getCurrent().getJavaScript().execute("document.getElementById('" + libElpLayout.getId() + "').style.display=\"none\";"); } } //Cas o le dernier lment tait un lment le pere qui n'avait aucun fils if (layoutPere != null && nbFils == 0) { layoutPere.setStyleName("layout-bottom-line-separator"); } //Ajout du javascript for (Entry<String, LinkedList<HorizontalLayout>> entry : layoutList.entrySet()) { String pere = entry.getKey(); LinkedList<HorizontalLayout> listeLayoutFils = entry.getValue(); // traitements if (listeLayoutFils != null && listeLayoutFils.size() > 0) { String affichagejavascriptfils = ""; for (HorizontalLayout hl : listeLayoutFils) { affichagejavascriptfils += "if(document.getElementById('" + hl.getId() + "').style.display==\"none\"){document.getElementById('" + hl.getId() + "').style.display = \"block\";}else{document.getElementById('" + hl.getId() + "').style.display = \"none\";}"; } //sur le clic du layout pere, on affiche les fils Page.getCurrent().getJavaScript().execute("document.getElementById('" + "layout_pere_" + pere + "').onclick=function(){ " + affichagejavascriptfils + "};"); } } layout.addComponent(notesLayout); layout.setExpandRatio(notesLayout, 1); } else { setHeight(30, Unit.PERCENTAGE); HorizontalLayout messageLayout = new HorizontalLayout(); messageLayout.setSpacing(true); messageLayout.setMargin(true); Label labelAucunResultat = new Label( applicationContext.getMessage(NAME + ".message.aucuneresultat", null, getLocale())); labelAucunResultat.setStyleName(ValoTheme.LABEL_BOLD); messageLayout.addComponent(labelAucunResultat); layout.addComponent(messageLayout); } addComponent(layout); setExpandRatio(layout, 1); } else { refreshJavascript(); } } }
From source file:com.espertech.esper.example.stockticker.TestStockTickerMultithreaded.java
public void performTest(int numberOfThreads, int numberOfTicksToSend, int ratioPriceOutOfLimit, int numberOfSecondsWaitForCompletion) { final int totalNumTicks = numberOfTicksToSend + 2 * TestStockTickerGenerator.NUM_STOCK_NAMES; log.info(".performTest Generating data, numberOfTicksToSend=" + numberOfTicksToSend + " ratioPriceOutOfLimit=" + ratioPriceOutOfLimit); StockTickerEventGenerator generator = new StockTickerEventGenerator(); LinkedList stream = generator.makeEventStream(numberOfTicksToSend, ratioPriceOutOfLimit, TestStockTickerGenerator.NUM_STOCK_NAMES, StockTickerRegressionConstants.PRICE_LIMIT_PCT_LOWER_LIMIT, StockTickerRegressionConstants.PRICE_LIMIT_PCT_UPPER_LIMIT, StockTickerRegressionConstants.PRICE_LOWER_LIMIT, StockTickerRegressionConstants.PRICE_UPPER_LIMIT, true);//w ww .j a v a 2s .com log.info(".performTest Send limit and initial tick events - singlethreaded"); for (int i = 0; i < TestStockTickerGenerator.NUM_STOCK_NAMES * 2; i++) { Object theEvent = stream.removeFirst(); epService.getEPRuntime().sendEvent(theEvent); } log.info(".performTest Loading thread pool work queue, numberOfRunnables=" + stream.size()); ThreadPoolExecutor pool = new ThreadPoolExecutor(0, numberOfThreads, 99999, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); for (Object theEvent : stream) { SendEventRunnable runnable = new SendEventRunnable(epService, theEvent); pool.execute(runnable); } log.info(".performTest Starting thread pool, threads=" + numberOfThreads); pool.setCorePoolSize(numberOfThreads); log.info(".performTest Listening for completion"); EPRuntimeUtil.awaitCompletion(epService.getEPRuntime(), totalNumTicks, numberOfSecondsWaitForCompletion, 1, 10); pool.shutdown(); // Check results : make sure the given ratio of out-of-limit stock prices was reported int expectedNumEmitted = (numberOfTicksToSend / ratioPriceOutOfLimit) + 1; assertTrue(listener.getSize() == expectedNumEmitted); log.info(".performTest Done test"); }
From source file:jext2.DataBlockAccess.java
@NotThreadSafe(useLock = true) private void dumpBranches(int depth, LinkedList<Long> blockNrs, StringBuilder sb) throws JExt2Exception { if (blockNrs.size() == 0) return;/*from w w w.j a v a 2s.c o m*/ if (depth > 0) { /* indirection exists -> go down */ depth -= 1; for (long nr : blockNrs) { if (nr == 0) continue; LinkedList<Long> nextBlockNrs = blocks.readAllBlockNumbersFromBlockSkipZero(nr); sb.append(String.format("%" + ((depth + 1) * 10) + "s \\_ %10s \n", " ", nr)); dumpBranches(depth, nextBlockNrs, sb); } } else { /* just data pointers left */ sb.append(String.format("%" + ((depth + 2) * 10) + "s -> %10s \n", " ", blockNrs)); } }
From source file:com.splicemachine.derby.stream.function.merge.AbstractMergeJoinFlatMapFunction.java
protected void initRightScan(PeekingIterator<LocatedRow> leftPeekingIterator) throws StandardException { ExecRow firstHashRow = joinOperation.getKeyRow(leftPeekingIterator.peek().getRow()); ExecRow startPosition = joinOperation.getRightResultSet().getStartPosition(); int[] columnOrdering = getColumnOrdering(joinOperation.getRightResultSet()); int nCols = startPosition != null ? startPosition.nColumns() : 0; ExecRow scanStartOverride = null;/*from w w w. ja v a2 s . c o m*/ int[] scanKeys = null; // If start row of right table scan has as many columns as key colummns of the table, cannot further // narrow down scan space, so return right tabel scan start row. if (nCols == columnOrdering.length) { scanStartOverride = startPosition; scanKeys = columnOrdering; } else { int[] rightHashKeys = joinOperation.getRightHashKeys(); // Find valid hash column values to narrow down right scan. The valid hash columns must: // 1) not be used as a start key for inner table scan // 2) be consecutive // 3) be a key column LinkedList<Pair<Integer, Integer>> hashColumnIndexList = new LinkedList<>(); for (int i = 0; i < rightHashKeys.length; ++i) { if (rightHashKeys[i] > nCols - 1) { if ((hashColumnIndexList.isEmpty() || hashColumnIndexList.getLast().getValue() == rightHashKeys[i] - 1) && isKeyColumn(columnOrdering, rightHashKeys[i])) { hashColumnIndexList.add(new ImmutablePair<Integer, Integer>(i, rightHashKeys[i])); } else { break; } } } scanStartOverride = new ValueRow(nCols + hashColumnIndexList.size()); if (startPosition != null) { for (int i = 1; i <= startPosition.nColumns(); ++i) { scanStartOverride.setColumn(i, startPosition.getColumn(i)); } } for (int i = 0; i < hashColumnIndexList.size(); ++i) { Pair<Integer, Integer> hashColumnIndex = hashColumnIndexList.get(i); int index = hashColumnIndex.getKey(); scanStartOverride.setColumn(nCols + i + 1, firstHashRow.getColumn(index + 1)); } // Scan key should include columns // 1) preceding the first hash column, these columns are in the form of "col=constant" // 2) all hash columns that are key columns scanKeys = new int[hashColumnIndexList.size() + rightHashKeys[0]]; for (int i = 0; i < rightHashKeys[0]; ++i) { scanKeys[i] = i; } for (int i = 0; i < hashColumnIndexList.size(); ++i) { Pair<Integer, Integer> hashColumnIndex = hashColumnIndexList.get(i); int colPos = hashColumnIndex.getValue(); scanKeys[rightHashKeys[0] + i] = colPos; } } ((BaseActivation) joinOperation.getActivation()).setScanStartOverride(scanStartOverride); ((BaseActivation) joinOperation.getActivation()).setScanKeys(scanKeys); if (startPosition != null) { ((BaseActivation) joinOperation.getActivation()).setScanStopOverride(startPosition); } }
From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java
public static String[] getCNs(final X509Certificate cert) { final LinkedList<String> cnList = new LinkedList<String>(); /*/*from w w w . ja va 2 s . com*/ * Sebastian Hauer's original StrictSSLProtocolSocketFactory used * getName() and had the following comment: * * Parses a X.500 distinguished name for the value of the "Common Name" * field. This is done a bit sloppy right now and should probably be * done a bit more according to <code>RFC 2253</code>. * * I've noticed that toString() seems to do a better job than getName() * on these X500Principal objects, so I'm hoping that addresses * Sebastian's concern. * * For example, getName() gives me this: * 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d * * whereas toString() gives me this: EMAILADDRESS=juliusdavies@cucbc.com * * Looks like toString() even works with non-ascii domain names! I * tested it with "花子.co.jp" and it worked fine. */ final String subjectPrincipal = cert.getSubjectX500Principal().toString(); final StringTokenizer st = new StringTokenizer(subjectPrincipal, ",+"); while (st.hasMoreTokens()) { final String tok = st.nextToken().trim(); if (tok.length() > 3) { if (tok.substring(0, 3).equalsIgnoreCase("CN=")) { cnList.add(tok.substring(3)); } } } if (!cnList.isEmpty()) { final String[] cns = new String[cnList.size()]; cnList.toArray(cns); return cns; } else return null; }
From source file:com.launcher.silverfish.AppDrawerTabFragment.java
/** * Loads apps from the database/* ww w. j av a 2 s . c om*/ */ private void loadApps() { Intent i = new Intent(Intent.ACTION_MAIN, null); i.addCategory(Intent.CATEGORY_LAUNCHER); switch (tabId) { case 1: // Tab 1 is a special tab and includes all except for the once in other tabs // so we retrieve all apps that are in the database LinkedList<String> ordered_apps = sqlHelper.getAllApps(); // And all installed apps on the device List<ResolveInfo> availableActivities = mPacMan.queryIntentActivities(i, 0); // And only add those that are not in the database for (int j = 0; j < availableActivities.size(); j++) { ResolveInfo ri = availableActivities.get(j); // Skip the apps that are in the database if (ordered_apps.contains(ri.activityInfo.packageName)) { continue; } AppDetail app = new AppDetail(); app.label = ri.loadLabel(mPacMan); app.name = ri.activityInfo.packageName; // Load the icon later in an async task. app.icon = null; appsList.add(app); } break; default: // All other tabs just query the apps from the database LinkedList<String> app_names = sqlHelper.getAppsForTab(tabId); for (String app_name : app_names) { boolean success = addAppToList(app_name); // If the app could not be added then it was probably uninstalled, // so we have to remove it from the database if (!success) { Log.d("DB", "Removing app " + app_name + " from db"); sqlHelper.removeAppFromTab(app_name, this.tabId); } } // show the empty category notice if this tab is empty if (app_names.size() == 0) { showEmptyCategoryNotice(); } } }
From source file:com.oltpbenchmark.benchmarks.seats.SEATSWorker.java
/** * Take an existing Reservation that we know is legit and randomly decide to * either queue it for a later update or delete transaction * @param r//from w w w. j ava 2s. c o m */ protected void requeueReservation(Reservation r) { CacheType ctype = null; // Queue this motha trucka up for a deletin' if (rng.nextBoolean()) { ctype = CacheType.PENDING_DELETES; } else { ctype = CacheType.PENDING_UPDATES; } assert (ctype != null); LinkedList<Reservation> cache = CACHE_RESERVATIONS.get(ctype); assert (cache != null); cache.add(r); if (LOG.isDebugEnabled()) LOG.debug(String.format("Queued %s for %s [cache=%d]", r, ctype, cache.size())); while (cache.size() > ctype.limit) { cache.remove(); } }
From source file:com.ccc.ccm.client.activemq.StoreablePooledConnectionFactory.java
public synchronized Connection createConnection(String userName, String password) throws JMSException { if (stopped.get()) { LOG.debug("PooledConnectionFactory is stopped, skip create new connection."); return null; }//from w ww .ja v a2 s. co m ConnectionKey key = new ConnectionKey(userName, password); LinkedList<ConnectionPool> pools = cache.get(key); if (pools == null) { pools = new LinkedList<ConnectionPool>(); cache.put(key, pools); } ConnectionPool connection = null; if (pools.size() == maxConnections) { connection = pools.removeFirst(); } // Now.. we might get a connection, but it might be that we need to // dump it.. if (connection != null && connection.expiredCheck()) { connection = null; } if (connection == null) { ActiveMQConnection delegate = createConnection(key); connection = createConnectionPool(delegate); } pools.add(connection); return new PooledConnection(connection); }
From source file:net.semanticmetadata.lire.solr.LireRequestHandler.java
/** * Actual search implementation based on (i) hash based retrieval and (ii) feature based re-ranking. * * @param rsp/*from w ww . j a va 2 s . c o m*/ * @param searcher * @param hashFieldName the hash field name * @param maximumHits * @param terms * @param queryFeature * @throws IOException * @throws IllegalAccessException * @throws InstantiationException */ private void doSearch(SolrQueryRequest req, SolrQueryResponse rsp, SolrIndexSearcher searcher, String hashFieldName, int maximumHits, List<Term> terms, Query query, LireFeature queryFeature) throws IOException, IllegalAccessException, InstantiationException { // temp feature instance LireFeature tmpFeature = queryFeature.getClass().newInstance(); // Taking the time of search for statistical purposes. time = System.currentTimeMillis(); Filter filter = null; // if the request contains a filter: if (req.getParams().get("fq") != null) { // only filters with [<field>:<value> ]+ are supported StringTokenizer st = new StringTokenizer(req.getParams().get("fq"), " "); LinkedList<Term> filterTerms = new LinkedList<Term>(); while (st.hasMoreElements()) { String[] tmpToken = st.nextToken().split(":"); if (tmpToken.length > 1) { filterTerms.add(new Term(tmpToken[0], tmpToken[1])); } } if (filterTerms.size() > 0) filter = new TermsFilter(filterTerms); } TopDocs docs; // with query only. if (filter == null) { docs = searcher.search(query, numberOfCandidateResults); } else { docs = searcher.search(query, filter, numberOfCandidateResults); } // TopDocs docs = searcher.search(query, new TermsFilter(terms), numberOfCandidateResults); // with TermsFilter and boosting by simple query // TopDocs docs = searcher.search(new ConstantScoreQuery(new TermsFilter(terms)), numberOfCandidateResults); // just with TermsFilter time = System.currentTimeMillis() - time; rsp.add("RawDocsCount", docs.scoreDocs.length + ""); rsp.add("RawDocsSearchTime", time + ""); // re-rank time = System.currentTimeMillis(); TreeSet<SimpleResult> resultScoreDocs = new TreeSet<SimpleResult>(); float maxDistance = -1f; float tmpScore; String featureFieldName = FeatureRegistry.getFeatureFieldName(hashFieldName); // iterating and re-ranking the documents. BinaryDocValues binaryValues = MultiDocValues.getBinaryValues(searcher.getIndexReader(), featureFieldName); // *** # BytesRef bytesRef;// = new BytesRef(); for (int i = 0; i < docs.scoreDocs.length; i++) { // using DocValues to retrieve the field values ... bytesRef = binaryValues.get(docs.scoreDocs[i].doc); tmpFeature.setByteArrayRepresentation(bytesRef.bytes, bytesRef.offset, bytesRef.length); // Getting the document from the index. // This is the slow step based on the field compression of stored fields. // tmpFeature.setByteArrayRepresentation(d.getBinaryValue(name).bytes, d.getBinaryValue(name).offset, d.getBinaryValue(name).length); tmpScore = queryFeature.getDistance(tmpFeature); if (resultScoreDocs.size() < maximumHits) { // todo: There's potential here for a memory saver, think of a clever data structure that can do the trick without creating a new SimpleResult for each result. resultScoreDocs.add( new SimpleResult(tmpScore, searcher.doc(docs.scoreDocs[i].doc), docs.scoreDocs[i].doc)); maxDistance = resultScoreDocs.last().getDistance(); } else if (tmpScore < maxDistance) { // if it is nearer to the sample than at least one of the current set: // remove the last one ... resultScoreDocs.remove(resultScoreDocs.last()); // add the new one ... resultScoreDocs.add( new SimpleResult(tmpScore, searcher.doc(docs.scoreDocs[i].doc), docs.scoreDocs[i].doc)); // and set our new distance border ... maxDistance = resultScoreDocs.last().getDistance(); } } // System.out.println("** Creating response."); time = System.currentTimeMillis() - time; rsp.add("ReRankSearchTime", time + ""); LinkedList list = new LinkedList(); for (Iterator<SimpleResult> it = resultScoreDocs.iterator(); it.hasNext();) { SimpleResult result = it.next(); HashMap m = new HashMap(2); m.put("d", result.getDistance()); // add fields as requested: if (req.getParams().get("fl") == null) { m.put("id", result.getDocument().get("id")); if (result.getDocument().get("title") != null) m.put("title", result.getDocument().get("title")); } else { String fieldsRequested = req.getParams().get("fl"); if (fieldsRequested.contains("score")) { m.put("score", result.getDistance()); } if (fieldsRequested.contains("*")) { // all fields for (IndexableField field : result.getDocument().getFields()) { String tmpField = field.name(); if (result.getDocument().getFields(tmpField).length > 1) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getValues(tmpField)); } else if (result.getDocument().getFields(tmpField).length > 0) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getFields(tmpField)[0].stringValue()); } } } else { StringTokenizer st; if (fieldsRequested.contains(",")) st = new StringTokenizer(fieldsRequested, ","); else st = new StringTokenizer(fieldsRequested, " "); while (st.hasMoreElements()) { String tmpField = st.nextToken(); if (result.getDocument().getFields(tmpField).length > 1) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getValues(tmpField)); } else if (result.getDocument().getFields(tmpField).length > 0) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getFields(tmpField)[0].stringValue()); } } } } // m.put(field, result.getDocument().get(field)); // m.put(field.replace("_ha", "_hi"), result.getDocument().getBinaryValue(field)); list.add(m); } rsp.add("docs", list); // rsp.add("Test-name", "Test-val"); }
From source file:org.grails.datastore.mapping.simpledb.util.SimpleDBTemplateImpl.java
private List<Item> queryInternal(String query, int max, int attempt) { LinkedList<Item> items = new LinkedList<Item>(); try {// ww w.j av a 2 s .c o m SelectRequest selectRequest = new SelectRequest(query); SelectResult result = sdb.select(selectRequest); items.addAll(result.getItems()); String nextToken = null; do { nextToken = result.getNextToken(); if (nextToken != null) { selectRequest = new SelectRequest(query).withNextToken(nextToken); result = sdb.select(selectRequest); items.addAll(result.getItems()); } } while (nextToken != null && items.size() < max); //truncate if needed while (items.size() > max) { items.removeLast(); } return items; } catch (AmazonServiceException e) { if (SimpleDBUtil.AWS_ERR_CODE_NO_SUCH_DOMAIN.equals(e.getErrorCode())) { throw new IllegalArgumentException("no such domain: " + query, e); } else if (SimpleDBUtil.AWS_ERR_CODE_SERVICE_UNAVAILABLE.equals(e.getErrorCode())) { //retry after a small pause SimpleDBUtil.sleepBeforeRetry(attempt); attempt++; return queryInternal(query, max, attempt); } else { throw e; } } }