List of usage examples for java.util Collections reverse
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void reverse(List<?> list)
This method runs in linear time.
From source file:istata.service.StataService.java
/** * produce a list with possible sidebar suggestions for the current context * /*from w w w.j a v a2s . co m*/ * @param filter * @param pos * @param from * @param to * @return */ public List<ContentLine> suggest(String filter, int pos, int from, int to) { LinkedHashSet<ContentLine> res = new LinkedHashSet<ContentLine>(); ArrayList<ContentLine> rescmd = new ArrayList<ContentLine>(); { int i = 0; for (ContentLine cl : cmdRepository.findAll()) { if (cl.getContent().startsWith(filter)) { ContentLine srl = new ContentLine(); Map<String, Object> model = new HashMap<String, Object>(); model.put("cmd", cl); model.put("from", from); model.put("to", to); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "items/cmd.vm", "UTF-8", model); srl.setContent(text); srl.setLine(i++); rescmd.add(srl); } } } Collections.reverse(rescmd); res.addAll(rescmd.subList(0, Math.min(10, rescmd.size()))); List<ContentLine> out = new ArrayList<ContentLine>(); try { IStata stata = stataFactory.getInstance(); /* * get files */ Collection<ContentLine> filesNames = filteredFiles(filter, pos, from, to); res.addAll(filesNames); /* * get VARS, should be a mothod call probably */ // current token StringBuilder token = new StringBuilder(""); StringBuilder rest = new StringBuilder(filter); int p = (pos == -1 || pos > filter.length()) ? filter.length() : pos; char ch = 'x'; while (p > 0 && (CharUtils.isAsciiAlphanumeric(ch = filter.charAt(p - 1)) || ch == '_')) { token.insert(0, ch); rest.deleteCharAt(p - 1); p--; } // remove rest of potential token while (rest.length() > 0 && p > 0 && p < rest.length() && (CharUtils.isAsciiAlphanumeric(rest.charAt(p)) || rest.charAt(p) == '_')) { rest.deleteCharAt(p); } String t = token.toString(); List<StataVar> list = new ArrayList<StataVar>(); List<StataVar> listfull = stata.getVars("", false); if (t.length() > 0) { for (StataVar sv : listfull) { if (sv.getName().startsWith(t)) { list.add(sv); } } } else { list = listfull; } for (int i = 0; i < list.size(); i++) { ContentLine srl = new ContentLine(); srl.setLine(i + 100); String vname = list.get(i).getName(); String cl = new StringBuilder(rest).insert(p, " ").insert(p, vname).toString(); try { String cc = URLEncoder.encode(cl, "UTF-8"); Map<String, Object> model = new HashMap<String, Object>(); model.put("var", vname); model.put("repl", cc); model.put("focuspos", p + 1 + vname.length()); model.put("from", from); model.put("to", to); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "items/var.vm", "UTF-8", model); srl.setContent(text); res.add(srl); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (StataNotRunningException e) { ContentLine srl = new ContentLine(); srl.setLine(1); srl.setContent( "<div class='list-group-item sidebaritem error' >" + "Stata not running, you can try to start " + "an instance by clicking " + "<a target='_blank' href='/start'>here</a>" + "</div>"); out.add(srl); } catch (StataBusyException e1) { ContentLine srl = new ContentLine(); srl.setLine(1); srl.setContent("<div class='list-group-item sidebaritem error' >" + "Stata appears to by busy or not running, you can try to " + "start a new instance by clicking " + "<a target='_blank' href='/start'>here</a> " + "or wait for the current job to complete</div>"); out.add(srl); } out.addAll(res); return out; }
From source file:es.pode.catalogadorWeb.presentacion.taxonomias.TaxonomiasControllerImpl.java
/** * @see es.pode.catalogadorBasico.presentacion.taxonomias.TaxonomiasController#consultaRuta(org.apache.struts.action.ActionMapping, * es.pode.catalogadorBasico.presentacion.taxonomias.ConsultaRutaForm, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *//*from w ww . jav a2 s.com*/ public final void consultaRuta(ActionMapping mapping, es.pode.catalogadorWeb.presentacion.taxonomias.ConsultaRutaForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { String idioma = request.getParameter("idioma"); if (idioma == null) { idioma = ((Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE)) .getLanguage(); } String nomTaxonomia = request.getParameter("nomTaxonomia"); String id = request.getParameter("id"); String vocabName = request.getParameter("vocabName"); if (form.getIdioma() != null && !form.getIdioma().equals("")) idioma = form.getIdioma(); form.setId(id); form.setIdioma(idioma); form.setVocabName(vocabName); form.setNomTaxonomia(nomTaxonomia); List rutaPadrevo = Arrays .asList(this.getSrvTaxonomiaService().obtenerTaxonPath(id, nomTaxonomia, idioma)); Collections.reverse(rutaPadrevo); form.setRutaPadrevo(rutaPadrevo); TaxonVO[] taxVO = this.getSrvTaxonomiaService().obtenerNodos(id, nomTaxonomia, idioma); form.setTaxonesvoAsArray(taxVO); } catch (org.acegisecurity.AccessDeniedException ad) { logger.error("Error de Acceso " + ad); throw new java.lang.Exception("taxonomias", ad); } catch (Exception e) { logger.error("Error en catalogadorWeb, Taxonomias, metodo consultaRutas " + e); throw new java.lang.Exception("taxonomias", e); } }
From source file:com.sun.labs.aura.fb.DataManager.java
public ItemInfo[] getComparisonCloud(ItemInfo[] tagCloud1, ItemInfo[] tagCloud2) { ///* w w w. ja v a 2s .co m*/ // Make two WordClouds, then ask Aura to explain how they overlap WordCloud one = new WordCloud(); for (ItemInfo i : tagCloud1) { one.add(i.getItemName(), i.getScore()); } WordCloud two = new WordCloud(); for (ItemInfo i : tagCloud2) { two.add(i.getItemName(), i.getScore()); } // // Get the overlap set List<Scored<String>> result = new ArrayList<Scored<String>>(); try { result = mdb.getDataStore().explainSimilarity(one, two, new SimilarityConfig(CLOUD_SIZE)); } catch (AuraException e) { logger.log(Level.WARNING, "Failed while talking to Aura", e); } catch (RemoteException e) { logger.log(Level.WARNING, "Communication disruption", e); } // // Normalize the overlaps cloud ItemInfo[] overlap = Util.normalize(result); // // Now assemble the results for display as a cloud Set<String> commonNames = getNameSet(overlap); List<ItemInfo> infos = new ArrayList<ItemInfo>(); List<ItemInfo> head = Util.negative(Util.getTopUniqueInfo(tagCloud1, commonNames, CLOUD_SIZE / 2)); infos.addAll(head); overlap = ItemInfo.shuffle(overlap); for (ItemInfo ii : overlap) { infos.add(ii); } List<ItemInfo> tail = Util.negative(Util.getTopUniqueInfo(tagCloud2, commonNames, CLOUD_SIZE / 2)); Collections.reverse(tail); infos.addAll(tail); return infos.toArray(new ItemInfo[0]); }
From source file:de.blizzy.backup.backup.BackupRun.java
private void removeOldDatabaseBackups() { File outputFolder = new File(settings.getOutputFolder()); File dbBackupRootFolder = new File(outputFolder, "$db-backup"); //$NON-NLS-1$ if (dbBackupRootFolder.isDirectory()) { List<Long> timestamps = new ArrayList<>(); for (File f : dbBackupRootFolder.listFiles()) { if (f.isDirectory()) { timestamps.add(Long.valueOf(f.getName())); }//from w w w. j a v a 2 s. com } if (timestamps.size() > 19) { Collections.sort(timestamps); Collections.reverse(timestamps); for (int i = 19; i < timestamps.size(); i++) { long timestamp = timestamps.get(i).longValue(); File folder = new File(dbBackupRootFolder, String.valueOf(timestamp)); try { FileUtils.forceDelete(folder); } catch (IOException e) { BackupPlugin.getDefault().logError("error while deleting old database backup folder: " + //$NON-NLS-1$ folder.getAbsolutePath(), e); fireBackupErrorOccurred(e, BackupErrorEvent.Severity.WARNING); } } } } }
From source file:de.thischwa.pmcms.model.domain.PoInfo.java
/** * Generate all breadcrumbs objects for persitentPojo (bottom-up). * /*www.j a v a 2 s . co m*/ * @param po */ public static List<APoormansObject<?>> getBreadcrumbs(final APoormansObject<?> po) { List<APoormansObject<?>> list = new ArrayList<APoormansObject<?>>(); if (po != null) { APoormansObject<?> temppo = po; list.add(temppo); while (temppo.getParent() != null) { temppo = (APoormansObject<?>) temppo.getParent(); list.add(temppo); } } Collections.reverse(list); return list; }
From source file:it.sayservice.platform.smartplanner.cache.annotated.AnnotatedReader.java
private AnnotatedTimetable read(String agencyId, String fileName) throws Exception { System.out.println("Reading: " + fileName); List<String[]> lines = readCSV(fileName); int index = fileName.lastIndexOf(System.getProperty("file.separator")); String routeId = fileName.substring(index + 1); index = routeId.lastIndexOf("-"); index = routeId.indexOf("-"); routeId = routeId.substring(0, index).replace("_", ""); AnnotatedTimetable aTimetable = new AnnotatedTimetable(); List<String> tripIds = Lists.newArrayList(); List<String> serviceIds = Lists.newArrayList(); List<String> stopsIds = Lists.newArrayList(); List<String> stopNames = Lists.newArrayList(); List<Integer> invisibles = Lists.newArrayList(); List<List<String>> cols = Lists.newArrayList(); List<String> frequenza = Lists.newArrayList(); List<String> linea = Lists.newArrayList(); List<String> routeIds = Lists.newArrayList(); List<Integer> toSkip = Lists.newArrayList(); boolean stopStarted = false; int maxLine = 0; for (String[] line : lines) { maxLine = Math.max(maxLine, line.length); }/*ww w. ja v a2 s . com*/ for (String[] line : lines) { if (line.length < 2) { continue; } if (stopStarted) { boolean skip = true; for (int i = 2; i < line.length; i++) { if (!line[i].isEmpty()) { skip = false; break; } } if (skip) { System.err.println("Skipping empty line: " + line[0]); continue; } } String c0 = line[0]; String c1 = line[1]; String c2 = line[2]; if ("Descr.breve:".equals(c0)) { aTimetable.setShortDescription(c2); } if ("Descr.lunga:".equals(c0)) { aTimetable.setLongDescription(c2); } if ("Validit:".equals(c0)) { aTimetable.setValidity(c2); } if ("Orario:".equals(c0)) { aTimetable.setSchedule(c2); } if ("Linea:".equals(c0)) { for (int i = 2; i < line.length; i++) { linea.add(line[i]); } } if ("Frequenza:".equals(c0)) { for (int i = 2; i < line.length; i++) { frequenza.add(line[i]); } } if ("smartplanner route_id".equals(c0)) { for (int i = 2; i < line.length; i++) { routeIds.add(line[i]); } } if (stopStarted) { if (c0.startsWith("*")) { invisibles.add(1); } else { invisibles.add(0); } if (c0.isEmpty()) { System.err.println("Empty line in " + fileName); break; } stopNames.add(c0.replace("*", "")); stopsIds.add(c1 + "_" + agencyId); for (int i = 0; i < cols.size(); i++) { String time = line[i + 2].replace("-", "").replace(".", ":"); cols.get(i).add(time); } } if ("gtfs trip_id".equals(c0)) { for (int i = 2; i < line.length; i++) { if (line[i].isEmpty()) { toSkip.add(i - 2); } tripIds.add(line[i]); cols.add(new ArrayList<String>()); } } if ("service_id".equals(c0)) { for (int i = 2; i < line.length; i++) { if (line[i].contains("$")) { System.out.println("warn " + line[i]); } serviceIds.add(line[i]); } } if ("stops".equals(c0)) { stopStarted = true; } } for (int i = linea.size(); i < cols.size(); i++) { linea.add(""); } for (int i = frequenza.size(); i < cols.size(); i++) { frequenza.add(""); } Collections.reverse(toSkip); for (int i : toSkip) { tripIds.remove(i); serviceIds.remove(i); cols.remove(i); routeIds.remove(i); frequenza.remove(i); linea.remove(i); } int keepN = tripIds.size(); serviceIds = serviceIds.subList(0, keepN); cols = cols.subList(0, keepN); routeIds = routeIds.subList(0, keepN); frequenza = frequenza.subList(0, keepN); linea = linea.subList(0, keepN); List<AnnotatedColumn> aCols = Lists.newArrayList(); for (String tripId : tripIds) { int tripIndex = tripIds.indexOf(tripId); AnnotatedColumn aCol = new AnnotatedColumn(); aCol.setTripId(tripId); aCol.setSymbolicRouteId(routeId); aCol.setRouteId(routeIds.get(tripIndex)); aCol.setServiceId(serviceIds.get(tripIndex)); List<String> times = Lists.newArrayList(); int i = 0; for (String stopId : stopsIds) { String time = cols.get(tripIndex).get(i); time = fixTimes(time); times.add(time); i++; } aCol.setTimes(times); aCols.add(aCol); } aTimetable.setColumns(aCols); aTimetable.setStopNames(stopNames); aTimetable.setStopIds(stopsIds); aTimetable.setInvisibles(invisibles); aTimetable.setFrequency(frequenza); aTimetable.setRouteIds(routeIds); aTimetable.setLine(linea); aTimetable.setSymbolicRouteId(routeId); boolean eq = aCols.size() == routeIds.size() && frequenza.size() == linea.size() && aCols.size() == frequenza.size(); if (!eq) { System.err.println("ERRROR: different column sizes."); } return aTimetable; }
From source file:org.springframework.cloud.config.server.environment.EnvironmentController.java
private Map<String, Object> convertToProperties(Environment profiles) { // Map of unique keys containing full map of properties for each unique // key/*w ww. j a va 2 s . co m*/ Map<String, Map<String, Object>> map = new LinkedHashMap<>(); List<PropertySource> sources = new ArrayList<>(profiles.getPropertySources()); Collections.reverse(sources); Map<String, Object> combinedMap = new TreeMap<>(); for (PropertySource source : sources) { @SuppressWarnings("unchecked") Map<String, Object> value = (Map<String, Object>) source.getSource(); for (String key : value.keySet()) { if (!key.contains("[")) { // Not an array, add unique key to the map combinedMap.put(key, value.get(key)); } else { // An existing array might have already been added to the property map // of an unequal size to the current array. Replace the array key in // the current map. key = key.substring(0, key.indexOf("[")); Map<String, Object> filtered = new TreeMap<>(); for (String index : value.keySet()) { if (index.startsWith(key + "[")) { filtered.put(index, value.get(index)); } } map.put(key, filtered); } } } // Combine all unique keys for array values into the combined map for (Entry<String, Map<String, Object>> entry : map.entrySet()) { combinedMap.putAll(entry.getValue()); } postProcessProperties(combinedMap); return combinedMap; }
From source file:com.moviejukebox.scanner.MovieNFOScanner.java
/** * Search for the NFO file in the library structure * * @param movie The movie bean to locate the NFO for * @return A List structure of all the relevant NFO files *///w w w. j a v a 2s .c o m public static List<File> locateNFOs(Movie movie) { List<File> nfoFiles = new ArrayList<>(); GenericFileFilter fFilter; File currentDir = movie.getFirstFile().getFile(); if (currentDir == null) { return nfoFiles; } String baseFileName = currentDir.getName(); String pathFileName = currentDir.getAbsolutePath(); // Get the folder if it's a BluRay disk if (pathFileName.toUpperCase().contains(File.separator + "BDMV" + File.separator)) { currentDir = new File(FileTools.getParentFolder(currentDir)); baseFileName = currentDir.getName(); pathFileName = currentDir.getAbsolutePath(); } if (ARCHIVE_SCAN_RAR && pathFileName.toLowerCase().contains(".rar")) { currentDir = new File(FileTools.getParentFolder(currentDir)); baseFileName = currentDir.getName(); pathFileName = currentDir.getAbsolutePath(); } // If "pathFileName" is a file then strip the extension from the file. if (currentDir.isFile()) { pathFileName = FilenameUtils.removeExtension(pathFileName); baseFileName = FilenameUtils.removeExtension(baseFileName); } else { // *** First step is to check for VIDEO_TS // The movie is a directory, which indicates that this is a VIDEO_TS file // So, we should search for the file moviename.nfo in the sub-directory checkNFO(nfoFiles, pathFileName + pathFileName.substring(pathFileName.lastIndexOf(File.separator))); } // TV Show specific scanning if (movie.isTVShow()) { String nfoFilename; // Check for the "tvshow.nfo" filename in the parent directory if (movie.getFile().getParentFile().getParent() != null) { nfoFilename = StringTools.appendToPath(movie.getFile().getParentFile().getParent(), XBMC_TV_NFO_NAME); checkNFO(nfoFiles, nfoFilename); } // Check for the "tvshow.nfo" filename in the current directory nfoFilename = StringTools.appendToPath(movie.getFile().getParent(), XBMC_TV_NFO_NAME); checkNFO(nfoFiles, nfoFilename); // Check for individual episode files if (!SKIP_TV_NFO_FILES) { for (MovieFile mf : movie.getMovieFiles()) { nfoFilename = mf.getFile().getParent().toUpperCase(); if (nfoFilename.contains("BDMV")) { nfoFilename = FileTools.getParentFolder(mf.getFile()); nfoFilename = nfoFilename.substring(nfoFilename.lastIndexOf(File.separator) + 1); } else { nfoFilename = FilenameUtils.removeExtension(mf.getFile().getName()); } checkNFO(nfoFiles, StringTools.appendToPath(mf.getFile().getParent(), nfoFilename)); } } } // *** Second step is to check for the filename.nfo file // This file should be named exactly the same as the video file with an extension of "nfo" or "NFO" // E.G. C:\Movies\Bladerunner.720p.avi => Bladerunner.720p.nfo checkNFO(nfoFiles, pathFileName); if (isValidString(NFO_DIR)) { // *** Next step if we still haven't found the nfo file is to // search the NFO directory as specified in the moviejukebox.properties file String sNFOPath = FileTools.getDirPathWithSeparator(movie.getLibraryPath()) + NFO_DIR; checkNFO(nfoFiles, sNFOPath + File.separator + baseFileName); } // *** Next step is to check for a directory wide NFO file. if (ACCEPT_ALL_NFO) { /* * If any NFO file in this directory will do, then we search for all we can find * * NOTE: for scanning efficiency, it is better to first search for specific filenames before we start doing * filtered "listfiles" which scans all the files; * * A movie collection with all moviefiles in one directory could take tremendously longer if for each * moviefile found, the entire directory must be listed!! * * Therefore, we first check for specific filenames (cfr. old behaviour) before doing an entire scan of the * directory -- and only if the user has decided to accept any NFO file! */ // Check the current directory fFilter = new GenericFileFilter(NFO_EXT_REGEX); checkRNFO(nfoFiles, currentDir.getParentFile(), fFilter); // Also check the directory above, for the case where movies are in a multi-part named directory (CD/PART/DISK/Etc.) Matcher allNfoMatch = PART_PATTERN.matcher(currentDir.getAbsolutePath()); if (allNfoMatch.find()) { LOG.debug("Found multi-part directory, checking parent directory for NFOs"); checkRNFO(nfoFiles, currentDir.getParentFile().getParentFile(), fFilter); } } else { // This file should be named the same as the directory that it is in // E.G. C:\TV\Chuck\Season 1\Season 1.nfo // We search up through all containing directories up to the library root // Check the current directory for the video filename fFilter = new GenericFileFilter("(?i)" + movie.getBaseFilename() + NFO_EXT_REGEX); checkRNFO(nfoFiles, currentDir, fFilter); } // Recurse through the directories to the library root looking for NFO files String libraryRootPath = new File(movie.getLibraryPath()).getAbsolutePath(); while (currentDir != null && !currentDir.getAbsolutePath().equals(libraryRootPath)) { //fFilter.setPattern("(?i)" + currentDir.getName() + nfoExtRegex); //checkRNFO(nfos, currentDir, fFilter); currentDir = currentDir.getParentFile(); if (currentDir != null) { final String path = currentDir.getPath(); // Path is not empty & is not the root if (!path.isEmpty() && !path.endsWith(File.separator)) { checkNFO(nfoFiles, appendToPath(path, currentDir.getName())); } } } // we added the most specific ones first, and we want to parse those the last, // so nfo files in sub-directories can override values in directories above. Collections.reverse(nfoFiles); return nfoFiles; }
From source file:com.github.jknack.handlebars.internal.Parser.java
public Template parse(final InputBuffer input) throws IOException { try {//from w ww . j a v a2 s . c o m ParseRunner<Object> runner = new SafeReportingParseRunner(template()) { @Override protected void resetValueStack() { startDelimiter = startDelimiterBack; endDelimiter = endDelimiterBack; hasTag = null; line.setLength(0); noffset = 0; if (rootParser) { partials.clear(); stacktraceList.clear(); } super.resetValueStack(); } }; ParsingResult<Object> result = runner.run(input); if (result.hasErrors()) { ParseError error = result.parseErrors.get(0); Collections.reverse(stacktraceList); HandlebarsError hbsError = ErrorFormatter.printParseError(filename, error, noffset, stacktraceList); throw new HandlebarsException(hbsError); } Node node = (Node) result.resultValue; TemplateList sequence = node.sequence; stripSpace(node); if (sequence.size() == 1) { return sequence.iterator().next(); } return sequence; } catch (ParserRuntimeException ex) { Throwable cause = ex.getCause() == null ? ex : ex.getCause(); if (cause instanceof HandlebarsException) { throw (HandlebarsException) cause; } HandlebarsException hex = new HandlebarsException(cause.getMessage(), cause); hex.setStackTrace(ex.getStackTrace()); throw hex; } finally { endDelimiter = null; endDelimiterBack = null; filename = null; handlebars = null; hasTag = null; line = null; nodeLine.clear(); nodeLine = null; if (rootParser) { partials.clear(); stacktraceList.clear(); } partials = null; stacktraceList = null; startDelimiter = null; } }