List of usage examples for com.google.common.collect Lists newArrayListWithExpectedSize
@GwtCompatible(serializable = true) public static <E> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize)
From source file:de.hpi.bp2013n1.anonymizer.PrimaryKey.java
public PrimaryKey(String schema, String table, Connection database) throws SQLException { DatabaseMetaData metaData = database.getMetaData(); try (ResultSet pkResultSet = metaData.getPrimaryKeys(null, schema, table)) { if (!pkResultSet.next()) { useAllColumnsAsPrimaryKey(schema, table, database); return; }//from w ww . j a va 2s . c o m keyName = pkResultSet.getString("PK_NAME"); TreeMap<Integer, String> columns = new TreeMap<>(); do { columns.put(pkResultSet.getInt("KEY_SEQ"), pkResultSet.getString("COLUMN_NAME")); } while (pkResultSet.next()); columnNames = new ArrayList<>(columns.values()); try (PreparedStatement select = database.prepareStatement("SELECT " + Joiner.on(',').join(columnNames) + " FROM " + SQLHelper.qualifiedTableName(schema, table) + " WHERE 1 = 0")) { // only interested in metadata ResultSetMetaData selectPKMetaData = select.getMetaData(); columnTypeNames = new ArrayList<>(columnNames.size()); columnNullable = Lists.newArrayListWithExpectedSize(columnNames.size()); for (int i = 1; i <= columnNames.size(); i++) { columnTypeNames.add(selectPKMetaData.getColumnTypeName(i)); columnNullable.add(selectPKMetaData.isNullable(i) == ResultSetMetaData.columnNullable); } } } }
From source file:com.technophobia.substeps.runner.builder.ScenarioNodeBuilder.java
public OutlineScenarioNode buildOutlineScenarioNode(final Scenario scenario, Set<String> inheritedTags, int depth) { int idx = 0;//from ww w . j a va 2 s.c om List<OutlineScenarioRowNode> outlineRowNodes = Lists .newArrayListWithExpectedSize(scenario.getExampleParameters().size()); Set<String> allTags = Sets.newHashSet(); allTags.addAll(inheritedTags); if (scenario.getTags() != null) { allTags.addAll(scenario.getTags()); } // TODO pass in the example params into the outline scenarionode for (final ExampleParameter outlineParameters : scenario.getExampleParameters()) { BasicScenarioNode basicSenarioNode = buildBasicScenarioNode(scenario, outlineParameters, allTags, depth + 2); outlineRowNodes.add(new OutlineScenarioRowNode(idx++, basicSenarioNode, allTags, depth + 1)); } return new OutlineScenarioNode(scenario.getDescription(), outlineRowNodes, allTags, depth); }
From source file:org.eclipse.gemoc.moccml.constraint.fsmkernel.model.design.editor.PopupXTextEditorActionSupport.java
public void initializeActions() { final List<IHandlerActivation> handlerActivations = Lists.newArrayListWithExpectedSize(3); final IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench() .getAdapter(IHandlerService.class); final Expression expression = new ActiveShellExpression(viewer.getControl().getShell()); viewer.getControl().getShell().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { handlerService.deactivateHandlers(handlerActivations); }/*from w ww.j a v a 2s. c om*/ }); TextViewerAction action = new TextViewerAction(viewer, ITextOperationTarget.UNDO); action.setText("UNDO"); fGlobalActions.put(ITextEditorActionConstants.UNDO, action); action = new TextViewerAction(viewer, ITextOperationTarget.REDO); action.setText("REDO"); fGlobalActions.put(ITextEditorActionConstants.REDO, action); action = new TextViewerAction(viewer, ITextOperationTarget.CUT); action.setText("CUT"); fGlobalActions.put(ITextEditorActionConstants.CUT, action); action = new TextViewerAction(viewer, ITextOperationTarget.COPY); action.setText("COPY"); fGlobalActions.put(ITextEditorActionConstants.COPY, action); action = new TextViewerAction(viewer, ITextOperationTarget.PASTE); action.setText("PASTE"); fGlobalActions.put(ITextEditorActionConstants.PASTE, action); action = new TextViewerAction(viewer, ITextOperationTarget.SELECT_ALL); action.setText("SELECT_ALL"); fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); action = new TextViewerAction(viewer, ISourceViewer.CONTENTASSIST_PROPOSALS); action.setText("CONTENTASSIST_PROPOSALS"); fGlobalActions.put(ITextEditorActionConstants.CONTENT_ASSIST, action); fSelectionActions.add(ITextEditorActionConstants.CUT); fSelectionActions.add(ITextEditorActionConstants.COPY); fSelectionActions.add(ITextEditorActionConstants.PASTE); viewer.getTextWidget().addFocusListener(new FocusListener() { public void focusLost(FocusEvent e) { handlerService.deactivateHandlers(handlerActivations); } public void focusGained(FocusEvent e) { IAction action = fGlobalActions.get(ITextEditorActionConstants.REDO); handlerActivations.add(handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_REDO, new ActionHandler(action), expression)); action = fGlobalActions.get(ITextEditorActionConstants.UNDO); handlerActivations.add(handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_UNDO, new ActionHandler(action), expression)); action = fGlobalActions.get(ITextEditorActionConstants.CONTENT_ASSIST); handlerActivations .add(handlerService.activateHandler(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, new ActionHandler(action), expression)); } }); }
From source file:com.arpnetworking.tsdcore.sinks.HttpPostSink.java
/** * Create HTTP requests for each serialized data entry. The list is * guaranteed to be non-empty.// ww w. j ava 2 s. com * * @param client The http client to build the request with. * @param periodicData The <code>PeriodicData</code> to be serialized. * @return The <code>HttpRequest</code> instance to execute. */ protected Collection<Request> createRequests(final AsyncHttpClient client, final PeriodicData periodicData) { final Collection<byte[]> serializedData = serialize(periodicData); final Collection<Request> requests = Lists.newArrayListWithExpectedSize(serializedData.size()); for (final byte[] serializedDatum : serializedData) { requests.add(createRequest(client, serializedDatum)); } return requests; }
From source file:de.tuberlin.uebb.jdae.simulation.ResultStorage.java
/** * Select a view of the result set//from w ww . j a v a 2 s . c om * * @param from * the start time of the view * @param to * the end time of the view * @param step * the maximal step size between to data points in the view * @return a list of data points of this result */ public List<double[][]> select(double from, double to, final double step) { final List<double[][]> steps = Lists.newArrayListWithExpectedSize((int) ((to - from) / step)); for (double[][] r : results) { if (r[0][0] >= from) { steps.add(r); if ((from += step) >= to) { break; } } } return steps; }
From source file:org.apache.phoenix.iterate.SerialIterators.java
@Override protected void submitWork(List<List<Scan>> nestedScans, List<List<Pair<Scan, Future<PeekingResultIterator>>>> nestedFutures, final Queue<PeekingResultIterator> allIterators, int estFlattenedSize) { // Pre-populate nestedFutures lists so that we can shuffle the scans // and add the future to the right nested list. By shuffling the scans // we get better utilization of the cluster since our thread executor // will spray the scans across machines as opposed to targeting a // single one since the scans are in row key order. ExecutorService executor = context.getConnection().getQueryServices().getExecutor(); for (final List<Scan> scans : nestedScans) { Scan firstScan = scans.get(0);/* www .ja va 2 s .c om*/ Scan lastScan = scans.get(scans.size() - 1); final Scan overallScan = ScanUtil.newScan(firstScan); overallScan.setStopRow(lastScan.getStopRow()); final String tableName = tableRef.getTable().getPhysicalName().getString(); final TaskExecutionMetricsHolder taskMetrics = new TaskExecutionMetricsHolder( context.getReadMetricsQueue(), tableName); Future<PeekingResultIterator> future = executor .submit(Tracing.wrap(new JobCallable<PeekingResultIterator>() { @Override public PeekingResultIterator call() throws Exception { List<PeekingResultIterator> concatIterators = Lists .newArrayListWithExpectedSize(scans.size()); for (final Scan scan : scans) { ResultIterator scanner = new TableResultIterator(context, tableRef, scan, context.getReadMetricsQueue().allotMetric(SCAN_BYTES, tableName), ScannerCreation.DELAYED); concatIterators.add(iteratorFactory.newIterator(context, scanner, scan, tableName)); } PeekingResultIterator concatIterator = ConcatResultIterator .newIterator(concatIterators); allIterators.add(concatIterator); return concatIterator; } /** * Defines the grouping for round robin behavior. All threads spawned to process * this scan will be grouped together and time sliced with other simultaneously * executing parallel scans. */ @Override public Object getJobId() { return SerialIterators.this; } @Override public TaskExecutionMetricsHolder getTaskExecutionMetric() { return taskMetrics; } }, "Serial scanner for table: " + tableRef.getTable().getName().getString())); // Add our singleton Future which will execute serially nestedFutures.add( Collections.singletonList(new Pair<Scan, Future<PeekingResultIterator>>(overallScan, future))); } }
From source file:com.metamx.rdiclient.RdiClientImpl.java
RdiClientImpl(final RdiClientConfig config, final Serializer<T> serializer, final Lifecycle lifecycle, final HttpClient httpClient, final long retryDurationOverride) { this.config = config; this.serializer = serializer; this.lifecycle = lifecycle; this.httpClient = httpClient; this.rdiClientVersion = RdiClient.class.getPackage().getImplementationVersion(); this.postSemaphore = new Semaphore(config.getMaxConnectionCount()); this.buffer = Lists.newArrayListWithExpectedSize(config.getFlushCount()); this.retryDurationOverride = retryDurationOverride; try {/*from w w w. ja v a 2 s. c om*/ this.url = new URL(config.getRdiUrl()); } catch (MalformedURLException e) { throw new IAE(String.format("Invalid URL: %s", config.getRdiUrl())); } }
From source file:org.jetbrains.android.dom.converters.CreateMissingClassQuickFix.java
@Override public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { final PsiPackage aPackage = myPackage.getElement(); if (aPackage == null) { return;//from ww w . j a v a 2 s . c o m } final AndroidFacet facet = AndroidFacet.getInstance(myModule); if (facet == null) { return; } final List<IdeaSourceProvider> providerList = IdeaSourceProvider.getCurrentSourceProviders(facet); final List<VirtualFile> javaDirectories = Lists.newArrayList(); for (IdeaSourceProvider provider : providerList) { javaDirectories.addAll(provider.getJavaDirectories()); } final PsiDirectory[] directories = aPackage.getDirectories(); final List<PsiDirectory> filteredDirectories = Lists.newArrayListWithExpectedSize(directories.length); for (PsiDirectory directory : directories) { for (VirtualFile file : javaDirectories) { if (VfsUtilCore.isAncestor(file, directory.getVirtualFile(), true)) { filteredDirectories.add(directory); break; } } } final PsiDirectory directory; switch (filteredDirectories.size()) { case 0: directory = null; break; case 1: directory = filteredDirectories.get(0); break; default: // There are several directories, present a dialog window for a user to choose a particular destination directory final PsiDirectory[] array = filteredDirectories.toArray(new PsiDirectory[filteredDirectories.size()]); directory = DirectoryChooserUtil.selectDirectory(aPackage.getProject(), array, filteredDirectories.get(0), ""); } if (directory == null) { return; } final RunResult<PsiClass> result = new WriteCommandAction<PsiClass>(project) { @Override protected void run(@NotNull Result<PsiClass> result) throws Throwable { // Create a new class final PsiClass psiClass = JavaDirectoryService.getInstance().createClass(directory, myClassName); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); // Add a base class to "extends" list final PsiReferenceList list = psiClass.getExtendsList(); if (list != null && myBaseClassFqcn != null) { final PsiClass parentClass = facade.findClass(myBaseClassFqcn, GlobalSearchScope.allScope(project)); if (parentClass != null) { list.add(facade.getElementFactory().createClassReferenceElement(parentClass)); } } // Add a "public" modifier, which is absent by default. Required because classes references in AndroidManifest // have to point to public classes. final PsiModifierList modifierList = psiClass.getModifierList(); if (modifierList != null) { modifierList.setModifierProperty(PsiModifier.PUBLIC, true); } result.setResult(psiClass); } }.execute(); PsiClass aClass = result.getResultObject(); OpenFileDescriptor fileDescriptor = new OpenFileDescriptor(project, aClass.getContainingFile().getVirtualFile()); FileEditorManager.getInstance(project).openEditor(fileDescriptor, true); }
From source file:defrac.intellij.projectView.DefracViewProjectNode.java
@NotNull @Override//ww w . j av a2 s. co m public Collection<? extends AbstractTreeNode> getChildren() { // we want to collect all modules and sort them based on // (1) the fact that they have a defrac facet // (1.1) the defrac project they belong to // (2) arbitrary modules final Project project = getProject(); if (project == null) { return Collections.emptyList(); } final Set<Module> modules = getModules(project); final Map<String, DefracProject> defracModules = Maps.newLinkedHashMap(); final ArrayList<Module> normalModules = Lists.newArrayListWithCapacity(0); for (final Module module : modules) { final DefracFacet facet = DefracFacet.getInstance(module); if (facet == null) { normalModules.add(module); } else { final File settingsFile = facet.getSettingsFile(); final String key = settingsFile.getAbsolutePath(); DefracProject defracProject = defracModules.get(key); if (defracProject == null) { defracProject = DefracProject.forSettings(project, checkNotNull(VfsUtil.findFileByIoFile(settingsFile, true))); defracModules.put(key, defracProject); } defracProject.addModule(module); } } final Collection<AbstractTreeNode> defracNodes = defracModules(project, defracModules.values()); final Collection<AbstractTreeNode> normalNodes = normalModules(normalModules); final int totalNodes = defracNodes.size() + normalNodes.size(); final ArrayList<AbstractTreeNode> result = Lists.newArrayListWithExpectedSize(totalNodes); result.addAll(defracNodes); result.addAll(normalNodes); return result; }
From source file:org.artifactory.webapp.wicket.page.importexport.repos.BasicImportPanel.java
private Form createImportForm() { Form importForm = new SecureForm("importForm"); add(importForm);/* www.j av a 2 s .com*/ //Add the drop down choice for the targetRepo IModel<String> targetRepoModel = new PropertyModel<>(this, "targetRepoKey"); List<LocalRepoDescriptor> localRepos = repositoryService.getLocalAndCachedRepoDescriptors(); Collections.sort(localRepos, new LocalRepoAlphaComparator()); List<String> repoKeys = Lists.newArrayListWithExpectedSize(localRepos.size() + 1); //Add the "All" pseudo repository repoKeys.add(ImportExportReposPage.ALL_REPOS); for (LocalRepoDescriptor localRepo : localRepos) { String key = localRepo.getKey(); repoKeys.add(key); } DropDownChoice<String> targetRepoDdc = new DropDownChoice<>("targetRepo", targetRepoModel, repoKeys); targetRepoDdc.setDefaultModelObject(ImportExportReposPage.ALL_REPOS); importForm.add(targetRepoDdc); final ImportExportStatusHolder status = new ImportExportStatusHolder(); TitledAjaxSubmitLink importButton = new TitledAjaxSubmitLink("import", "Import", importForm) { @Override protected void onSubmit(AjaxRequestTarget target, Form form) { Session.get().cleanupFeedbackMessages(); onBeforeImport(); boolean importAllRepos = ImportExportReposPage.ALL_REPOS.equals(targetRepoKey); File folder = importFromPath; if (importAllRepos) { //If the user has by mistake selected the root backup dir: RTFACT-3480 File repositoriesExportDir = new File(importFromPath, "repositories"); if (repositoriesExportDir.isDirectory()) { folder = repositoriesExportDir; } } status.reset(); status.setVerbose(verbose); ImportSettingsImpl importSettings = new ImportSettingsImpl(folder, status); try { importSettings.setFailIfEmpty(true); importSettings.setVerbose(verbose); importSettings.setIncludeMetadata(!excludeMetadata); //If we chose "All" import all local repositories, else import a single repo if (importAllRepos) { //Do not activate archive indexing until all repositories were imported repositoryService.importAll(importSettings); } else { //We enable the archive indexing from within the import job since we know there will be only one importSettings.setIndexMarkedArchives(true); repositoryService.importRepo(targetRepoKey, importSettings); } List<StatusEntry> errors = status.getErrors(); List<StatusEntry> warnings = status.getWarnings(); String systemLogsPage = WicketUtils.absoluteMountPathForPage(SystemLogsPage.class); String logs = "Please review the <a href=\"" + systemLogsPage + "\">log</a> for further information."; if (!errors.isEmpty()) { error(new UnescapedFeedbackMessage( errors.size() + " error(s) reported during the import. " + logs)); } else if (!warnings.isEmpty()) { warn(new UnescapedFeedbackMessage( warnings.size() + " warning(s) reported during the import. " + logs)); } else { info("Successfully imported '" + importFromPath + "' into '" + targetRepoKey + "'."); } } catch (Exception e) { status.error(e.getMessage(), log); errorImportFeedback(status); } finally { cleanupResources(); } refreshImportPanel(form, target); } private void errorImportFeedback(BasicStatusHolder status) { String error = status.getStatusMsg(); Throwable exception = status.getException(); if (exception != null) { error = exception.getMessage(); } String msg = "Failed to import '" + importFromPath + "' into '" + targetRepoKey + "'. Cause: " + error; error(msg); } }; importForm.add(importButton); importForm.add(new DefaultButtonBehavior(importButton)); return importForm; }