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:net.semanticmetadata.lire.solr.FastLireRequestHandler.java
/** * Search based on the given image hashes. * * @param req/*from w w w.ja v a2 s . co m*/ * @param rsp * @throws java.io.IOException * @throws IllegalAccessException * @throws InstantiationException */ private void handleHashSearch(SolrQueryRequest req, SolrQueryResponse rsp) throws IOException, IllegalAccessException, InstantiationException { SolrParams params = req.getParams(); SolrIndexSearcher searcher = req.getSearcher(); // get the params needed: // hashes=x y z ... // feature=<base64> // field=<cl_ha|ph_ha|...> String[] hashStrings = params.get("hashes").trim().split(" "); byte[] featureVector = Base64.decodeBase64(params.get("feature")); String paramField = "cl_ha"; if (req.getParams().get("field") != null) paramField = req.getParams().get("field"); int paramRows = defaultNumberOfResults; if (params.getInt("rows") != null) paramRows = params.getInt("rows"); numberOfQueryTerms = req.getParams().getDouble("accuracy", DEFAULT_NUMBER_OF_QUERY_TERMS); numberOfCandidateResults = req.getParams().getInt("candidates", DEFAULT_NUMBER_OF_CANDIDATES); // create boolean query: // System.out.println("** Creating query."); LinkedList<Term> termFilter = new LinkedList<Term>(); BooleanQuery query = new BooleanQuery(); for (int i = 0; i < hashStrings.length; i++) { // be aware that the hashFunctionsFileName of the field must match the one you put the hashes in before. hashStrings[i] = hashStrings[i].trim(); if (hashStrings[i].length() > 0) { termFilter.add(new Term(paramField, hashStrings[i].trim())); // System.out.println("** " + field + ": " + hashes[i].trim()); } } Collections.shuffle(termFilter); for (int k = 0; k < termFilter.size() * numberOfQueryTerms; k++) { query.add(new BooleanClause(new TermQuery(termFilter.get(k)), BooleanClause.Occur.SHOULD)); } // System.out.println("** Doing search."); // query feature LireFeature queryFeature = (LireFeature) FeatureRegistry.getClassForHashField(paramField).newInstance(); queryFeature.setByteArrayRepresentation(featureVector); // get results: doSearch(req, rsp, searcher, paramField, paramRows, termFilter, new MatchAllDocsQuery(), queryFeature); }
From source file:jext2.DataInode.java
/** * Read Inode data/* w w w. j av a2 s. c o m*/ * @param size size of the data to be read * @param offset start address in data area * @return buffer of size size containing data. * @throws FileTooLarge * @throws IoError */ public ByteBuffer readData(int size, long fileOffset) throws JExt2Exception, FileTooLarge { /* Returning null may break things somewhere.. * Zero length buffer breaks something in jlowfuse's c code */ if (getSize() == 0) return ByteBuffer.allocateDirect(1); /* * size may be larger than the inode.size, it doesn't make sense to return * 4k of zeros */ if (size > getSize()) size = (int) getSize(); ByteBuffer buf = ByteBuffer.allocateDirect(size); int blocksize = superblock.getBlocksize(); long i = 0; long firstBlock = fileOffset / blocksize; long offset = fileOffset % blocksize; /* * just as size may be larger than the inode's data, the number of blocks * may also be. */ long approxBlocks = (size / blocksize) + 1; long maxBlocks = this.getBlocks() / (superblock.getBlocksize() / 512); if (approxBlocks > maxBlocks) approxBlocks = maxBlocks; while (i < approxBlocks) { long start = firstBlock + i; long stop = firstBlock + approxBlocks; LinkedList<Long> b = accessData().getBlocks(start, stop); int blocksRead; /* * Note on the sparse file support: * getBlocks will return null if there is no data block for this * logical address. So just move the position count blocks forward. */ if (b == null) { /* hole */ blocksRead = 1; int unboundedLimit = buf.position() + blocksize; int limit = Math.min(unboundedLimit, buf.capacity()); assert limit <= buf.capacity() : "New position, limit " + limit + " is beyond buffer's capacity, " + buf; buf.limit(limit); buf.position(limit); assert buf.limit() == buf.position(); } else { /* blocks */ blocksRead = b.size(); long pos = b.getFirst() * blocksize + offset; int unboundedLimit = buf.position() + blocksRead * blocksize; int limit = Math.min(unboundedLimit, buf.capacity()); assert limit <= buf.capacity() : "New limit " + limit + " is beyond buffer's capacity, " + buf; buf.limit(limit); blockAccess.readToBufferUnsynchronized(pos, buf); } i += blocksRead; offset = 0; /* This should be removed soon. IllegalMonitorStateException happen * occasionally for unknown reasons. */ try { accessData().getHierarchyLock().readLock().unlock(); } catch (IllegalMonitorStateException e) { Logger log = Filesystem.getLogger(); log.warning("IllegalMonitorStateException encountered in readData, inode=" + this); log.warning(String.format( "context for exception: blocks=%s i=%d approxBlocks=%d off=%d buf=%s readlock=%s lock.readlock.holds=%s", b, i, approxBlocks, fileOffset, buf, accessData().getHierarchyLock(), accessData().getHierarchyLock().getReadHoldCount())); } if (buf.capacity() == buf.limit()) break; } assert buf.position() == buf.limit() : "Buffer wasn't filled completely"; assert buf.limit() == size : "Read buffer size does not match request size"; if (buf.limit() > getSize()) buf.limit((int) getSize()); buf.rewind(); return buf; }
From source file:com.trsst.Command.java
public int doPush(Client client, CommandLine commands, LinkedList<String> arguments, PrintStream out) { // if a second argument was specified if (arguments.size() < 2) { printPushUsage();// w ww. j ava2 s.com return 127; // "command not found" } URL url; String host = arguments.removeFirst().toString(); Client destinationClient; try { url = new URL(host); // this argument is a server url destinationClient = new Client(url); System.err.println("Using service: " + host); } catch (MalformedURLException e) { printPushUsage(); return 127; // "command not found" } for (String id : arguments) { System.out.println(destinationClient.push(client.pull(id), url)); // Feed feed = client.pull(id); // if ( feed != null ) { // feed = client.push(feed, url); // if ( feed != null ) { // out.println(feed); // } else { // System.err.println("Failed to push feed for id: " + id); // } // } else { // System.err.println("Failed to pull feed for id: " + id); // } } return 0; // "OK" }
From source file:com.stimulus.archiva.domain.Volumes.java
public synchronized void setVolumePriority(int id, Priority priority) { LinkedList<Volume> list = volumes; Volume v = list.get(id);//from w w w. j a v a 2s . c o m if (v.getStatus() != Volume.Status.UNUSED) // can only reorder unused return; if (priority == Priority.PRIORITY_HIGHER && id - 1 >= 0) { // cannot affect non unused vols Volume vs = list.get(id - 1); if (vs.getStatus() != Volume.Status.UNUSED) return; } list.remove(v); switch (priority) { case PRIORITY_HIGHER: if ((id - 1) <= 0) list.addFirst(v); else list.add(id - 1, v); break; case PRIORITY_LOWER: if ((id + 1) >= list.size()) list.addLast(v); else list.add(id + 1, v); break; } }
From source file:com.trsst.Command.java
public int doPull(Client client, CommandLine commands, LinkedList<String> arguments, PrintStream out) { if (arguments.size() < 1) { printPullUsage();/* w ww. j ava2s.c o m*/ return 127; // "command not found" } // decryption option String id = commands.getOptionValue("d"); PrivateKey[] decryptionKeys = null; if (id != null) { // obtain password id = Common.toFeedIdString(id); char[] password = null; String pass = commands.getOptionValue("p"); if (pass != null) { password = pass.toCharArray(); } else { try { Console console = System.console(); if (console != null) { password = console.readPassword("Password: "); } else { log.info("No console detected for password input."); } } catch (Throwable t) { log.error("Unexpected error while reading password", t); } } if (password == null) { log.error("Password is required to decrypt."); return 127; // "command not found" } if (password.length < 6) { System.err.println("Password must be at least six characters in length."); return 127; // "command not found" } // obtain keys KeyPair signingKeys = null; KeyPair encryptionKeys = null; String keyPath = commands.getOptionValue("k"); File keyFile; if (keyPath != null) { keyFile = new File(keyPath, id + Common.KEY_EXTENSION); } else { keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION); } if (keyFile.exists()) { System.err.println("Using existing account id: " + id); } else { System.err.println("Cannot locate keys for account id: " + id); return 78; // "configuration error" } signingKeys = readSigningKeyPair(id, keyFile, password); if (signingKeys != null) { encryptionKeys = readEncryptionKeyPair(id, keyFile, password); if (encryptionKeys == null) { decryptionKeys = new PrivateKey[] { signingKeys.getPrivate() }; } else { decryptionKeys = new PrivateKey[] { encryptionKeys.getPrivate(), signingKeys.getPrivate() }; } } } List<String> ids = new LinkedList<String>(); for (String arg : arguments) { ids.add(arg); } for (String feedId : ids) { try { Object feed; if (decryptionKeys != null) { feed = client.pull(feedId, decryptionKeys); } else { feed = client.pull(feedId); } if (feed != null) { if (format) { out.println(Common.formatXML(feed.toString())); } else { out.println(feed.toString()); } } else { System.err.println("Could not fetch: " + feedId + " : " + client); } } catch (Throwable t) { log.error("Unexpected error on pull: " + feedId + " : " + client, t); } } return 0; // "OK" }
From source file:com.nhncorp.lucy.security.xss.XssSaxFilter.java
/** * @param writer// w ww . j a va 2s .co m * @param neloLogWriter * @param stackForObjectTag * @param stackForAllowNetworkingValue * @throws IOException */ private boolean doObjectEndTagProcess(Writer writer, StringWriter neloLogWriter, LinkedList<Element> stackForObjectTag, LinkedList<String> stackForAllowNetworkingValue) throws IOException { List<String> paramNameList = new ArrayList<String>(); Element item = null; while (stackForObjectTag.size() > 0) { item = stackForObjectTag.pop(); if ("object".equalsIgnoreCase(item.getName())) { break; } else { Attribute nameAttr = item.getAttribute("name"); if (nameAttr != null) { paramNameList.add(nameAttr.getValue()); } } } if (item == null || !"object".equalsIgnoreCase(item.getName())) { return false; } else if (item != null && item.isDisabled()) { return true; } // PARAMLIST ( ?(param) )? param(paramNameList)? ? object ? . for (int index = 0; index < PARAMLIST.length; index++) { Pattern pattern = PARAMLIST[index]; boolean exist = false; for (String paramName : paramNameList) { if (pattern.matcher(paramName).matches()) { exist = true; break; } } if (!exist) { // ? param switch (index) { // <param name="invokeURLs" value="false" /> case 0: Element invokeURLs = new Element("param"); invokeURLs.putAttribute("name", "\"invokeURLs\""); invokeURLs.putAttribute("value", "\"false\""); this.serialize(writer, invokeURLs, neloLogWriter); break; // <param name="autostart" value="false" /> case 1: Element autostart = new Element("param"); autostart.putAttribute("name", "\"autostart\""); autostart.putAttribute("value", "\"false\""); this.serialize(writer, autostart, neloLogWriter); break; // <param name="allowScriptAccess" value="never" /> case 2: Element allowScriptAccess = new Element("param"); allowScriptAccess.putAttribute("name", "\"allowScriptAccess\""); allowScriptAccess.putAttribute("value", "\"never\""); this.serialize(writer, allowScriptAccess, neloLogWriter); break; // <param name="allowNetworking" value="all|internal" /> case 3: Element allowNetworking = new Element("param"); allowNetworking.putAttribute("name", "\"allowNetworking\""); allowNetworking.putAttribute("value", stackForAllowNetworkingValue.size() == 0 ? "\"internal\"" : stackForAllowNetworkingValue.pop()); this.serialize(writer, allowNetworking, neloLogWriter); break; // <param name="autoplay" value="false" /> case 4: Element autoplay = new Element("param"); autoplay.putAttribute("name", "\"autoplay\""); autoplay.putAttribute("value", "\"false\""); this.serialize(writer, autoplay, neloLogWriter); break; // <param name="enablehref" value="flase" /> case 5: Element enablehref = new Element("param"); enablehref.putAttribute("name", "\"enablehref\""); enablehref.putAttribute("value", "\"false\""); this.serialize(writer, enablehref, neloLogWriter); break; // <param name="enablejavascript" value="flase" /> case 6: Element enablejavascript = new Element("param"); enablejavascript.putAttribute("name", "\"enablejavascript\""); enablejavascript.putAttribute("value", "\"false\""); this.serialize(writer, enablejavascript, neloLogWriter); break; // <param name="nojava" value="true" /> case 7: Element nojava = new Element("param"); nojava.putAttribute("name", "\"nojava\""); nojava.putAttribute("value", "\"true\""); this.serialize(writer, nojava, neloLogWriter); break; // <param name="AllowHtmlPopupwindow" value="false" /> case 8: Element allowHtmlPopupwindow = new Element("param"); allowHtmlPopupwindow.putAttribute("name", "\"AllowHtmlPopupwindow\""); allowHtmlPopupwindow.putAttribute("value", "\"false\""); this.serialize(writer, allowHtmlPopupwindow, neloLogWriter); break; // <param name="enableHtmlAccess" value="false" /> case 9: Element enableHtmlAccess = new Element("param"); enableHtmlAccess.putAttribute("name", "\"enableHtmlAccess\""); enableHtmlAccess.putAttribute("value", "\"false\""); this.serialize(writer, enableHtmlAccess, neloLogWriter); break; default: System.out.println("? ?."); } } } return false; }
From source file:com.offbynull.voip.audio.gateways.io.OutputWriteRunnable.java
@Override public void run() { LOG.info("Output thread started: {}", openOutputDevice); try {// w w w . j a va 2s . c o m byte[] internalBuffer = new byte[bufferSize]; while (true) { LinkedList<OutputData> readBuffers = dumpQueue(); Iterator<OutputData> readBuffersIt = readBuffers.descendingIterator(); int remainingAmount = internalBuffer.length; int requiredAmount = 0; int copyAmount = 0; while (remainingAmount > 0 && readBuffersIt.hasNext()) { OutputData readBuffer = readBuffersIt.next(); byte[] readBufferData = readBuffer.getData(); requiredAmount = readBufferData.length; copyAmount = Math.min(remainingAmount, requiredAmount); int copyFrom = requiredAmount - copyAmount; int copyTo = remainingAmount - copyAmount; System.arraycopy(readBufferData, copyFrom, internalBuffer, copyTo, copyAmount); remainingAmount -= copyAmount; } if (copyAmount != requiredAmount || readBuffersIt.hasNext()) { // more than 1 buffer or some data not copied, show a warning LOG.info("Excess data read: {} buffers -- only playing last {} bytes", readBuffers.size(), bufferSize); } try { openOutputDevice.write(internalBuffer, remainingAmount, internalBuffer.length - remainingAmount); } catch (IllegalArgumentException iae) { LOG.warn("Output buffer potentially malformed: {}", iae.toString()); } } } catch (Exception e) { LOG.info("Output thread stopped: {}", e.toString()); } }
From source file:fi.ni.IFC_ClassModel.java
/** * Map entries.//from w ww. j a v a2s .com */ @SuppressWarnings("unchecked") private void mapEntries() { for (Map.Entry<Long, IFC_X3_VO> entry : linemap.entrySet()) { IFC_X3_VO vo = entry.getValue(); // Initialize the object_buffer try { Thing thing = object_buffer.get(vo.getLine_num()); if (thing == null) { @SuppressWarnings("rawtypes") Class cls = Class.forName("fi.ni.ifc2x3." + entities.get(vo.name).getName()); @SuppressWarnings("rawtypes") Constructor ct = cls.getConstructor(); thing = (Thing) ct.newInstance(); thing.i.drum_setLine_number(vo.getLine_num()); object_buffer.put(vo.getLine_num(), (Thing) thing); } } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < vo.list.size(); i++) { Object o = vo.list.get(i); if (String.class.isInstance(o)) { String s = (String) o; if (s.length() < 1) continue; if (s.charAt(0) == '#') { Object or = linemap.get(toLong(s.substring(1))); vo.list.set(i, or); } } if (LinkedList.class.isInstance(o)) { LinkedList<Object> tmp_list = (LinkedList<Object>) o; for (int j = 0; j < tmp_list.size(); j++) { Object o1 = tmp_list.get(j); if (String.class.isInstance(o1)) { String s = (String) o1; if (s.length() < 1) continue; if (s.charAt(0) == '#') { Object or = linemap.get(toLong(s.substring(1))); if (or == null) { System.err.println("Reference to non-existing line in the IFC file."); tmp_list.set(j, "-"); } else tmp_list.set(j, or); } } else if (LinkedList.class.isInstance(o1)) { LinkedList<Object> tmp2_list = (LinkedList<Object>) o1; for (int j2 = 0; j2 < tmp2_list.size(); j2++) { Object o2 = tmp2_list.get(j2); if (String.class.isInstance(o2)) { String s = (String) o2; if (s.length() < 1) continue; if (s.charAt(0) == '#') { Object or = linemap.get(toLong(s.substring(1))); if (or == null) { System.err.println("Reference to non-existing line in the IFC file."); tmp_list.set(j, "-"); } else tmp_list.set(j, or); } } } } } } } } }
From source file:com.oltpbenchmark.benchmarks.auctionmark.AuctionMarkProfile.java
/** * /*www . ja va 2 s. c o m*/ * @param itemSet * @param needCurrentPrice * @param needFutureEndDate TODO * @return */ private ItemInfo getRandomItem(LinkedList<ItemInfo> itemSet, boolean needCurrentPrice, boolean needFutureEndDate) { Timestamp currentTime = this.updateAndGetCurrentTime(); int num_items = itemSet.size(); int idx = -1; ItemInfo itemInfo = null; if (LOG.isTraceEnabled()) LOG.trace(String.format("Getting random ItemInfo [numItems=%d, currentTime=%s, needCurrentPrice=%s]", num_items, currentTime, needCurrentPrice)); long tries = 1000; tmp_seenItems.clear(); while (num_items > 0 && tries-- > 0 && tmp_seenItems.size() < num_items) { idx = this.rng.nextInt(num_items); ItemInfo temp = itemSet.get(idx); assert (temp != null); if (tmp_seenItems.contains(temp)) continue; tmp_seenItems.add(temp); // Needs to have an embedded currentPrice if (needCurrentPrice && temp.hasCurrentPrice() == false) { continue; } // If they want an item that is ending in the future, then we compare it with // the current timestamp if (needFutureEndDate) { boolean compareTo = (temp.getEndDate().compareTo(currentTime) < 0); if (LOG.isTraceEnabled()) LOG.trace("CurrentTime:" + currentTime + " / EndTime:" + temp.getEndDate() + " [compareTo=" + compareTo + "]"); if (temp.hasEndDate() == false || compareTo) { continue; } } // Uniform itemInfo = temp; break; } // WHILE if (itemInfo == null) { if (LOG.isDebugEnabled()) LOG.debug("Failed to find ItemInfo [hasCurrentPrice=" + needCurrentPrice + ", needFutureEndDate=" + needFutureEndDate + "]"); return (null); } assert (idx >= 0); // Take the item out of the set and insert back to the front // This is so that we can maintain MRU->LRU ordering itemSet.remove(idx); itemSet.addFirst(itemInfo); if (needCurrentPrice) { assert (itemInfo.hasCurrentPrice()) : "Missing currentPrice for " + itemInfo; assert (itemInfo.getCurrentPrice() > 0) : "Negative currentPrice '" + itemInfo.getCurrentPrice() + "' for " + itemInfo; } if (needFutureEndDate) { assert (itemInfo.hasEndDate()) : "Missing endDate for " + itemInfo; } return itemInfo; }
From source file:fi.ni.IFC_ClassModel.java
/** * Estimate_level./*from ww w. j a v a 2s . c o m*/ * * @param vo * the value object representing the IFC file line * @param level * the iteration count in the recursive run */ private void estimate_level(IFC_X3_VO vo, int level) { if (level > vo.getMaxlevel()) vo.setMaxlevel(level); EntityVO evo = entities.get(vo.name); int pointer = 0; for (int i = 0; i < vo.list.size(); i++) { Object o = vo.list.get(i); if (String.class.isInstance(o)) { if (!((String) o).equals("$")) { // Do not handle empty values if ((evo != null) && (evo.getDerived_attribute_list() != null) && (evo.getDerived_attribute_list().size() > pointer)) { if (evo.getDerived_attribute_list().get(pointer).getName() .equals(IFC_CLassModelConstants.GLOBAL_ID)) { vo.setGid(filter_extras((String) o)); } } } pointer++; } else if (IFC_X3_VO.class.isInstance(o)) { estimate_level((IFC_X3_VO) o, level + 1); } else if (LinkedList.class.isInstance(o)) { @SuppressWarnings("unchecked") LinkedList<Object> tmp_list = (LinkedList<Object>) o; for (int j = 0; j < tmp_list.size(); j++) { Object o1 = tmp_list.get(j); if (IFC_X3_VO.class.isInstance(o1)) { estimate_level((IFC_X3_VO) o1, level + 1); } else if (LinkedList.class.isInstance(o1)) { @SuppressWarnings("unchecked") LinkedList<Object> tmp2_list = (LinkedList<Object>) o1; for (int j2 = 0; j2 < tmp2_list.size(); j2++) { Object o2 = tmp2_list.get(j2); if (IFC_X3_VO.class.isInstance(o2)) { estimate_level((IFC_X3_VO) o2, level + 1); } else if (String.class.isInstance(o2)) { // if (!((String) o2).equals("?")) // System.err.println("ts:" + ((String) o2)); } else if (Character.class.isInstance(o2)) ; else System.err.println("t:" + o2.getClass().getSimpleName()); } } } } } }