List of usage examples for java.util LinkedList get
public E get(int index)
From source file:uk.ac.horizon.ubihelper.service.PeerManager.java
private synchronized void srvDiscoveryComplete(DnsClient dc, InetAddress src) { // copy peers in case of delete ArrayList<PeerRequestInfo> peers2 = new ArrayList<PeerRequestInfo>(); peers2.addAll(peerRequests);//from ww w.j av a2s .c om for (int i = 0; i < peers2.size(); i++) { PeerRequestInfo pi = peers2.get(i); if (pi.state == PeerRequestState.STATE_SRV_DISCOVERY && pi.src.equals(src)) { LinkedList<DnsProtocol.RR> as = dc.getAnswers(); if (as.size() == 0) { pi.state = PeerRequestState.STATE_SRV_DISCOVERY_FAILED; updatePeer(pi); } else { try { DnsProtocol.SrvData srv = DnsProtocol.srvFromData(as.get(0).rdata); pi.state = PeerRequestState.STATE_SRV_FOUND; pi.port = srv.port; if (!srv.target.equals(src.getHostAddress())) { Log.w(TAG, "SRV returned different IP: " + srv.target + " vs " + src.getHostAddress()); } updatePeer(pi); } catch (IOException e) { Log.w(TAG, "Error parsing SRV data: " + e.getMessage()); pi.state = PeerRequestState.STATE_SRV_DISCOVERY_FAILED; updatePeer(pi); } } } } }
From source file:report.mainReport.java
public static String createstopsInfos(Connection c, Statement s, String dvId, int irang, LinkedList pList) { boolean flag; boolean first; ResultSet rs = null;// w ww. j a v a 2 s .c om String stopsInfos = ""; String accountID = ""; String deviceID = ""; String deviceIDlast = ""; Double latitude = 0.0; Double longitude = 0.0; Timestamp dateEV; Timestamp dateEVfirst, timestamp = null; String temps = ""; String temps2 = ""; String datem; int vitesse = 0; int tmps, nbstop = 0; int nb = 0, nblecture = 0; int indexlast = 0; double speedlast = -1; boolean havenext = false; String request = ""; formatSymbols.setDecimalSeparator('.'); DecimalFormat dec = new DecimalFormat("#00.000000", formatSymbols); nbrarret = 0; //stopsInfos[3]=Array(Array(Array(-18.94387,47.50355,20151208065907,"",null,0),Array(-18.93862,47.50042,70152,"00-00-00 00:03:20",70512,0) LinkedList<Events> pListemp = new LinkedList<Events>(); for (int i = 0; i < pList.size(); i++) { Events evt = (Events) pList.get(i); if (evt.getDeviceID().equals(dvId)) { if (!(speedlast == 0 && evt.getSpeed() == 0)) { pListemp.add(new Events(evt.getAccountID(), evt.DeviceID, evt.getLatitude(), evt.getLongitude(), evt.getSpeed(), evt.getDateEvt(), evt.getOdometerKM(), evt.getOdometerOffsetKM(), (int) evt.getStatusCode(), (int) evt.getSpeedMax(), evt.getHeading())); } speedlast = evt.getSpeed(); } } for (int i = 0; i < pListemp.size(); i++) { Events evt = (Events) pListemp.get(i); if (i == 0) { stopsInfos = "Array(" + dec.format(evt.getLatitude()) + ", " + dec.format(evt.getLongitude()) + ", " + new SimpleDateFormat("yyyyMMddHHmmss").format(evt.getDateEvt()) + ", \"\", null, " + evt.getSpeed() + ")"; accountID = evt.getAccountID(); speedlast = evt.getSpeed(); indexlast = i; nbstop++; request = request + "loc=" + dec.format(evt.getLatitude()) + "," + dec.format(evt.getLongitude()); } else { if (evt.getSpeed() < 1.) { tmps = getDuration(pListemp, dvId, i); if (i == (indexlast + 1) && speedlast < 1) { } else { if (tmps > ARRET_MAX) { temps = "\"00-00-00 " + getDurationString(tmps) + "\""; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(evt.getDateEvt().getTime()); cal.add(Calendar.SECOND, tmps); timestamp = new Timestamp(cal.getTime().getTime()); temps2 = new SimpleDateFormat("HHmmss").format(timestamp); datem = new SimpleDateFormat("HHmmss").format(evt.getDateEvt()); stopsInfos = stopsInfos + ", Array(" + dec.format(evt.getLatitude()) + ", " + dec.format(evt.getLongitude()) + ", " + datem + ", " + temps + ", " + temps2 + ", " + evt.getSpeed() + ")"; nbstop++; nbrarret++; indexlast = i; //request = request + "loc=" + dec.format(evt.getLatitude()) + "," + dec.format(evt.getLongitude()); } } } speedlast = evt.getSpeed(); } } if (pListemp.size() > 2 && indexlast != (pListemp.size() - 1)) { Events evt = (Events) pListemp.get(pListemp.size() - 1); stopsInfos = stopsInfos + ", Array(" + dec.format(evt.getLatitude()) + ", " + dec.format(evt.getLongitude()) + ", " + new SimpleDateFormat("yyyyMMddHHmmss").format(evt.getDateEvt()) + ", \"\", null, " + evt.getSpeed() + ")"; //request = request + "loc=" + dec.format(evt.getLatitude()) + "," + dec.format(evt.getLongitude()); } //System.out.println("stopsInfos Dernier points: "+stopsInfos); if (nbstop > 0) { /*if (nbstop > 1){ Events evt = (Events) pList.get(indexlast); stopsInfos = stopsInfos + ", Array(" + dec.format(evt.getLatitude())+", "+ dec.format(evt.getLongitude())+", "+new SimpleDateFormat("yyyyMMddHHmmss").format(evt.getDateEvt())+", \"\", null, "+evt.getSpeed()+")"; nbstop++; }*/ stopsInfos = stopsInfos + ")"; String sql = "SELECT accountID, deviceID, vehicleMake, vehicleModel, licensePlate FROM Device where accountID='" + accountID + "' and deviceID='" + dvId + "';"; try { rs = s.executeQuery(sql); if (rs.next()) { String vehicleMake = rs.getObject("vehicleMake") != null ? rs.getString("vehicleMake") : null; String vehicleModel = rs.getObject("vehicleModel") != null ? rs.getString("vehicleModel") : null; String licensePlate = rs.getObject("licensePlate") != null ? rs.getString("licensePlate") : null; stopsInfos = "Array(Array(" + stopsInfos + ", \"" + licensePlate + " " + vehicleModel + "\")"; } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("stopsInfos: "+nbstop); //System.out.println(stopsInfos); } else { stopsInfos = null; System.out.println(deviceIDlast + " AUCUN stopsInfos"); } return stopsInfos; }
From source file:org.trnltk.apps.morphology.contextless.parser.CachingMorphologicParserApp.java
@App("Parse sample TBMM Journal w/o bulk parse") public void parseTbmmJournal_b0241h_noBulkParse() throws Exception { final File tokenizedFile = new File("core/src/test/resources/tokenizer/tbmm_b0241h_tokenized.txt"); final List<String> lines = Files.readLines(tokenizedFile, Charsets.UTF_8); final LinkedList<String> words = new LinkedList<String>(); final HashSet<String> uniqueWords = new HashSet<String>(); for (String line : lines) { final ArrayList<String> strings = Lists .newArrayList(Splitter.on(" ").trimResults().omitEmptyStrings().split(line)); words.addAll(strings);/*from ww w .j a v a 2 s . c om*/ uniqueWords.addAll(strings); } final int initialL1CacheSize = uniqueWords.size(); final int maxL1CacheSize = initialL1CacheSize; final MorphologicParserCache l1Cache = new LRUMorphologicParserCache(NUMBER_OF_THREADS, initialL1CacheSize, maxL1CacheSize); final ExecutorService pool = Executors.newFixedThreadPool(NUMBER_OF_THREADS); final MorphologicParser[] parsers = new MorphologicParser[NUMBER_OF_THREADS]; for (int i = 0; i < parsers.length; i++) { parsers[i] = new CachingMorphologicParser(new TwoLevelMorphologicParserCache(BULK_SIZE, l1Cache), contextlessMorphologicParser, true); } final StopWatch stopWatch = new StopWatch(); stopWatch.start(); for (int i = 0; i < words.size(); i++) { final MorphologicParser parser = parsers[i % NUMBER_OF_THREADS]; final String word = words.get(i); final int wordIndex = i; pool.execute(new SingleParseCommand(parser, word, wordIndex, false)); } pool.shutdown(); while (!pool.isTerminated()) { System.out.println("Waiting pool to be terminated!"); pool.awaitTermination(500, TimeUnit.MILLISECONDS); } stopWatch.stop(); System.out.println("Total time :" + stopWatch.toString()); System.out.println("Nr of tokens : " + words.size()); System.out.println("Avg time : " + (stopWatch.getTime() * 1.0d) / (words.size() * 1.0d) + " ms"); }
From source file:edu.cuny.cat.stat.HistoricalReport.java
/** * /* w ww . j a v a2 s . c om*/ * @param shouts * @param index * @param length * @return a string that prints out the specified shouts in the list in a * pretty way. */ protected String prettyString(final LinkedList<Shout> shouts, final int index, final int length) { int last = shouts.size(); if (length >= 0) { last = index + length; } String s = ""; for (int i = index; i < last; i++) { if (s.length() == 0) { s += "["; } else { s += ", "; } s += prettyString(shouts.get(i)); } if (s.length() == 0) { s += "["; } s += "]"; return s; }
From source file:org.openscience.cdk.applications.taverna.basicutilities.ChartTool.java
/** * Creates a residue plot.//from w w w .j a v a2 s.c om * * @param yValues * @param header * @param xAxis * @param yAxis * @param seriesNames * @return */ public JFreeChart createResiduePlot(List<Double[]> yValues, String header, String xAxis, String yAxis, List<String> seriesNames) { LinkedList<XYLineAnnotation> lines = new LinkedList<XYLineAnnotation>(); DefaultXYDataset xyDataSet = new DefaultXYDataset(); for (int j = 0; j < yValues.size(); j++) { XYSeries series = new XYSeries(seriesNames.get(j)); for (int i = 0; i < yValues.get(j).length; i++) { series.add(i + 1, yValues.get(j)[i]); float dash[] = { 10.0f }; BasicStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f); XYLineAnnotation annotation = new XYLineAnnotation(i + 1, 0, i + 1, yValues.get(j)[i], stroke, Color.BLUE); lines.add(annotation); } xyDataSet.addSeries(seriesNames.get(j), series.toArray()); } JFreeChart chart = ChartFactory.createScatterPlot(header, xAxis, yAxis, xyDataSet, PlotOrientation.VERTICAL, true, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setNoDataMessage("NO DATA"); plot.setDomainZeroBaselineVisible(true); plot.setRangeZeroBaselineVisible(true); for (int i = 0; i < lines.size(); i++) { plot.addAnnotation(lines.get(i)); } XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setSeriesOutlinePaint(0, Color.black); renderer.setUseOutlinePaint(true); NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis(); domainAxis.setAutoRangeIncludesZero(false); domainAxis.setTickMarkInsideLength(2.0f); domainAxis.setTickMarkOutsideLength(0.0f); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setTickMarkInsideLength(2.0f); rangeAxis.setTickMarkOutsideLength(0.0f); return chart; }
From source file:com.swordlord.gozer.databinding.DataBindingManager.java
/** * TODO need to merge with getResolvedRow(LinkedList<DataBindingElement> * elements, String strTableName, DataRowBase rowFather). Today there is too * many risk. We need a better Parser and a lot of JUnit Tests. * /*from ww w . j a va 2 s . c om*/ * @param elements * @param strTableName * @param rowFather * @return */ public DataRowBase[] getResolvedRows(LinkedList<DataBindingElement> elements, String strTableName, DataRowBase rowFather) { if ((elements == null) || (elements.size() == 0)) { LOG.error("elements is empty"); } ArrayList<DataRowBase> dataRowBaseLst = new ArrayList<DataRowBase>(); boolean rowFound = false; for (DataBindingElement element : elements) { if (!element.isField()) { String strPathElement = element.getPathElement(); // ignore the same level if (strPathElement.compareToIgnoreCase(strTableName) != 0) { Object property = rowFather.getProperty(strPathElement); if (property == null) { return new DataRowBase[0]; } else { if (property instanceof DataRowBase) { rowFather = (DataRowBase) property; rowFound = true; } else if (property instanceof ToManyList) { ToManyList list = (ToManyList) property; if (list.size() > 0) { if (elements.get(elements.size() - 2).equals(element)) { // Last element without field name if (list.getValueDirectly() == null) { try { rowFather = (DataRowBase) list.get(element.getRowNumber()); rowFound = true; } catch (Exception e) { e.printStackTrace(); return new DataRowBase[0]; } dataRowBaseLst.add(rowFather); return dataRowBaseLst.toArray(new DataRowBase[dataRowBaseLst.size()]); } else { List<DataRowBase> lst = (List) list.getValueDirectly(); return lst.toArray(new DataRowBase[lst.size()]); } } else { rowFather = (DataRowBase) list.get(element.getRowNumber()); rowFound = true; } } } } // this is some nice side effect where we just loop as long // as we // are not at the right level } } } if (rowFound) { dataRowBaseLst.add(rowFather); return dataRowBaseLst.toArray(new DataRowBase[dataRowBaseLst.size()]); } else { return new DataRowBase[0]; } }
From source file:com.oltpbenchmark.benchmarks.auctionmark.AuctionMarkProfile.java
/** * //from ww w. ja v a 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:ome.services.blitz.repo.ManagedRepositoryI.java
/** * Checks for the top-level user directory restriction before calling * {@link PublicRepositoryI#makeCheckedDirs(LinkedList<CheckedPath>, boolean, Current)} *//*from w ww. j av a2 s. c o m*/ @Override protected void makeCheckedDirs(final LinkedList<CheckedPath> paths, boolean parents, Session s, ServiceFactory sf, SqlAction sql, ome.system.EventContext effectiveEventContext) throws ServerError { final IAdmin adminService = sf.getAdminService(); final EventContext ec = IceMapper.convert(effectiveEventContext); final String expanded = expandTemplate(template, ec); final FsFile rootOwnedPath = splitPath(expanded).getKey(); final List<CheckedPath> pathsToFix = new ArrayList<CheckedPath>(); final List<CheckedPath> pathsForRoot; /* if running as root then the paths must be root-owned */ final long rootId = adminService.getSecurityRoles().getRootId(); if (adminService.getEventContext().getCurrentUserId() == rootId) { pathsForRoot = ImmutableList.copyOf(paths); } else { pathsForRoot = ImmutableList.of(); } for (int i = 0; i < paths.size(); i++) { CheckedPath checked = paths.get(i); if (checked.isRoot) { // This shouldn't happen but just in case. throw new ResourceError(null, null, "Cannot re-create root!"); } /* check that the path is consistent with the root-owned template path directories */ if (!isConsistentPrefixes(rootOwnedPath.getComponents(), checked.fsFile.getComponents())) { throw new omero.ValidationException(null, null, "cannot create directory \"" + checked.fsFile + "\" with template path's root-owned \"" + rootOwnedPath + "\""); } pathsToFix.add(checked); } super.makeCheckedDirs(paths, parents, s, sf, sql, effectiveEventContext); /* ensure that root segment of the template path is wholly root-owned */ if (!pathsForRoot.isEmpty()) { final Experimenter rootUser = sf.getQueryService().find(Experimenter.class, rootId); final IUpdate updateService = sf.getUpdateService(); for (final CheckedPath pathForRoot : pathsForRoot) { final OriginalFile directory = repositoryDao.findRepoFile(sf, sql, getRepoUuid(), pathForRoot, null); if (directory.getDetails().getOwner().getId() != rootId) { directory.getDetails().setOwner(rootUser); updateService.saveObject(directory); } } } // Now that we know that these are the right directories for // the current user, we make sure that the directories are in // the user group. repositoryDao.createOrFixUserDir(getRepoUuid(), pathsToFix, s, sf, sql); }
From source file:com.ibm.jaggr.core.impl.deps.DepTree.java
/** * Object constructor. Attempts to de-serialize the cached dependency lists * from disk and then validates the dependency lists based on last-modified * dates, looking for any new or removed files. If the cached dependency * list data cannot be de-serialized, new lists are constructed. Once the * dependency lists have been validated, the list data is serialized back * out to disk./*from w ww . jav a2 s . c o m*/ * * @param paths * Collection of URIs which specify the target resources * to be scanned for javascript files. * @param aggregator * The servlet instance for this object * @param stamp * timestamp associated with external override/customization * resources that are check on every server restart * @param clean * If true, then the dependency lists are generated from scratch * rather than by de-serializing and then validating the cached * dependency lists. * @param validateDeps * If true, then validate existing cached dependencies using * file last-modified times. * @throws IOException */ public DepTree(Collection<URI> paths, IAggregator aggregator, long stamp, boolean clean, boolean validateDeps) throws IOException { final String sourceMethod = "<ctor>"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(DepTree.class.getName(), sourceMethod, new Object[] { paths, aggregator, stamp, clean, validateDeps }); } this.stamp = stamp; IConfig config = aggregator.getConfig(); rawConfig = config.toString(); cacheBust = AggregatorUtil.getCacheBust(aggregator); File cacheDir = new File(aggregator.getWorkingDirectory(), DEPCACHE_DIRNAME); File cacheFile = new File(cacheDir, CACHE_FILE); /* * The de-serialized dependency map. If we have a cached dependency map, * then it will be validated against the last-modified dates of the * current files and only the files that have changed will need to be * re-parsed to update the dependency lists. */ DepTree cached = null; if (!clean) { // If we're not starting clean, try to de-serialize the map from // cache try { ObjectInputStream is = new ObjectInputStream(new FileInputStream(cacheFile)); try { if (isTraceLogging) { log.finer("Attempting to read cached dependencies from " + cacheFile.toString()); //$NON-NLS-1$ } cached = (DepTree) is.readObject(); } finally { try { is.close(); } catch (Exception ignore) { } } } catch (FileNotFoundException e) { /* * Not an error. Just means that the cache file hasn't been * written yet or else it's been deleted. */ if (log.isLoggable(Level.INFO)) log.log(Level.INFO, Messages.DepTree_1); } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); } } // If the cacheBust config param has changed, then do a clean build // of the dependencies. if (cached != null) { if (stamp == 0) { // no init stamp provided. Preserve the cached one. stamp = cached.stamp; } if (stamp > cached.stamp) { // init stamp has been updated. Validate dependencies. validateDeps = true; } if (!StringUtils.equals(cacheBust, cached.cacheBust)) { if (isTraceLogging) { log.finer("Current cacheBust = " + cacheBust + ", cached cacheBust = " + cached.cacheBust); //$NON-NLS-1$//$NON-NLS-2$ } if (log.isLoggable(Level.INFO)) { log.info(Messages.DepTree_2); } cached = null; } if (cached != null && !StringUtils.equals(rawConfig, cached.rawConfig)) { if (isTraceLogging) { log.finer("Current config = " + rawConfig); //$NON-NLS-1$ log.finer("Cached config = " + cached.rawConfig); //$NON-NLS-1$ } validateDeps = true; } } /* * If we de-serialized a previously saved dependency map, then go with * that. */ if (cached != null && !validateDeps && !clean) { depMap = cached.depMap; fromCache = true; return; } else if (isTraceLogging) { log.finer("Building/validating deps: cached = " + cached + ", validateDeps = " + validateDeps //$NON-NLS-1$//$NON-NLS-2$ + ", clean = " + clean); //$NON-NLS-1$ } // Initialize the dependency map depMap = new ConcurrentHashMap<URI, DepTreeNode>(); // This can take a while, so print something to the console String msg = MessageFormat.format(Messages.DepTree_3, new Object[] { aggregator.getName() }); ConsoleService cs = new ConsoleService(); cs.println(msg); if (log.isLoggable(Level.INFO)) { log.info(msg); } // Make sure that all the paths are unique and orthogonal paths = DepUtils.removeRedundantPaths(paths); /* * Create the thread pools, one for the tree builders and one for the * parsers. Since a tree builder thread will wait for all the outstanding * parser threads started by that builder to complete, we need to use two * independent thread pools to guard against the possibility of deadlock * caused by all the threads in the pool being consumed by tree builders * and leaving none available to service the parsers. */ final ThreadGroup treeBuilderTG = new ThreadGroup(TREEBUILDER_TGNAME), parserTG = new ThreadGroup(JSPARSER_TGNAME); ExecutorService treeBuilderExc = Executors.newFixedThreadPool(10, new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(treeBuilderTG, r, MessageFormat.format(THREADNAME, new Object[] { treeBuilderTG.getName(), treeBuilderTG.activeCount() })); } }), parserExc = Executors.newFixedThreadPool(20, new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(parserTG, r, MessageFormat.format(THREADNAME, new Object[] { parserTG.getName(), parserTG.activeCount() })); } }); // Counter to keep track of number of tree builder threads started AtomicInteger treeBuilderCount = new AtomicInteger(0); // The completion services for the thread pools final CompletionService<URI> parserCs = new ExecutorCompletionService<URI>(parserExc); CompletionService<DepTreeBuilder.Result> treeBuilderCs = new ExecutorCompletionService<DepTreeBuilder.Result>( treeBuilderExc); Set<String> nonJSExtensions = Collections.unmodifiableSet(getNonJSExtensions(aggregator)); // Start the tree builder threads to process the paths for (final URI path : paths) { /* * Create or get from cache the root node for this path and * add it to the new map. */ DepTreeNode root = new DepTreeNode("", path); //$NON-NLS-1$ DepTreeNode cachedNode = null; if (cached != null) { cachedNode = cached.depMap.get(path); if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_4, new Object[] { path })); } } else { if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_5, new Object[] { path })); } } depMap.put(path, root); treeBuilderCount.incrementAndGet(); treeBuilderCs.submit(new DepTreeBuilder(aggregator, parserCs, path, root, cachedNode, nonJSExtensions)); } // List of parser exceptions LinkedList<Exception> parserExceptions = new LinkedList<Exception>(); /* * Pull the completed tree builder tasks from the completion queue until * all the paths have been processed */ while (treeBuilderCount.decrementAndGet() >= 0) { try { DepTreeBuilder.Result result = treeBuilderCs.take().get(); if (log.isLoggable(Level.INFO)) { log.info(MessageFormat.format(Messages.DepTree_6, new Object[] { result.parseCount, result.dirName })); } } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) log.log(Level.SEVERE, e.getMessage(), e); parserExceptions.add(e); } } // shutdown the thread pools now that we're done with them parserExc.shutdown(); treeBuilderExc.shutdown(); // If parser exceptions occurred, then rethrow the first one if (parserExceptions.size() > 0) { throw new RuntimeException(parserExceptions.get(0)); } // Prune dead nodes (folder nodes with no children) for (Map.Entry<URI, DepTreeNode> entry : depMap.entrySet()) { entry.getValue().prune(); } /* * Make sure the cache directory exists before we try to serialize the * dependency map. */ if (!cacheDir.exists()) if (!cacheDir.mkdirs()) { throw new IOException( MessageFormat.format(Messages.DepTree_0, new Object[] { cacheDir.getAbsolutePath() })); } // Serialize the map to the cache directory ObjectOutputStream os; os = new ObjectOutputStream(new FileOutputStream(cacheFile)); try { if (isTraceLogging) { log.finer("Writing cached dependencies to " + cacheFile.toString()); //$NON-NLS-1$ } os.writeObject(this); } finally { try { os.close(); } catch (Exception ignore) { } } msg = MessageFormat.format(Messages.DepTree_7, new Object[] { aggregator.getName() }); // Output that we're done. cs.println(msg); if (log.isLoggable(Level.INFO)) { log.info(msg); } if (isTraceLogging) { log.exiting(DepTree.class.getName(), sourceMethod); } }
From source file:app.android.kopper.selectmaparea.MapActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { try {/*from w w w. j a va2s. co m*/ super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); final GoogleMap map = mapFragment.getMap(); //todo: map is null when no internet connection ?? if (map != null) { map.getUiSettings().setCompassEnabled(false); map.getUiSettings().setZoomControlsEnabled(true); map.getUiSettings().setIndoorLevelPickerEnabled(false); map.getUiSettings().setRotateGesturesEnabled(false); map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { createMarker(latLng, map); } }); findViewById(R.id.done_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LinkedList<LatLng> positions = getPositions(); if (positions.size() != 2) Toast.makeText(getApplicationContext(), getString(R.string.error_two_points), Toast.LENGTH_SHORT).show(); else { Intent data = getOrCreateIntent(); data.putExtra(SELECTED_POSITIONS, positions); Serializable nextPage = data .getSerializableExtra(MapActivity.class.getCanonicalName() + "-next"); if (nextPage != null) { try { Intent ii = new Intent(getApplicationContext(), (Class<?>) nextPage); ii.putExtras(data); startActivityForResult(ii, WIZARD_RESULT_CODE); } catch (Exception e) { LogUtil.e(e); } } else { setResult(RESULT_OK, data); finish(); } } } }); LinkedList<LatLng> positions = (LinkedList<LatLng>) getLastCustomNonConfigurationInstance(); if (positions != null) { for (int a = 0; a < positions.size(); a++) { createMarker(positions.get(a), map); } } else { Intent intent = getOrCreateIntent(); Bundle extras = intent.getExtras(); List<LatLng> selectedPoints = (List<LatLng>) extras.get(SELECTED_POSITIONS); if (selectedPoints != null) for (LatLng pos : selectedPoints) createMarker(pos, map); map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition arg0) { map.setOnCameraChangeListener(null); if (markers.size() == 2) map.moveCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds( markers.get(0).getPosition(), markers.get(1).getPosition()), 40)); if (markers.size() == 1) map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 10)); } }); } } else { //no map ((TextView) findViewById(R.id.message)).setText(getString(R.string.error_map_load)); } } catch (Exception e) { LogUtil.e(e); } }