List of usage examples for java.util LinkedList toArray
@SuppressWarnings("unchecked") public <T> T[] toArray(T[] a)
From source file:model.utilities.stats.collectors.PeriodicMarketObserver.java
private void outputToFile() { Preconditions.checkState(writer != null); LinkedList<String> row = new LinkedList<>(); row.add(Double.toString(getLastPriceObserved())); row.add(Double.toString(getLastQuantityTradedObserved())); row.add(Double.toString(getLastQuantityProducedObserved())); row.add(Double.toString(getLastQuantityConsumedObserved())); row.add(Double.toString(getLastDayObserved())); row.add(Double.toString(//from w ww. j a v a 2 s. com market.getObservationRecordedThisDay(MarketDataType.DEMAND_GAP, days.get(days.size() - 1)))); row.add(Double.toString( market.getObservationRecordedThisDay(MarketDataType.SUPPLY_GAP, days.get(days.size() - 1)))); writer.writeNext(row.toArray(new String[row.size()])); try { writer.flush(); } catch (IOException e) { } }
From source file:org.j2free.invoker.InvokerFilter.java
/** * Locks to prevent request processing while mapping is added. * * Finds all classes annotated with ServletConfig and maps the class to * the url specified in the annotation. Wildcard mapping are allowed in * the form of *.extension or /some/path/* * * @param context an active ServletContext *///from w w w.j av a 2 s . co m public void load(final ServletContext context) { try { write.lock(); LinkedList<URL> urlList = new LinkedList<URL>(); urlList.addAll(Arrays.asList(ClasspathUrlFinder.findResourceBases(EMPTY))); urlList.addAll(Arrays.asList(WarUrlFinder.findWebInfLibClasspaths(context))); URL[] urls = new URL[urlList.size()]; urls = urlList.toArray(urls); AnnotationDB annoDB = new AnnotationDB(); annoDB.setScanClassAnnotations(true); annoDB.setScanFieldAnnotations(false); annoDB.setScanMethodAnnotations(false); annoDB.setScanParameterAnnotations(false); annoDB.scanArchives(urls); HashMap<String, Set<String>> annotationIndex = (HashMap<String, Set<String>>) annoDB .getAnnotationIndex(); if (annotationIndex != null && !annotationIndex.isEmpty()) { //----------------------------------------------------------- // Look for any classes annotated with @ServletConfig Set<String> classNames = annotationIndex.get(ServletConfig.class.getName()); if (classNames != null) { for (String c : classNames) { try { final Class<? extends HttpServlet> klass = (Class<? extends HttpServlet>) Class .forName(c); if (klass.isAnnotationPresent(ServletConfig.class)) { final ServletConfig config = (ServletConfig) klass .getAnnotation(ServletConfig.class); // If the config specifies String mapppings... if (config.mappings() != null) { for (String url : config.mappings()) { // Leave the asterisk, we'll add it when matching... //if (url.matches("(^\\*[^*]*?)|([^*]*?/\\*$)")) // url = url.replace("*", EMPTY); url = url.toLowerCase(); // all comparisons are lower-case if (urlMap.putIfAbsent(url, klass) == null) { if (log.isDebugEnabled()) log.debug("Mapping servlet " + klass.getName() + " to path " + url); } else log.error("Unable to map servlet " + klass.getName() + " to path " + url + ", path already mapped to " + urlMap.get(url).getName()); } } // If the config specifies a regex mapping... if (!empty(config.regex())) { regexMap.putIfAbsent(config.regex(), klass); if (log.isDebugEnabled()) log.debug("Mapping servlet " + klass.getName() + " to regex path " + config.regex()); } // Create an instance of the servlet and init it HttpServlet servlet = klass.newInstance(); servlet.init(new ServletConfigImpl(klass.getName(), context)); // Store a reference servletMap.put(klass, new ServletMapping(servlet, config)); } } catch (Exception e) { log.error("Error registering servlet [name=" + c + "]", e); } } } //----------------------------------------------------------- // Look for any classes annotated with @FiltersConfig classNames = annotationIndex.get(FilterConfig.class.getName()); if (classNames != null) { for (String c : classNames) { try { final Class<? extends Filter> klass = (Class<? extends Filter>) Class.forName(c); if (klass.isAnnotationPresent(FilterConfig.class)) { final FilterConfig config = (FilterConfig) klass.getAnnotation(FilterConfig.class); // Create an instance of the servlet and init it Filter filter = klass.newInstance(); filter.init(new FilterConfigImpl(klass.getName(), context)); if (log.isDebugEnabled()) log.debug("Mapping filter " + klass.getName() + " to path " + config.match()); // Store a reference filters.add(new FilterMapping(filter, config)); } } catch (Exception e) { log.error("Error registering servlet [name=" + c + "]", e); } } } } } catch (IOException e) { log.error("Error loading urlMappings", e); } finally { write.unlock(); // ALWAYS Release the configure lock } }
From source file:org.gcaldaemon.core.notifier.GmailNotifier.java
public final void run() { log.info("Gmail notifier started successfully."); try {/*from w w w . j ava2 s . c om*/ sleep(7000); } catch (Exception ignored) { return; } // Processed (displayed) mails HashSet processedMails = new HashSet(); // Polling mailbox int i; for (;;) { try { // Verify local username if (users != null) { // List active users String[] activeUsers = getActiveUsers(); boolean enabled = false; if (activeUsers != null && activeUsers.length != 0) { for (i = 0; i < activeUsers.length; i++) { enabled = isUserMatch(activeUsers[i]); if (enabled) { break; } } if (!enabled) { // Sleep for a minute log.debug("Access denied for active local users."); sleep(MINUTE); // Restart loop (verify username) continue; } } } // Get Gmail address book (or null) GmailContact[] contacts = configurator.getAddressBook(); GmailContact contact; // Load feed entries SyndEntry[] entries = FeedUtilities.getFeedEntries(FEED_URL, username, password); SyndEntry entry; HashSet newMails = new HashSet(); for (i = 0; i < entries.length; i++) { entry = entries[i]; String date = getDate(entry); String from = getFrom(entry); if (contacts != null) { for (int n = 0; n < contacts.length; n++) { contact = contacts[n]; if (from.equalsIgnoreCase(contact.email)) { from = contact.name; break; } } } String title = getTitle(entry); if (mailtermSubject != null) { if (title.equals(mailtermSubject) || title.equals("Re:" + mailtermSubject)) { // Do not display mailterm commands and responses continue; } } String summary = getSummary(entry); newMails.add(date + '\t' + from + '\t' + title + '\t' + summary); } // Remove readed mails Iterator iterator = processedMails.iterator(); Object key; while (iterator.hasNext()) { key = iterator.next(); if (!newMails.contains(key)) { iterator.remove(); } } // Look up unprocessed mails LinkedList unprocessedMails = new LinkedList(); iterator = newMails.iterator(); while (iterator.hasNext()) { key = iterator.next(); if (processedMails.contains(key)) { continue; } processedMails.add(key); unprocessedMails.addLast(key); } // Display unprocessed mails if (!unprocessedMails.isEmpty()) { String[] array = new String[unprocessedMails.size()]; unprocessedMails.toArray(array); Arrays.sort(array, String.CASE_INSENSITIVE_ORDER); window.show(array); } // Sleep sleep(pollingTimeout); } catch (InterruptedException interrupt) { // Dispose window if (window != null) { try { window.setVisible(false); } catch (Exception ignored) { } } break; } catch (Exception loadError) { log.error("Unable to load Gmail feed!", loadError); try { sleep(HOUR); } catch (Exception interrupt) { return; } } } }
From source file:org.gofleet.module.routing.RoutingMap.java
private TSPPlan[] processFile(File file, JProgressBar progressbar) { try {/*from w w w . j a va 2 s.co m*/ LinkedList<TSPPlan> res = new LinkedList<TSPPlan>(); BufferedReader br = new BufferedReader(new FileReader(file)); String line; int i = 0; TSPPlan plan = new TSPPlan(); while ((line = br.readLine()) != null) { log.trace(line); progressbar.setValue(i++); if (!line.isEmpty()) plan.addStops(line); else { res.add(plan); plan = new TSPPlan(); } } res.add(plan); return res.toArray(new TSPPlan[0]); } catch (Throwable e) { log.error("Error processing file", e); } return null; }
From source file:com.facebook.react.views.textinput.ReactTextInputManager.java
@ReactProp(name = "maxLength") public void setMaxLength(ReactEditText view, @Nullable Integer maxLength) { InputFilter[] currentFilters = view.getFilters(); InputFilter[] newFilters = EMPTY_FILTERS; if (maxLength == null) { if (currentFilters.length > 0) { LinkedList<InputFilter> list = new LinkedList<>(); for (int i = 0; i < currentFilters.length; i++) { if (!(currentFilters[i] instanceof InputFilter.LengthFilter)) { list.add(currentFilters[i]); }//ww w. j a va 2s . c o m } if (!list.isEmpty()) { newFilters = (InputFilter[]) list.toArray(new InputFilter[list.size()]); } } } else { if (currentFilters.length > 0) { newFilters = currentFilters; boolean replaced = false; for (int i = 0; i < currentFilters.length; i++) { if (currentFilters[i] instanceof InputFilter.LengthFilter) { currentFilters[i] = new InputFilter.LengthFilter(maxLength); replaced = true; } } if (!replaced) { newFilters = new InputFilter[currentFilters.length + 1]; System.arraycopy(currentFilters, 0, newFilters, 0, currentFilters.length); currentFilters[currentFilters.length] = new InputFilter.LengthFilter(maxLength); } } else { newFilters = new InputFilter[1]; newFilters[0] = new InputFilter.LengthFilter(maxLength); } } view.setFilters(newFilters); }
From source file:com.clustercontrol.composite.FacilityTreeComposite.java
/** * // w w w . j a va 2s. c o m * @param keyword ? */ public void doSearch(String keyword) { // Check and format keyword if (null == keyword) { return; } keyword = keyword.trim(); if (keyword.isEmpty()) { return; } StructuredSelection selection = (StructuredSelection) treeViewer.getSelection(); Object targetItem = selection.getFirstElement(); FacilityTreeItem result = searchItem( (FacilityTreeItem) (null != targetItem ? targetItem : treeViewer.getInput()), keyword); if (null != result) { FacilityTreeItem trace = result; LinkedList<FacilityTreeItem> pathList = new LinkedList<>(); do { pathList.addFirst(trace); trace = trace.getParent(); } while (null != trace); TreePath path = new TreePath(pathList.toArray(new FacilityTreeItem[] {})); treeViewer.setSelection(new TreeSelection(path), true); } else { MessageDialog.openInformation(this.getShell(), Messages.getString("message"), Messages.getString("search.not.found")); treeViewer.setSelection( new StructuredSelection(((FacilityTreeItem) treeViewer.getInput()).getChildren().get(0)), true); } }
From source file:org.xdi.util.EasyX509TrustManager.java
/** * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], * String authType)//w ww . j ava 2 s. c o m */ public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { if (certificates != null && LOG.isDebugEnabled()) { LOG.debug("Server certificate chain:"); for (int i = 0; i < certificates.length; i++) { LOG.debug("X509Certificate[" + i + "]=" + certificates[i]); } } if (certificates != null && (certificates.length == 1)) { certificates[0].checkValidity(); } else { List<X509Certificate> certs = new ArrayList<X509Certificate>(); if (certificates != null) { certs.addAll(Arrays.asList(certificates)); } X509Certificate certChain = certs.get(0); certs.remove(certChain); LinkedList<X509Certificate> chainList = new LinkedList<X509Certificate>(); chainList.add(certChain); Principal certIssuer = certChain.getIssuerDN(); Principal certSubject = certChain.getSubjectDN(); while (!certs.isEmpty()) { List<X509Certificate> tempcerts = new ArrayList<X509Certificate>(); tempcerts.addAll(certs); for (X509Certificate cert : tempcerts) { if (cert.getIssuerDN().equals(certSubject)) { chainList.addFirst(cert); certSubject = cert.getSubjectDN(); certs.remove(cert); continue; } if (cert.getSubjectDN().equals(certIssuer)) { chainList.addLast(cert); certIssuer = cert.getIssuerDN(); certs.remove(cert); continue; } } } standardTrustManager.checkServerTrusted(chainList.toArray(new X509Certificate[] {}), authType); } }
From source file:org.marketcetera.util.l10n.MessageComparator.java
/** * Creates a new comparator for the given meta-information. For * both parameters, the order of list elements is unimportant. * * @param srcInfo The source meta-information. * @param dstInfo The destination meta-information. *///from w w w . ja v a2 s. c om public MessageComparator(List<MessageInfo> srcInfo, List<MessageInfo> dstInfo) { // Analyze source and destination. HashMap<String, MessageInfo> srcMessages = toHashMap(srcInfo); HashMap<String, MessageInfo> dstMessages = toHashMap(dstInfo); // Compare. LinkedList<MessageInfoPair> mismatches = new LinkedList<MessageInfoPair>(); LinkedList<MessageInfo> extraSrcInfo = new LinkedList<MessageInfo>(); for (String name : srcMessages.keySet()) { MessageInfo srcMessage = srcMessages.get(name); // Message missing from destination. if (!dstMessages.containsKey(name)) { extraSrcInfo.add(srcMessage); continue; } // Message exists in both source and destination, but // parameter count differs. MessageInfo dstMessage = dstMessages.get(name); if ((srcMessage.getParamCount() != -1) && (dstMessage.getParamCount() != -1) && (srcMessage.getParamCount() != dstMessage.getParamCount())) { mismatches.add(new MessageInfoPair(srcMessage, dstMessage)); } dstMessages.remove(name); } // Retain results. mMismatches = mismatches.toArray(MessageInfoPair.EMPTY_ARRAY); mExtraSrcInfo = extraSrcInfo.toArray(MessageInfo.EMPTY_ARRAY); mExtraDstInfo = dstMessages.values().toArray(MessageInfo.EMPTY_ARRAY); }
From source file:org.sonar.plugins.javascript.lcov.LCOVCoverageSensor.java
protected void saveMeasureFromLCOVFile(SensorContext context) { LinkedList<File> lcovFiles = new LinkedList<>(); for (String reportPath : reportPaths) { String providedPath = settings.getString(reportPath); if (StringUtils.isBlank(providedPath)) { continue; }//from www. j av a2 s . c o m File lcovFile = getIOFile(fileSystem.baseDir(), providedPath); if (lcovFile.isFile()) { lcovFiles.add(lcovFile); } else { LOG.warn( "No coverage information will be saved because LCOV file cannot be found. Provided LCOV file path: {}", providedPath); LOG.warn("Provided LCOV file path: {}. Seek file with path: {}", providedPath, lcovFile.getAbsolutePath()); } } if (lcovFiles.isEmpty()) { LOG.warn("No coverage information will be saved because all LCOV files cannot be found."); return; } LOG.info("Analysing {}", lcovFiles); LCOVParser parser = LCOVParser.create(fileSystem, lcovFiles.toArray(new File[lcovFiles.size()])); Map<InputFile, CoverageMeasuresBuilder> coveredFiles = parser.coverageByFile(); for (InputFile inputFile : fileSystem.inputFiles(mainFilePredicate)) { try { CoverageMeasuresBuilder fileCoverage = coveredFiles.get(inputFile); org.sonar.api.resources.File resource = org.sonar.api.resources.File .create(inputFile.relativePath()); if (fileCoverage != null) { for (Measure measure : fileCoverage.createMeasures()) { context.saveMeasure(resource, convertMeasure(measure)); } } else { // colour all lines as not executed LOG.debug("Default value of zero will be saved for file: {}", resource.getPath()); LOG.debug( "Because: either was not present in LCOV report either was not able to retrieve associated SonarQube resource"); saveZeroValueForResource(resource, context); } } catch (Exception e) { LOG.error("Problem while calculating coverage for " + inputFile.absolutePath(), e); } } List<String> unresolvedPaths = parser.unresolvedPaths(); if (!unresolvedPaths.isEmpty()) { LOG.warn(String.format("Could not resolve %d file paths in %s, first unresolved path: %s", unresolvedPaths.size(), lcovFiles, unresolvedPaths.get(0))); } }
From source file:edu.umn.msi.tropix.common.jobqueue.impl.JobProcessorQueueImpl.java
public Status getStatus(final Ticket ticket) { initializationTracker.waitForInitialization(ticket); final LinkedList<StatusEntry> entries = new LinkedList<StatusEntry>(); final JobInfo jobInfo = jobMap.get(ticket); // jobMap.get(ticket); final QueueStage queueStage = jobInfo == null ? QueueStage.ABSENT : jobInfo.queueStage; final Status status = new Status(); status.setStage(new Stage(queueStage.getStageEnumerationValue())); if (queueStage.equals(QueueStage.RUNNING)) { final Double percentComplete = jobInfo.percentComplete; if (percentComplete != null) { final PercentComplete percentCompleteObject = new PercentComplete(); percentCompleteObject.setValue(percentComplete); entries.add(percentCompleteObject); }//from w w w .j av a 2s. c o m } if (jobInfo != null && jobInfo.cancelled) { entries.add(new WasCancelled(true)); } status.setStatusEntry(entries.toArray(new StatusEntry[entries.size()])); // If the execution queue might have more information to add to the // status allow it too. if (queueStage.equals(QueueStage.PENDING) || queueStage.equals(QueueStage.RUNNING) || queueStage.equals(QueueStage.COMPLETED) || queueStage.equals(QueueStage.FAILED)) { if (statusModifier != null) { statusModifier.extendStatus(ticket.getValue(), status); } } return status; }