List of usage examples for com.google.common.collect Lists reverse
@CheckReturnValue public static <T> List<T> reverse(List<T> list)
From source file:com.google.jimfs.FileSystemView.java
/** * Gets the {@linkplain Path#toRealPath(LinkOption...) real path} to the file located by the * given path./*from w ww .j a v a 2 s.c om*/ */ public JimfsPath toRealPath(JimfsPath path, PathService pathService, Set<? super LinkOption> options) throws IOException { checkNotNull(path); checkNotNull(options); store.readLock().lock(); try { DirectoryEntry entry = lookUp(path, options).requireExists(path); List<Name> names = new ArrayList<>(); names.add(entry.name()); while (!entry.file().isRootDirectory()) { entry = entry.directory().entryInParent(); names.add(entry.name()); } // names are ordered last to first in the list, so get the reverse view List<Name> reversed = Lists.reverse(names); Name root = reversed.remove(0); return pathService.createPath(root, reversed); } finally { store.readLock().unlock(); } }
From source file:com.facebook.buck.jvm.java.abi.InnerClassesTable.java
public void reportInnerClassReferences(ClassVisitor visitor) { List<TypeElement> enclosingClasses = new ArrayList<>(); List<TypeElement> memberClasses = new ArrayList<>(); ElementKind elementKind = topElement.getKind(); if (elementKind.isClass() || elementKind.isInterface()) { TypeElement walker = (TypeElement) topElement; while (walker.getNestingKind() == NestingKind.MEMBER) { enclosingClasses.add(walker); walker = (TypeElement) walker.getEnclosingElement(); }/*from w w w. j ava 2s . c o m*/ } ElementScanner8<Void, Void> elementScanner = new ElementScanner8<Void, Void>() { @Override public Void visitPackage(PackageElement e, Void aVoid) { addTypeReferences(e.getAnnotationMirrors()); // If we're being asked to report inner class references of a package, it really means // we're being asked to report inner class references of package-info.java; i.e., just // the package annotations. We therefore return without chaining to super to avoid // recursing into enclosed elements. return null; } @Override public Void visitType(TypeElement e, Void aVoid) { if (e != topElement && !memberClasses.contains(e)) { memberClasses.add(e); return null; } addTypeReferences(e); return super.visitType(e, aVoid); } }; elementScanner.scan(topElement); Set<TypeElement> reported = new HashSet<>(); for (TypeElement element : Lists.reverse(enclosingClasses)) { if (reported.add(element)) { visitor.visitInnerClass(descriptorFactory.getInternalName(element), descriptorFactory.getInternalName((TypeElement) element.getEnclosingElement()), element.getSimpleName().toString(), accessFlagsUtils.getAccessFlags(element) & ~Opcodes.ACC_SUPER); } } for (TypeElement element : Lists.reverse(memberClasses)) { if (reported.add(element)) { visitor.visitInnerClass(descriptorFactory.getInternalName(element), descriptorFactory.getInternalName((TypeElement) element.getEnclosingElement()), element.getSimpleName().toString(), accessFlagsUtils.getAccessFlags(element) & ~Opcodes.ACC_SUPER); } } referencesToInners.stream().filter(reported::add) .sorted(Comparator.comparing(e -> e.getQualifiedName().toString())).forEach(element -> { visitor.visitInnerClass(descriptorFactory.getInternalName(element), descriptorFactory.getInternalName((TypeElement) element.getEnclosingElement()), element.getSimpleName().toString(), accessFlagsUtils.getAccessFlags(element) & ~Opcodes.ACC_SUPER); }); }
From source file:co.cask.cdap.logging.read.StandaloneLogReader.java
@Override public void getLogPrev(final LoggingContext loggingContext, final long fromOffset, final int maxEvents, final Filter filter, final Callback callback) { executor.submit(new Runnable() { @Override/* w w w. ja v a 2 s . c om*/ public void run() { callback.init(); try { Filter logFilter = new AndFilter( ImmutableList.of(LoggingContextHelper.createFilter(loggingContext), filter)); SortedMap<Long, Location> sortedFiles = ImmutableSortedMap.copyOf( fileMetaDataManager.listFiles(loggingContext), Collections.<Long>reverseOrder()); if (sortedFiles.isEmpty()) { return; } long fromTimeMs = fromOffset >= 0 ? fromOffset - 1 : System.currentTimeMillis(); List<Location> tailFiles = Lists.newArrayListWithExpectedSize(sortedFiles.size()); for (Map.Entry<Long, Location> entry : sortedFiles.entrySet()) { if (entry.getKey() <= fromTimeMs) { tailFiles.add(entry.getValue()); } } List<Collection<LogEvent>> logSegments = Lists.newLinkedList(); AvroFileLogReader logReader = new AvroFileLogReader(schema); int count = 0; for (Location file : tailFiles) { Collection<LogEvent> events = logReader.readLogPrev(file, logFilter, fromTimeMs, maxEvents - count); logSegments.add(events); count += events.size(); if (count >= maxEvents) { break; } } for (LogEvent event : Iterables.concat(Lists.reverse(logSegments))) { callback.handle(event); } } catch (Throwable e) { LOG.error("Got exception: ", e); throw Throwables.propagate(e); } finally { callback.close(); } } }); }
From source file:com.searchcode.app.util.LoggerWrapper.java
public synchronized List<String> getSevereLogs() { List<String> values = new ArrayList<>(); try {//ww w .j a v a 2 s . com values = new ArrayList(this.severeRecentCache); values = Lists.reverse(values); } catch (ArrayIndexOutOfBoundsException ignored) { } return values; }
From source file:org.openscada.configurator.GenericMasterConfiguration.java
public void addSecurityRules(final Rules rules) { int priority = 1000; for (final Rule rule : Lists.reverse(rules.getRules())) { final RuleEncoder encoder = RuleEncoder.findEncoder(rule); if (encoder != null) { encoder.encodeRule(this, priority += 100); }/*ww w .j av a 2 s.c o m*/ } }
From source file:io.spikex.filter.internal.FiltersConfig.java
private void buildChains(final YamlResource resource) { m_chains.clear();/* w ww .jav a2 s.c o m*/ List<YamlDocument> documents = resource.getData(); if (documents != null && !documents.isEmpty()) { YamlDocument conf = documents.get(0); List<Map> chains = conf.getList(CONF_KEY_CHAINS, new ArrayList()); for (Map chainMap : chains) { String name = (String) chainMap.get(CONF_KEY_CHAIN); Preconditions.checkNotNull(name, "Missing chain"); logger().info("Found chain: {}", name); ChainDef chain = new ChainDef(name); String chainInputAddress = ""; String chainOutputAddress = ""; { List<Map> filters = (List) chainMap.get(CONF_KEY_FILTERS); for (Map filterMap : filters) { String alias = (String) filterMap.get(CONF_KEY_FILTER); logger().info("Filter map: {}", filterMap); if (filterMap.containsKey(ALIAS_INPUT_ADDRESS)) { alias = ALIAS_INPUT_ADDRESS; } if (filterMap.containsKey(ALIAS_OUTPUT_ADDRESS)) { alias = ALIAS_OUTPUT_ADDRESS; } Preconditions.checkNotNull(alias, "Missing alias"); // // Handle filter configurations // switch (alias) { case ALIAS_INPUT_ADDRESS: chainInputAddress = (String) filterMap.get(ALIAS_INPUT_ADDRESS); break; case ALIAS_OUTPUT_ADDRESS: chainOutputAddress = (String) filterMap.get(ALIAS_OUTPUT_ADDRESS); break; default: FilterDef filter = findFilterCopy(name, alias); Preconditions.checkNotNull(filter, "Could not find matching filter definition: " + alias); Map config = (Map) filterMap.get(CONF_KEY_CONFIG); config.put(CONF_KEY_CHAIN_NAME, name); filter.setConfig(config); // // worker, multi-threaded and instances // if (filterMap.containsKey(CONF_KEY_WORKER)) { filter.setWorker((Boolean) filterMap.get(CONF_KEY_WORKER)); } if (filterMap.containsKey(CONF_KEY_MULTI_THREADED)) { filter.setMultiThreaded((Boolean) filterMap.get(CONF_KEY_MULTI_THREADED)); } if (filterMap.containsKey(CONF_KEY_INSTANCES)) { filter.setInstances((Integer) filterMap.get(CONF_KEY_INSTANCES)); } chain.addFilter(filter); break; } } } { // // Set the output address of each filter // String outputAddress = ""; List<FilterDef> filters = chain.getFilters(); for (FilterDef filter : Lists.reverse(filters)) { if (!Strings.isNullOrEmpty(outputAddress)) { filter.setOutputAddress(outputAddress); } outputAddress = filter.getInputAddress(); } } // // Redirect input/output // if (!Strings.isNullOrEmpty(chainInputAddress)) { chain.setInputAddress(chainInputAddress); } if (!Strings.isNullOrEmpty(chainOutputAddress)) { chain.setOutputAddress(chainOutputAddress); } m_chains.add(chain); } } }
From source file:org.caleydo.view.tourguide.stratomex.s.AddWizardElementFactory.java
/** * @param state/*from w ww . ja v a 2s . co m*/ * @param hideEmpty * @param addStratifications */ private static void addStartTransition(StateMachineImpl state, String stateID, boolean hideEmpty) { IState target = state.get(stateID); List<ITransition> transitions = state.getTransitions(target); if (transitions.isEmpty()) return; String reason = "Unknown"; for (ITransition t : Lists.reverse(transitions)) { if (t.isEnabled()) { reason = null; break; } reason = t.getDisabledReason(); } if (reason == null || !hideEmpty) state.addTransition(state.getCurrent(), new SimpleTransition(target, target.getLabel(), reason)); }
From source file:edu.isi.karma.modeling.research.approach1.RankedModel.java
private List<Coherence> computeCoherence() { if (model == null || model.edgeSet().size() == 0) return null; List<Coherence> coherence = new ArrayList<Coherence>(); List<String> patternIds = new ArrayList<String>(); HashMap<String, HashSet<String>> patternToLinks = new HashMap<String, HashSet<String>>(); HashMap<String, Integer> patternToFrequency = new HashMap<String, Integer>(); for (Link e : model.edgeSet()) for (String s : e.getPatternIds()) { if (!patternIds.contains(s)) patternIds.add(s);// w w w . j a va 2 s.c om patternToFrequency.put(s, 1); HashSet<String> links = patternToLinks.get(s); if (links == null) { links = new HashSet<String>(); patternToLinks.put(s, links); } links.add(e.getId()); } int size1, size2, size3; String p1, p2; for (int i = 0; i < patternIds.size() - 1; i++) { p1 = patternIds.get(i); if (!patternToLinks.containsKey(p1)) continue; size1 = patternToLinks.get(p1).size(); for (int j = i + 1; j < patternIds.size(); j++) { p2 = patternIds.get(j); if (!patternToLinks.containsKey(p1)) continue; if (!patternToLinks.containsKey(p2)) continue; size2 = patternToLinks.get(p2).size(); Set<String> shared = Sets.intersection(patternToLinks.get(p1), patternToLinks.get(p2)); if (shared == null) continue; size3 = shared.size(); if (size3 < size2 && size3 < size1) continue; else if (size3 == size1 && size3 < size2) { patternToLinks.remove(p1); patternToFrequency.remove(p1); } else if (size3 == size2 && size3 < size1) { patternToLinks.remove(p2); patternToFrequency.remove(p2); } else if (size3 == size1 && size3 == size2) { Integer count = patternToFrequency.get(p1); patternToFrequency.put(p1, count + 1); patternToLinks.remove(p2); patternToFrequency.remove(p2); } } } for (Entry<String, HashSet<String>> entry : patternToLinks.entrySet()) { Coherence c = new Coherence(entry.getValue().size(), patternToFrequency.get(entry.getKey()).intValue()); coherence.add(c); } Collections.sort(coherence); coherence = Lists.reverse(coherence); return coherence; }
From source file:org.kuali.kpme.tklm.time.approval.web.TimeApprovalWSAction.java
public ActionForward getTimeSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { TimeApprovalActionForm taaf = (TimeApprovalActionForm) form; TimesheetDocument td = TkServiceLocator.getTimesheetService().getTimesheetDocument(taaf.getDocumentId()); TimeSummary ts = td.getTimeSummary(); //TimeSummary ts = (TimeSummary)TkServiceLocator.getTimeSummaryService().getTimeSummaryForDocument(taaf.getDocumentId()); List<Assignment> assignments = td.getAllAssignments(); List<String> assignmentKeys = new ArrayList<String>(); for (Assignment assignment : assignments) { assignmentKeys.add(assignment.getAssignmentKey()); }//from w w w . j a v a2 s . com List<TimeBlock> timeBlocks = td.getTimeBlocks(); List<LeaveBlock> leaveBlocks = LmServiceLocator.getLeaveBlockService().getLeaveBlocksForTimeCalendar( td.getPrincipalId(), td.getAsOfDate(), td.getDocEndDate(), assignmentKeys); Map<String, String> aMap = ActionFormUtils.buildAssignmentStyleClassMap(timeBlocks, leaveBlocks); // set css classes for each assignment row for (EarnGroupSection earnGroupSection : ts.getSections()) { for (EarnCodeSection section : earnGroupSection.getEarnCodeSections()) { for (AssignmentRow assignRow : section.getAssignmentsRows()) { String assignmentCssStyle = MapUtils.getString(aMap, assignRow.getAssignmentKey()); assignRow.setCssClass(assignmentCssStyle); for (AssignmentColumn assignmentColumn : assignRow.getAssignmentColumns().values()) { assignmentColumn.setCssClass(assignmentCssStyle); } } } } //reverse sections for javascripts $parent.after (always inserting directly after parent element, which reverses order) ts.setSections(Lists.reverse(ts.getSections())); taaf.setOutputString(ts.toJsonString()); return mapping.findForward("ws"); }
From source file:io.prestosql.sql.gen.BytecodeUtils.java
public static BytecodeNode generateInvocation(Scope scope, String name, ScalarFunctionImplementation function, Optional<BytecodeNode> instance, List<BytecodeNode> arguments, CallSiteBinder binder) { LabelNode end = new LabelNode("end"); BytecodeBlock block = new BytecodeBlock().setDescription("invoke " + name); List<Class<?>> stackTypes = new ArrayList<>(); if (function.getInstanceFactory().isPresent()) { checkArgument(instance.isPresent()); }//from w ww . j a v a2s . co m // Index of current parameter in the MethodHandle int currentParameterIndex = 0; // Index of parameter (without @IsNull) in Presto function int realParameterIndex = 0; // Go through all the choices in the function and then pick the best one List<ScalarImplementationChoice> choices = function.getAllChoices(); ScalarImplementationChoice bestChoice = null; for (ScalarImplementationChoice currentChoice : choices) { boolean isValid = true; for (int i = 0; i < arguments.size(); i++) { if (currentChoice.getArgumentProperty(i).getArgumentType() != VALUE_TYPE) { continue; } if (!(arguments.get(i) instanceof InputReferenceNode) && currentChoice.getArgumentProperty(i) .getNullConvention() == NullConvention.BLOCK_AND_POSITION) { isValid = false; break; } } if (isValid) { bestChoice = currentChoice; } } checkState(bestChoice != null, "None of the scalar function implementation choices are valid"); Binding binding = binder.bind(bestChoice.getMethodHandle()); MethodType methodType = binding.getType(); Class<?> returnType = methodType.returnType(); Class<?> unboxedReturnType = Primitives.unwrap(returnType); boolean boundInstance = false; while (currentParameterIndex < methodType.parameterArray().length) { Class<?> type = methodType.parameterArray()[currentParameterIndex]; stackTypes.add(type); if (bestChoice.getInstanceFactory().isPresent() && !boundInstance) { checkState(type.equals(bestChoice.getInstanceFactory().get().type().returnType()), "Mismatched type for instance parameter"); block.append(instance.get()); boundInstance = true; } else if (type == ConnectorSession.class) { block.append(scope.getVariable("session")); } else { ArgumentProperty argumentProperty = bestChoice.getArgumentProperty(realParameterIndex); switch (argumentProperty.getArgumentType()) { case VALUE_TYPE: // Apply null convention for value type argument switch (argumentProperty.getNullConvention()) { case RETURN_NULL_ON_NULL: block.append(arguments.get(realParameterIndex)); checkArgument(!Primitives.isWrapperType(type), "Non-nullable argument must not be primitive wrapper type"); block.append(ifWasNullPopAndGoto(scope, end, unboxedReturnType, Lists.reverse(stackTypes))); break; case USE_NULL_FLAG: block.append(arguments.get(realParameterIndex)); block.append(scope.getVariable("wasNull")); block.append(scope.getVariable("wasNull").set(constantFalse())); stackTypes.add(boolean.class); currentParameterIndex++; break; case USE_BOXED_TYPE: block.append(arguments.get(realParameterIndex)); block.append(boxPrimitiveIfNecessary(scope, type)); block.append(scope.getVariable("wasNull").set(constantFalse())); break; case BLOCK_AND_POSITION: InputReferenceNode inputReferenceNode = (InputReferenceNode) arguments .get(realParameterIndex); block.append(inputReferenceNode.produceBlockAndPosition()); stackTypes.add(int.class); currentParameterIndex++; break; default: throw new UnsupportedOperationException( format("Unsupported null convention: %s", argumentProperty.getNullConvention())); } break; case FUNCTION_TYPE: block.append(arguments.get(realParameterIndex)); break; default: throw new UnsupportedOperationException( format("Unsupported argument type: %s", argumentProperty.getArgumentType())); } realParameterIndex++; } currentParameterIndex++; } block.append(invoke(binding, name)); if (function.isNullable()) { block.append(unboxPrimitiveIfNecessary(scope, returnType)); } block.visitLabel(end); return block; }