List of usage examples for java.util LinkedList addFirst
public void addFirst(E e)
From source file:com.turn.ttorrent.common.Torrent.java
/** * Helper method to create a {@link Torrent} object for a set of files. * * <p>/*from w ww .j a va2 s . co m*/ * Hash the given files to create the multi-file {@link Torrent} object * representing the Torrent meta-info about them, needed for announcing * and/or sharing these files. Since we created the torrent, we're * considering we'll be a full initial seeder for it. * </p> * * @param parent The parent directory or location of the torrent files, * also used as the torrent's name. * @param files The files to add into this torrent. * @param announce The announce URI that will be used for this torrent. * @param announceList The announce URIs organized as tiers that will * be used for this torrent * @param createdBy The creator's name, or any string identifying the * torrent's creator. */ private static Torrent create(File parent, List<File> files, int pieceLength, URI announce, List<List<URI>> announceList, String createdBy) throws InterruptedException, IOException, NoSuchAlgorithmException { if (files == null || files.isEmpty()) { logger.info("Creating single-file torrent for {}...", parent.getName()); } else { logger.info("Creating {}-file torrent {}...", files.size(), parent.getName()); } Map<String, BEValue> torrent = new HashMap<String, BEValue>(); if (announce != null) { torrent.put("announce", new BEValue(announce.toString())); } if (announceList != null) { List<BEValue> tiers = new LinkedList<BEValue>(); for (List<URI> trackers : announceList) { List<BEValue> tierInfo = new LinkedList<BEValue>(); for (URI trackerURI : trackers) { tierInfo.add(new BEValue(trackerURI.toString())); } tiers.add(new BEValue(tierInfo)); } torrent.put("announce-list", new BEValue(tiers)); } torrent.put("creation date", new BEValue(new Date().getTime() / 1000)); torrent.put("created by", new BEValue(createdBy)); Map<String, BEValue> info = new TreeMap<String, BEValue>(); info.put("name", new BEValue(parent.getName())); info.put("piece length", new BEValue(pieceLength)); if (files == null || files.isEmpty()) { info.put("length", new BEValue(parent.length())); info.put("pieces", new BEValue(Torrent.hashFile(parent, pieceLength), Torrent.BYTE_ENCODING)); } else { List<BEValue> fileInfo = new LinkedList<BEValue>(); for (File file : files) { Map<String, BEValue> fileMap = new HashMap<String, BEValue>(); fileMap.put("length", new BEValue(file.length())); LinkedList<BEValue> filePath = new LinkedList<BEValue>(); while (file != null) { if (file.equals(parent)) { break; } filePath.addFirst(new BEValue(file.getName())); file = file.getParentFile(); } fileMap.put("path", new BEValue(filePath)); fileInfo.add(new BEValue(fileMap)); } info.put("files", new BEValue(fileInfo)); info.put("pieces", new BEValue(Torrent.hashFiles(files, pieceLength), Torrent.BYTE_ENCODING)); } torrent.put("info", new BEValue(info)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BEncoder.bencode(new BEValue(torrent), baos); return new Torrent(baos.toByteArray(), true); }
From source file:com.unboundid.scim2.common.utils.Parser.java
/** * Read a filter from the reader.// ww w. ja va 2 s. c om * * @param reader The reader to read the filter from. * @param isValueFilter Whether to read the filter as a value filter. * @return The parsed filter. * @throws BadRequestException If the filter string could not be parsed. */ private static Filter readFilter(final StringReader reader, final boolean isValueFilter) throws BadRequestException { final Stack<Filter> outputStack = new Stack<Filter>(); final Stack<String> precedenceStack = new Stack<String>(); String token; String previousToken = null; while ((token = readFilterToken(reader, isValueFilter)) != null) { if (token.equals("(") && expectsNewFilter(previousToken)) { precedenceStack.push(token); } else if (token.equalsIgnoreCase(FilterType.NOT.getStringValue()) && expectsNewFilter(previousToken)) { // "not" should be followed by an ( String nextToken = readFilterToken(reader, isValueFilter); if (nextToken == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (!nextToken.equals("(")) { final String msg = String.format("Expected '(' at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } precedenceStack.push(token); } else if (token.equals(")") && !expectsNewFilter(previousToken)) { String operator = closeGrouping(precedenceStack, outputStack, false); if (operator == null) { final String msg = String.format( "No opening parenthesis matching closing " + "parenthesis at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } if (operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) { // Treat "not" the same as "(" except wrap everything in a not filter. outputStack.push(Filter.not(outputStack.pop())); } } else if (token.equalsIgnoreCase(FilterType.AND.getStringValue()) && !expectsNewFilter(previousToken)) { // and has higher precedence than or. precedenceStack.push(token); } else if (token.equalsIgnoreCase(FilterType.OR.getStringValue()) && !expectsNewFilter(previousToken)) { // pop all the pending ands first before pushing or. LinkedList<Filter> andComponents = new LinkedList<Filter>(); while (!precedenceStack.isEmpty()) { if (precedenceStack.peek().equalsIgnoreCase(FilterType.AND.getStringValue())) { precedenceStack.pop(); andComponents.addFirst(outputStack.pop()); } else { break; } if (!andComponents.isEmpty()) { andComponents.addFirst(outputStack.pop()); outputStack.push(Filter.and(andComponents)); } } precedenceStack.push(token); } else if (token.endsWith("[") && expectsNewFilter(previousToken)) { // This is a complex value filter. final Path filterAttribute; try { filterAttribute = parsePath(token.substring(0, token.length() - 1)); } catch (final BadRequestException e) { Debug.debugException(e); final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (filterAttribute.isRoot()) { final String msg = String.format("Attribute path expected at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } outputStack.push(Filter.hasComplexValue(filterAttribute, readFilter(reader, true))); } else if (isValueFilter && token.equals("]") && !expectsNewFilter(previousToken)) { break; } else if (expectsNewFilter(previousToken)) { // This must be an attribute path followed by operator and maybe value. final Path filterAttribute; try { filterAttribute = parsePath(token); } catch (final BadRequestException e) { Debug.debugException(e); final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (filterAttribute.isRoot()) { final String msg = String.format("Attribute path expected at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } String op = readFilterToken(reader, isValueFilter); if (op == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (op.equalsIgnoreCase(FilterType.PRESENT.getStringValue())) { outputStack.push(Filter.pr(filterAttribute)); } else { ValueNode valueNode; try { // Mark the beginning of the JSON value so we can later reset back // to this position and skip the actual chars that were consumed // by Jackson. The Jackson parser is buffered and reads everything // until the end of string. reader.mark(0); ScimJsonFactory scimJsonFactory = (ScimJsonFactory) JsonUtils.getObjectReader() .getFactory(); JsonParser parser = scimJsonFactory.createScimFilterParser(reader); // The object mapper will return a Java null for JSON null. // Have to distinguish between reading a JSON null and encountering // the end of string. if (parser.getCurrentToken() == null && parser.nextToken() == null) { // End of string. valueNode = null; } else { valueNode = parser.readValueAsTree(); // This is actually a JSON null. Use NullNode. if (valueNode == null) { valueNode = JsonUtils.getJsonNodeFactory().nullNode(); } } // Reset back to the beginning of the JSON value. reader.reset(); // Skip the number of chars consumed by JSON parser. reader.skip(parser.getCurrentLocation().getCharOffset()); } catch (IOException e) { final String msg = String.format("Invalid comparison value at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (valueNode == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (op.equalsIgnoreCase(FilterType.EQUAL.getStringValue())) { outputStack.push(Filter.eq(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.NOT_EQUAL.getStringValue())) { outputStack.push(Filter.ne(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.CONTAINS.getStringValue())) { outputStack.push(Filter.co(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.STARTS_WITH.getStringValue())) { outputStack.push(Filter.sw(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.ENDS_WITH.getStringValue())) { outputStack.push(Filter.ew(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.GREATER_THAN.getStringValue())) { outputStack.push(Filter.gt(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.GREATER_OR_EQUAL.getStringValue())) { outputStack.push(Filter.ge(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.LESS_THAN.getStringValue())) { outputStack.push(Filter.lt(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.LESS_OR_EQUAL.getStringValue())) { outputStack.push(Filter.le(filterAttribute, valueNode)); } else { final String msg = String.format("Unrecognized attribute operator '%s' at position %d. " + "Expected: eq,ne,co,sw,ew,pr,gt,ge,lt,le", op, reader.mark); throw BadRequestException.invalidFilter(msg); } } } else { final String msg = String.format("Unexpected character '%s' at position %d", token, reader.mark); throw BadRequestException.invalidFilter(msg); } previousToken = token; } closeGrouping(precedenceStack, outputStack, true); if (outputStack.isEmpty()) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } return outputStack.pop(); }
From source file:uk.ac.kcl.iop.brc.core.pipeline.dncpipeline.service.PythonService.java
/** * Runs the Python interpreter.// www . j a v a2 s . c o m * @param args List of arguments to be supplied to the python command. * @return Result from python string * @throws IOException */ public String runFile(List<String> args) throws IOException { LinkedList<String> list = new LinkedList<>(args); list.addFirst("python"); ProcessBuilder processBuilder = new ProcessBuilder(list); Process p = processBuilder.start(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); StringWriter stringWriter = new StringWriter(); in.lines().forEach(stringWriter::append); p.destroy(); return stringWriter.toString(); }
From source file:ga.rugal.jpt.common.tracker.common.Torrent.java
/** * Helper method to create a {@link Torrent} object for a set of files. * * <p>/* w ww . j a v a 2 s . co m*/ * Hash the given files to create the multi-file {@link Torrent} object representing the Torrent * meta-info about them, needed for announcing and/or sharing these files. Since we created the * torrent, we're considering we'll be a full initial seeder for it. * </p> * * @param parent The parent directory or location of the torrent files, also used as the * torrent's name. * @param files The files to add into this torrent. * @param announce The announce URI that will be used for this torrent. * @param announceList The announce URIs organized as tiers that will be used for this torrent * @param createdBy The creator's name, or any string identifying the torrent's creator. */ private static Torrent create(File parent, List<File> files, int pieceLength, URI announce, List<List<URI>> announceList, String createdBy) throws InterruptedException, IOException { if (files == null || files.isEmpty()) { LOG.info("Creating single-file torrent for {}...", parent.getName()); } else { LOG.info("Creating {}-file torrent {}...", files.size(), parent.getName()); } Map<String, BEValue> torrent = new HashMap<>(); if (announce != null) { torrent.put("announce", new BEValue(announce.toString())); } if (announceList != null) { List<BEValue> tiers = new LinkedList<>(); for (List<URI> trackers : announceList) { List<BEValue> tierInfo = new LinkedList<>(); for (URI trackerURI : trackers) { tierInfo.add(new BEValue(trackerURI.toString())); } tiers.add(new BEValue(tierInfo)); } torrent.put("announce-list", new BEValue(tiers)); } torrent.put("creation date", new BEValue(new Date().getTime() / 1000)); torrent.put("created by", new BEValue(createdBy)); Map<String, BEValue> info = new TreeMap<>(); info.put("name", new BEValue(parent.getName())); info.put("piece length", new BEValue(pieceLength)); if (files == null || files.isEmpty()) { info.put("length", new BEValue(parent.length())); info.put("pieces", new BEValue(Torrent.hashFile(parent, pieceLength), SystemDefaultProperties.BYTE_ENCODING)); } else { List<BEValue> fileInfo = new LinkedList<>(); for (File file : files) { Map<String, BEValue> fileMap = new HashMap<>(); fileMap.put("length", new BEValue(file.length())); LinkedList<BEValue> filePath = new LinkedList<>(); while (file != null) { if (file.equals(parent)) { break; } filePath.addFirst(new BEValue(file.getName())); file = file.getParentFile(); } fileMap.put("path", new BEValue(filePath)); fileInfo.add(new BEValue(fileMap)); } info.put("files", new BEValue(fileInfo)); info.put("pieces", new BEValue(Torrent.hashFiles(files, pieceLength), SystemDefaultProperties.BYTE_ENCODING)); } torrent.put("info", new BEValue(info)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BEncoder.bencode(new BEValue(torrent), baos); return new Torrent(baos.toByteArray(), true); }
From source file:com.p2p.peercds.common.Torrent.java
private static void updateFileInfo(List<File> filesList, File parent, File actualParent, List<BEValue> fileInfo, List<File> files) throws UnsupportedEncodingException { for (File file : filesList) { if (!file.isDirectory()) { Map<String, BEValue> fileMap = new HashMap<String, BEValue>(); fileMap.put("length", new BEValue(file.length())); LinkedList<BEValue> filePath = new LinkedList<BEValue>(); File actual = file;//ww w. j a v a 2s .c o m while (file != null) { if (file.equals(actualParent)) { break; } filePath.addFirst(new BEValue(file.getName())); file = file.getParentFile(); } fileMap.put("path", new BEValue(filePath)); fileInfo.add(new BEValue(fileMap)); logger.info("adding file: " + actual.getName() + " to the files list"); files.add(actual); } else { logger.info("Making recursive call"); updateFileInfo(Arrays.asList(file.listFiles(Constants.hiddenFilesFilter)), file, actualParent, fileInfo, files); } } }
From source file:com.projity.script.object.TimeIntervals.java
public static int generateWindows(int scale, long ref, long start, long end, int winCount, LinkedList<TimeWindow> windows) { TimeWindow win, lastWin = null;//www . j av a2s. co m if (winCount > 0) { for (int i = 0; i <= winCount; i++) { win = generateWindow(ref, scale, 1); //if (win.getS()>end) return i; if (lastWin != null) { lastWin.setE(win.getS()); windows.add(lastWin); } ref = win.getE(); lastWin = win; } } else { for (int i = 0; i >= winCount; i--) { win = generateWindow(ref, scale, -1); //if (win.getE()<start) return i; if (lastWin != null) { lastWin.setS(win.getE()); windows.addFirst(lastWin); } ref = win.getS(); lastWin = win; } } return winCount; }
From source file:com.norconex.commons.lang.file.FileUtil.java
/** * Returns the specified number of lines starting from the beginning * of a text file, using the given encoding. * @param file the file to read lines from * @param encoding the file encoding/*from w w w . ja v a 2s . c o m*/ * @param numberOfLinesToRead the number of lines to read * @param stripBlankLines whether to return blank lines or not * @param filter InputStream filter * @return array of file lines * @throws IOException i/o problem */ public static String[] head(File file, String encoding, final int numberOfLinesToRead, boolean stripBlankLines, IInputStreamFilter filter) throws IOException { assertFile(file); assertNumOfLinesToRead(numberOfLinesToRead); LinkedList<String> lines = new LinkedList<String>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); int remainingLinesToRead = numberOfLinesToRead; String line = StringUtils.EMPTY; while (line != null && remainingLinesToRead-- > 0) { line = reader.readLine(); if (!stripBlankLines || StringUtils.isNotBlank(line)) { if (filter != null && filter.accept(line)) { lines.addFirst(line); } else { remainingLinesToRead++; } } else { remainingLinesToRead++; } } reader.close(); return lines.toArray(ArrayUtils.EMPTY_STRING_ARRAY); }
From source file:com.espertech.esper.view.ViewServiceHelper.java
/** * Add merge views for any views in the chain requiring a merge (group view). * Appends to the list of view specifications passed in one ore more * new view specifications that represent merge views. * Merge views have the same parameter list as the (group) view they merge data for. * @param specifications is a list of view definitions defining the chain of views. * @throws ViewProcessingException indicating that the view chain configuration is invalid *//*from w ww . j a va 2s .com*/ protected static void addMergeViews(List<ViewSpec> specifications) throws ViewProcessingException { if (log.isDebugEnabled()) { log.debug(".addMergeViews Incoming specifications=" + Arrays.toString(specifications.toArray())); } // A grouping view requires a merge view and cannot be last since it would not group sub-views if (specifications.size() > 0) { ViewSpec lastView = specifications.get(specifications.size() - 1); ViewEnum viewEnum = ViewEnum.forName(lastView.getObjectNamespace(), lastView.getObjectName()); if ((viewEnum != null) && (viewEnum.getMergeView() != null)) { throw new ViewProcessingException("Invalid use of the '" + lastView.getObjectNamespace() + ":" + lastView.getObjectName() + "' view, the view requires one or more child views to group, or consider using the group-by clause"); } } LinkedList<ViewSpec> mergeViewSpecs = new LinkedList<ViewSpec>(); for (ViewSpec spec : specifications) { ViewEnum viewEnum = ViewEnum.forName(spec.getObjectNamespace(), spec.getObjectName()); if (viewEnum == null) { continue; } if (viewEnum.getMergeView() == null) { continue; } // The merge view gets the same parameters as the view that requires the merge ViewSpec mergeViewSpec = new ViewSpec(viewEnum.getMergeView().getNamespace(), viewEnum.getMergeView().getName(), spec.getObjectParameters()); // The merge views are added to the beginning of the list. // This enables group views to stagger ie. marketdata.group("symbol").group("feed").xxx.merge(...).merge(...) mergeViewSpecs.addFirst(mergeViewSpec); } specifications.addAll(mergeViewSpecs); if (log.isDebugEnabled()) { log.debug(".addMergeViews Outgoing specifications=" + Arrays.toString(specifications.toArray())); } }
From source file:syndeticlogic.memento.LfuStrategy.java
@Override public void revalueNode(Cache.CacheNode node) { assert node != null && node instanceof LfuNode; LfuNode n = (LfuNode) node;// w w w. jav a 2s . c om LinkedListNode lln = n.lfuNode; LinkedList currBucket = lru(n.numUsages); LinkedList nextBucket = lru(++n.numUsages); currBucket.remove(lln); n.lfuNode = nextBucket.addFirst(lln.getValue()); }
From source file:org.tinygroup.jspengine.runtime.JspFactoryImpl.java
private void internalReleasePageContext(PageContext pc) { pc.release();/* w w w . j a va 2s . c o m*/ if (USE_POOL && (pc instanceof PageContextImpl)) { LinkedList<PageContext> pcPool = (LinkedList<PageContext>) pool.get(); pcPool.addFirst(pc); } }