Example usage for java.util.function Consumer Consumer

List of usage examples for java.util.function Consumer Consumer

Introduction

In this page you can find the example usage for java.util.function Consumer Consumer.

Prototype

Consumer

Source Link

Usage

From source file:com.gs.collections.impl.parallel.SerialParallelLazyPerformanceTest.java

private void forEach(FastList<Integer> collection) {
    MutableList<Runnable> runnables = FastList.newList();
    runnables.add(() -> this.basicSerialForEachPerformance(collection, SERIAL_RUN_COUNT));
    int cores = Runtime.getRuntime().availableProcessors();
    ExecutorService service = Executors.newFixedThreadPool(cores);
    runnables.add(() -> {//from w  w w .  j  a  v a  2s .co  m
        MutableMap<Integer, Boolean> map = new ConcurrentHashMap<>();
        this.basicParallelLazyForEachPerformance(collection, "Lambda", item -> map.put(item, Boolean.TRUE),
                PARALLEL_RUN_COUNT, cores, service);
    });
    runnables.add(() -> {
        MutableMap<Integer, Boolean> map = new ConcurrentHashMap<>();
        this.basicParallelLazyForEachPerformance(collection, "Procedure", new Procedure<Integer>() {
            @Override
            public void value(Integer each) {
                map.put(each, Boolean.TRUE);
            }
        }, PARALLEL_RUN_COUNT, cores, service);
    });
    runnables.add(() -> {
        MutableMap<Integer, Boolean> map = new ConcurrentHashMap<>();
        this.basicJava8ParallelLazyForEachPerformance(collection, "Lambda", item -> map.put(item, Boolean.TRUE),
                PARALLEL_RUN_COUNT);
    });
    List<Integer> arrayList = new ArrayList<>(collection);
    runnables.add(() -> {
        MutableMap<Integer, Boolean> map = new ConcurrentHashMap<>();
        this.basicJava8ParallelLazyForEachPerformance(arrayList, "Lambda", item -> map.put(item, Boolean.TRUE),
                PARALLEL_RUN_COUNT);
    });
    runnables.add(() -> {
        MutableMap<Integer, Boolean> map = new ConcurrentHashMap<>();
        this.basicJava8ParallelLazyForEachPerformance(arrayList, "Consumer", new Consumer<Integer>() {
            @Override
            public void accept(Integer each) {
                map.put(each, Boolean.TRUE);
            }
        }, PARALLEL_RUN_COUNT);
    });
    this.shuffleAndRun(runnables);
    service.shutdown();
    try {
        service.awaitTermination(1, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.taobao.android.builder.manager.AtlasAppTaskManager.java

@Override
public void runTask() {

    appExtension.getApplicationVariants().forEach(new Consumer<ApplicationVariant>() {

        @Override//from w ww . j a va2  s  . c om
        public void accept(ApplicationVariant applicationVariant) {

            AppVariantContext appVariantContext = AtlasBuildContext.sBuilderAdapter.appVariantContextFactory
                    .getAppVariantContext(project, applicationVariant);
            if (!AtlasBuildContext.atlasMainDexHelperMap.containsKey(appVariantContext.getVariantName())) {
                AtlasBuildContext.atlasMainDexHelperMap.put(appVariantContext.getVariantName(),
                        new AtlasMainDexHelper());
            }

            TransformReplacer transformReplacer = new TransformReplacer(appVariantContext);

            repalceAndroidBuilder(applicationVariant);

            List<MtlTaskContext> mtlTaskContextList = new ArrayList<MtlTaskContext>();

            mtlTaskContextList.add(new MtlTaskContext(appVariantContext.getVariantData().preBuildTask));

            mtlTaskContextList.add(new MtlTaskContext(BuildAtlasEnvTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(ScanDupResTask.ConfigActon.class, null));

            mtlTaskContextList.add(new MtlTaskContext(LogDependenciesTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(PrepareAPTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(appVariantContext.getVariantData().mergeAssetsTask));

            mtlTaskContextList.add(new MtlTaskContext(RenderscriptCompile.class));

            mtlTaskContextList.add(new MtlTaskContext(StandardizeLibManifestTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(PrepareBundleInfoTask.ConfigAction.class, null));

            if (!atlasExtension.getTBuildConfig().getClassInject() && atlasExtension.isAtlasEnabled()) {
                mtlTaskContextList.add(new MtlTaskContext(GenerateAtlasSourceTask.ConfigAction.class, null));
            }

            mtlTaskContextList.add(new MtlTaskContext(PreparePackageIdsTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(PrepareAaptTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(AidlCompile.class));

            mtlTaskContextList.add(new MtlTaskContext(GenerateBuildConfig.class));

            mtlTaskContextList.add(new MtlTaskContext(MergeResAwbsConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(MergeAssetAwbsConfigAction.class, null));

            if (null != androidExtension.getDataBinding() && androidExtension.getDataBinding().isEnabled()) {

                //                                                                  mtlTaskContextList.add(
                //                                                                          new MtlTaskContext(AwbDataBindingProcessLayoutTask.ConfigAction.class, null));
                mtlTaskContextList
                        .add(new MtlTaskContext(AwbDataBindingExportBuildInfoTask.ConfigAction.class, null));
                mtlTaskContextList
                        .add(new MtlTaskContext(AwbDataBindingMergeArtifactsTask.ConfigAction.class, null));

            }

            mtlTaskContextList.add(new MtlTaskContext(MergeManifests.class));

            mtlTaskContextList.add(new MtlTaskContext(MergeManifestAwbsConfigAction.class, null));

            //mtlTaskContextList.add(new MtlTaskContext(MergeResV4Dir.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(ProcessAndroidResources.class));

            ProcessAndroidResources processAndroidResources = appVariantContext.getScope()
                    .getProcessResourcesTask()
                    .get(new TaskContainerAdaptor(appVariantContext.getProject().getTasks()));
            if (processAndroidResources.isAapt2Enabled()) {
                processAndroidResources.doLast(new Action<Task>() {
                    @Override
                    public void execute(Task task) {
                        File processResourcePackageOutputDirectory = appVariantContext.getScope()
                                .getProcessResourcePackageOutputDirectory();
                        File[] files = processResourcePackageOutputDirectory
                                .listFiles((file, name) -> name.endsWith(SdkConstants.DOT_RES));
                        for (File file : files) {
                            try {
                                ResourcePatch.makePatchable(file);
                            } catch (IOException e) {
                                throw new UncheckedIOException(e);
                            }
                        }
                    }
                });
            }
            mtlTaskContextList.add(new MtlTaskContext(ProcessResAwbsTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(JavacAwbsTask.ConfigAction.class, null));

            if (null != androidExtension.getDataBinding() && androidExtension.getDataBinding().isEnabled()) {
                mtlTaskContextList.add(new MtlTaskContext(AwbDataBindingRenameTask.ConfigAction.class, null));
            }

            mtlTaskContextList.add(new MtlTaskContext(TransformTask.class));

            mtlTaskContextList.add(new MtlTaskContext(PackageAwbsTask.ConfigAction.class, null));

            if (appVariantContext.getAtlasExtension().getTBuildConfig().isIncremental()
                    && (appVariantContext.getBuildType().getPatchConfig() == null
                            || !appVariantContext.getBuildType().getPatchConfig().isCreateTPatch())) {
                //                                                                  mtlTaskContextList.add(new MtlTaskContext(PrepareBaseApkTask.ConfigAction.class, null));
                final TaskFactory tasks = new TaskContainerAdaptor(project.getTasks());
                VariantScope variantScope = appVariantContext.getVariantData().getScope();

                // create the stream generated from this task
                variantScope.getTransformManager()
                        .addStream(OriginalStream.builder(project, applicationVariant.getName())
                                .addContentType(QualifiedContent.DefaultContentType.RESOURCES)
                                .addScope(QualifiedContent.Scope.PROJECT)
                                .setFolders(new Supplier<Collection<File>>() {
                                    @Override
                                    public Collection<File> get() {
                                        return ImmutableList
                                                .of(new File(appVariantContext.apContext.getBaseApk() + "_"));
                                    }
                                }).build());
            }

            final TaskFactory tasks = new TaskContainerAdaptor(project.getTasks());
            VariantScope variantScope = appVariantContext.getVariantData().getScope();

            mtlTaskContextList.add(new MtlTaskContext(PackageApplication.class));

            if (appVariantContext.getAtlasExtension().isInstantAppEnabled()) {

                mtlTaskContextList.add(new MtlTaskContext(AtlasBundleInstantApp.ConfigAction.class, null));
            }

            mtlTaskContextList.add(new MtlTaskContext(ApBuildTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(DiffBundleInfoTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(TPatchDiffResAPBuildTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(TPatchDiffApkBuildTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext(TPatchTask.ConfigAction.class, null));

            mtlTaskContextList.add(new MtlTaskContext("assemble"));

            new MtlTaskInjector(appVariantContext).injectTasks(mtlTaskContextList, tAndroidBuilder);

            List<MtlTransformContext> mtlTransformContextList = new ArrayList<MtlTransformContext>();

            if (atlasExtension.getTBuildConfig().getClassInject()) {
                mtlTransformContextList.add(new MtlTransformContext(ClassInjectTransform.class,
                        ProGuardTransform.class, DexTransform.class));
            }
            if (!mtlTransformContextList.isEmpty()) {
                new MtlTransformInjector(appVariantContext).injectTasks(mtlTransformContextList);
            }
            Collection<BaseVariantOutput> baseVariantOutputDataList = appVariantContext.getVariantOutputData();

            boolean multiDexEnabled = appVariantContext.getVariantData().getVariantConfiguration()
                    .isMultiDexEnabled();

            if (atlasExtension.getTBuildConfig().isAtlasMultiDex() && multiDexEnabled) {
                transformReplacer.replaceMultiDexListTransform();
            }

            transformReplacer.replaceProguardTransform();

            transformReplacer.disableCache();

            if (variantScope.getGlobalScope().getExtension().getDataBinding().isEnabled()) {
                transformReplacer.replaceDataBindingMergeArtifactsTransform();
            }

            for (final BaseVariantOutput vod : baseVariantOutputDataList) {
                transformReplacer.replaceFixStackFramesTransform(vod);
                transformReplacer.replaceDesugarTransform(vod);
                transformReplacer.replaceDexArchiveBuilderTransform(vod);
                transformReplacer.replaceDexExternalLibMerge(vod);
                transformReplacer.replaceDexMerge(vod);
                transformReplacer.replaceDexTransform(appVariantContext, vod);
                transformReplacer.replaceShrinkResourcesTransform();
                transformReplacer.replaceMergeJavaResourcesTransform(appVariantContext, vod);

                if (atlasExtension.getTBuildConfig().isIncremental()) {
                    InstantRunPatchingPolicy patchingPolicy = variantScope.getInstantRunBuildContext()
                            .getPatchingPolicy();
                    BaseVariantOutputImpl variantOutput = (BaseVariantOutputImpl) vod;
                    ApkData data = ApkDataUtils.get(variantOutput);
                    AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees
                            .get(variantScope.getFullVariantName());

                    //                                                                      for (AwbBundle awbBundle : atlasDependencyTree.getAwbBundles()) {
                    //                                                                          AndroidTask<Dex> dexTask = androidTasks.create(tasks, new Dex.ConfigAction(
                    //                                                                                  appVariantContext.getVariantData().getScope(), appVariantContext.getAppVariantOutputContext(data), awbBundle));
                    //                                                                          dexTask.dependsOn(tasks, Iterables
                    //                                                                                  .getLast(TaskQueryHelper.findTask(project, TransformTask.class, appVariantContext.getVariantData())));
                    //                                                                          PackagingScope packagingScope = new AwbPackagingScope(appVariantContext.getScope(), appVariantContext,
                    //                                                                                  awbBundle,vod);
                    //                                                                          AndroidTask<PackageAwb> packageAwb = androidTasks.create(tasks,
                    //                                                                                  new PackageAwb
                    //                                                                                          .StandardConfigAction(
                    //                                                                                          packagingScope,
                    //                                                                                          patchingPolicy));
                    ////
                    //                                                                         packageAwb.dependsOn(tasks, dexTask);
                    //                                                                         PackageAwbsTask packageAwbsTask = Iterators.getOnlyElement(
                    //                                                                                  TaskQueryHelper.findTask(project, PackageAwbsTask.class, appVariantContext.getVariantData()).iterator());
                    //                                                                          packageAwbsTask.setEnabled(false);
                    //                                                                          packageAwbsTask.dependsOn(packageAwb.get(tasks));
                    //                                                                     }
                    //                                                                             AndroidTask<AwoInstallTask> awoInstallTask = androidTasks.create(tasks,
                    //                                                                              new AwoInstallTask.ConfigAction(appVariantContext, vod));
                    //                                                                                awoInstallTask.dependsOn(tasks, variantScope.getPackageApplicationTask().getName());
                }

            }

            Boolean includeCompileClasspath = appVariantContext.getScope().getVariantConfiguration()
                    .getJavaCompileOptions().getAnnotationProcessorOptions().getIncludeCompileClasspath();

            appVariantContext.getVariantData().javaCompilerTask.doFirst(task -> {
                JavaCompile compile = (JavaCompile) task;
                Set<File> mainDexFiles = new MainFilesCollection(appVariantContext.getVariantName()).getFiles();
                FileCollection mainFiles = appVariantContext.getProject().files(mainDexFiles);
                FileCollection files = appVariantContext.getScope()
                        .getArtifactFileCollection(ANNOTATION_PROCESSOR, ALL, JAR);
                FileCollection bootFiles = appVariantContext.getProject().files(appVariantContext.getScope()
                        .getGlobalScope().getAndroidBuilder().getBootClasspath(false));
                mainFiles = mainFiles.plus(bootFiles);
                FileCollection fileCollection = compile.getClasspath();
                File kotlinClasses = null;
                for (File file : fileCollection) {
                    if (file.getAbsolutePath().contains("kotlin-classes")) {
                        mainFiles = mainFiles.plus(appVariantContext.getProject().files(file));
                        kotlinClasses = file;
                        break;
                    }
                }
                compile.setClasspath(mainFiles);
                if (Boolean.TRUE.equals(includeCompileClasspath)) {
                    compile.getOptions().setAnnotationProcessorPath(files.plus(mainFiles));
                }
            });

            appVariantContext.getVariantData().javaCompilerTask.doLast(new Action<Task>() {
                @Override
                public void execute(Task task) {
                    JavaCompile compile = (JavaCompile) task;
                    AtlasBuildContext.atlasMainDexHelperMap.get(appVariantContext.getVariantName())
                            .getInputDirs().add(compile.getDestinationDir());
                }
            });

            PackageAndroidArtifact packageAndroidArtifact = appVariantContext.getVariantData()
                    .getTaskByType(PackageAndroidArtifact.class);
            if (packageAndroidArtifact != null) {
                ReflectUtils.updateField(packageAndroidArtifact, "javaResourceFiles",
                        new AbstractFileCollection() {
                            @Override
                            public String getDisplayName() {
                                return "java-merge-res.jar";
                            }

                            @Override
                            public Set<File> getFiles() {
                                if (AtlasBuildContext.atlasMainDexHelperMap
                                        .get(packageAndroidArtifact.getVariantName())
                                        .getMainJavaRes() == null) {
                                    return Sets.newHashSet();
                                }
                                return Sets.newHashSet(AtlasBuildContext.atlasMainDexHelperMap
                                        .get(packageAndroidArtifact.getVariantName()).getMainJavaRes());
                            }
                        });
            }

            TaskCollection<ExtractTryWithResourcesSupportJar> taskCollection = appVariantContext.getProject()
                    .getTasks().withType(ExtractTryWithResourcesSupportJar.class);
            for (ExtractTryWithResourcesSupportJar task : taskCollection) {
                task.doLast(new Action<Task>() {
                    @Override
                    public void execute(Task task) {
                        ConfigurableFileCollection fileCollection = variantScope
                                .getTryWithResourceRuntimeSupportJar();
                        for (File file : fileCollection.getFiles()) {
                            if (file.exists()) {
                                AtlasBuildContext.atlasMainDexHelperMap.get(variantScope.getFullVariantName())
                                        .addMainDex(new BuildAtlasEnvTask.FileIdentity(
                                                "runtime-deps-try-with-resources", file, false, false));
                                break;
                            }
                        }
                    }
                });

            }
        }
    });
}

From source file:gedi.atac.Atac.java

public static void perChromosomeAndLengthStatistics(GenomicRegionStorage<? extends AlignedReadsData> storage,
        String chrPath, String lenPath) throws IOException {

    LineOrientedFile chr = new LineOrientedFile(chrPath);
    LineOrientedFile len = new LineOrientedFile(lenPath);
    chr.startWriting();/*from  w w  w  .j av a2s .com*/
    len.startWriting();

    chr.write("chromosome");
    len.write("Length");
    for (DynamicObject cond : storage.getMetaData().get("conditions").asArray()) {
        chr.writef("\t%s", cond.getEntry("name").asString());
        len.writef("\t%s", cond.getEntry("name").asString());
    }
    chr.writeLine();
    len.writeLine();

    IntArrayList[] lenHisto = new IntArrayList[storage.getRandomRecord().getNumConditions()];
    for (int i = 0; i < lenHisto.length; i++)
        lenHisto[i] = new IntArrayList();

    for (ReferenceSequence ref : storage.getReferenceSequences()) {

        MutableMonad<long[]> count = new MutableMonad<long[]>();

        storage.iterateMutableReferenceGenomicRegions(ref)
                .forEachRemaining(new Consumer<MutableReferenceGenomicRegion<? extends AlignedReadsData>>() {

                    @Override
                    public void accept(MutableReferenceGenomicRegion<? extends AlignedReadsData> mrgr) {
                        if (count.Item == null)
                            count.Item = new long[mrgr.getData().getNumConditions()];
                        for (int d = 0; d < mrgr.getData().getDistinctSequences(); d++)
                            //                  if (mrgr.getData().getMultiplicity(d)==1)
                            for (int i = 0; i < count.Item.length; i++) {
                                count.Item[i] += mrgr.getData().getCount(d, i) > 0 ? 1 : 0;
                                lenHisto[i].increment(mrgr.getRegion().getTotalLength(),
                                        mrgr.getData().getCount(d, i) > 0 ? 1 : 0);
                            }
                    }

                });

        if (count.Item != null) {
            chr.write(ref.toString());
            for (int i = 0; i < count.Item.length; i++)
                chr.writef("\t%s", count.Item[i]);
            chr.writeLine();
        }

    }

    int maxLength = 0;
    for (int i = 0; i < lenHisto.length; i++)
        maxLength = Math.max(maxLength, lenHisto[i].size() - 1);

    for (int l = 1; l <= maxLength; l++) {
        len.writef("%d", l);
        for (int i = 0; i < lenHisto.length; i++)
            len.writef("\t%d", lenHisto[i].getInt(l));
        len.writeLine();
    }
    chr.finishWriting();
    len.finishWriting();
}

From source file:gov.va.isaac.sync.view.SyncView.java

private Set<String> resolveMergeFailure(MergeFailure mf) throws IllegalArgumentException, IOException {
    Set<String> changedFiles = mf.getFilesChangedDuringMergeAttempt();

    CountDownLatch cdl = new CountDownLatch(1);
    HashMap<String, MergeFailOption> resolutions = new HashMap<String, MergeFailOption>();

    Platform.runLater(() -> {/*from  w  w  w . j  a v  a  2  s  .c  o m*/
        new ResolveConflicts(root_.getScene().getWindow(), mf.getMergeFailures(),
                new Consumer<HashMap<String, MergeFailOption>>() {
                    @Override
                    public void accept(HashMap<String, MergeFailOption> t) {
                        resolutions.putAll(t);
                        cdl.countDown();
                    }
                });
    });

    try {
        cdl.await();
    } catch (InterruptedException e) {
        log.info("Interrupted during wait for resolutions");
    }

    try {
        syncService_.resolveMergeFailures(resolutions);
    } catch (MergeFailure nestedMF) {
        changedFiles.addAll(resolveMergeFailure(nestedMF));
    }

    return changedFiles;
}

From source file:module.siadap.domain.Siadap.java

@Atomic
public void createCurricularPonderation(SiadapUniverse siadapUniverse, BigDecimal gradeToAssign,
        Boolean assignedExcellency, String excellencyAwardJustification,
        String curricularPonderationJustification, Person evaluator) {
    // let's validate everything
    if (siadapUniverse == null || assignedExcellency == null || evaluator == null
            || !SiadapGlobalEvaluation.isValidGrade(gradeToAssign, assignedExcellency.booleanValue())
            || (assignedExcellency.booleanValue() && StringUtils.isEmpty(excellencyAwardJustification))
            || StringUtils.isEmpty(curricularPonderationJustification)) {
        throw new SiadapException("invalid.data.for.creation.of.a.curricular.ponderation");
    }/*from  ww  w .j  a va 2  s.  co  m*/

    // let's if we don't have an evaluation for the given universe
    if (getSiadapEvaluationUniverseForSiadapUniverse(siadapUniverse) != null) {
        throw new SiadapException("error.curricular.ponderation.cannot.have.more.than.one.eval.for.universe");
    }

    SiadapYearConfiguration siadapYearConfiguration = getSiadapYearConfiguration();
    Unit siadapSpecialHarmonizationUnit = siadapYearConfiguration.getSiadapSpecialHarmonizationUnit();
    if (siadapSpecialHarmonizationUnit == null) {
        throw new SiadapException("error.must.configure.special.harmonnization.unit.first");
    }

    final AccountabilityType accTypeToReplace;
    if (siadapUniverse.equals(SiadapUniverse.SIADAP2)) {
        accTypeToReplace = siadapYearConfiguration.getSiadap2HarmonizationRelation();
    } else if (siadapUniverse.equals(SiadapUniverse.SIADAP3)) {
        accTypeToReplace = siadapYearConfiguration.getSiadap3HarmonizationRelation();
    } else {
        accTypeToReplace = null;
    }

    if (accTypeToReplace == null) {
        throw new SiadapException("error.must.configure.SIADAP.2.and.3.harm.relation.types.first");
    }
    // let's create the new SiadapEvaluationUniverse
    SiadapEvaluationUniverse siadapEvaluationUniverse = new SiadapEvaluationUniverse(this, siadapUniverse, null,
            false);
    CurricularPonderationEvaluationItem curricularPonderationEvaluationItem = new CurricularPonderationEvaluationItem(
            gradeToAssign, assignedExcellency, excellencyAwardJustification, curricularPonderationJustification,
            siadapEvaluationUniverse, evaluator);
    // let's connect this SiadapEvaluationUniverse with the specialunit
    Person evaluated = getEvaluated();
    // let's remove the current accountability that it might have for the
    // given SiadapUniverse

    // let's search for the previous accountability
    evaluated.getParentAccountabilityStream()
            .filter(a -> accTypeToReplace == null || a.getAccountabilityType() == accTypeToReplace)
            .filter(a -> a.getParent() instanceof Unit
                    && a.isActive(SiadapMiscUtilClass.lastDayOfYear(getYear())))
            .findAny().ifPresent(new Consumer<Accountability>() {
                @Override
                public void accept(Accountability t) {
                    throw new SiadapException("already.with.a.curricular.ponderation.attributed");
                }

            });

    LocalDate dateToUse = getSiadapYearConfiguration().getLastDayForAccountabilities();

    evaluated.addParent(siadapSpecialHarmonizationUnit, accTypeToReplace, dateToUse,
            SiadapMiscUtilClass.lastDayOfYear(getYear()), null);

}

From source file:gedi.atac.Atac.java

public static void lengthPerTypeStatistics(GenomicRegionStorage<? extends AlignedReadsData> storage, String out,
        String aggOut, String... typePattern) throws IOException {

    IntArrayList[][] lenHisto = new IntArrayList[typePattern.length][storage.getRandomRecord()
            .getNumConditions()];//from   w  w  w  . j a  va2  s  . com
    for (int t = 0; t < lenHisto.length; t++)
        for (int i = 0; i < lenHisto[t].length; i++)
            lenHisto[t][i] = new IntArrayList();

    Pattern[] types = new Pattern[typePattern.length];
    for (int i = 0; i < types.length; i++)
        types[i] = Pattern.compile(typePattern[i]);

    for (ReferenceSequence ref : storage.getReferenceSequences()) {

        int ty = 0;
        for (; ty < types.length && !types[ty].matcher(ref.toPlusMinusString()).find(); ty++)
            ;

        if (ty < types.length)
            System.out.println(ref + " -> " + types[ty]);
        else
            System.out.println("Skipping " + ref);
        MutableMonad<long[]> count = new MutableMonad<long[]>();

        int tyind = ty;
        if (ty < types.length)
            storage.iterateMutableReferenceGenomicRegions(ref).forEachRemaining(
                    new Consumer<MutableReferenceGenomicRegion<? extends AlignedReadsData>>() {

                        @Override
                        public void accept(MutableReferenceGenomicRegion<? extends AlignedReadsData> mrgr) {
                            if (count.Item == null)
                                count.Item = new long[mrgr.getData().getNumConditions()];

                            for (int i = 0; i < count.Item.length; i++) {
                                count.Item[i] += mrgr.getData().getTotalCountForConditionInt(i,
                                        ReadCountMode.All);
                                lenHisto[tyind][i].increment(mrgr.getRegion().getTotalLength(),
                                        mrgr.getData().getTotalCountForConditionInt(i, ReadCountMode.All));
                            }
                        }

                    });

    }

    LineOrientedFile o = new LineOrientedFile(out);
    o.startWriting();

    o.write("Type\tLength");
    for (DynamicObject cond : storage.getMetaData().get("conditions").asArray()) {
        o.writef("\t%s", cond.getEntry("name").asString());
    }
    o.writeLine();

    int maxLength = 0;
    for (int t = 0; t < lenHisto.length; t++)
        for (int i = 0; i < lenHisto.length; i++)
            maxLength = Math.max(maxLength, lenHisto[t][i].size() - 1);

    for (int t = 0; t < lenHisto.length; t++)
        for (int l = 1; l <= maxLength; l++) {
            o.writef("%s\t%d", typePattern[t], l);
            for (int i = 0; i < lenHisto[t].length; i++)
                o.writef("\t%d", lenHisto[t][i].getInt(l));
            o.writeLine();
        }
    o.finishWriting();

    o = new LineOrientedFile(aggOut);
    o.startWriting();

    o.write("Type");
    for (DynamicObject cond : storage.getMetaData().get("conditions").asArray()) {
        o.writef("\t%s", cond.getEntry("name").asString());
    }
    o.writeLine();

    for (int t = 0; t < lenHisto.length; t++) {
        o.writef("%s", typePattern[t]);
        for (int i = 0; i < lenHisto[t].length; i++) {
            long sum = 0;
            for (int l = 1; l <= maxLength; l++)
                sum += lenHisto[t][i].getInt(l);
            o.writef("\t%d", sum);
        }
        o.writeLine();
    }
    o.finishWriting();
}

From source file:dk.dma.ais.store.FileExportRest.java

private AisReader aisReadWriter(InputStream in) throws Exception {

    AisReader r = AisReaders.createReaderFromInputStream(in);
    r.registerPacketHandler(new Consumer<AisPacket>() {

        @Override/*www.  j ava2 s.  c o  m*/
        public void accept(AisPacket t) {
            AisMessage message = t.tryGetAisMessage();

            // System.out.println(message.toString());

            currentTimeStamp = t.getBestTimestamp();

            if (lastLoadedTimestamp >= currentTimeStamp) {
                // System.out.println("Skipping Message!");
                return;
            }

            if (message == null) {
                return;
            }

            try {
                sink.process(outputStream, t, counter.incrementAndGet());

                if (currentTimeStamp != lastFlushTimestamp && counter.get() % 10000 == 0) {

                    // We have a new timestamp sequence
                    lastFlushTimestamp = currentTimeStamp;

                    writeMetaUpdate(lastFlushTimestamp, counter.get());

                    // Force flush on both

                    outputStream.flush();
                    fileOutputStream.flush();

                    // Write
                    // lastFlushTimestamp
                    // timestamp

                    // if (counter.get() >= 1000) {
                    // System.out.println("Terminating as part of test! Last written timestamp was " + lastFlushTimestamp);
                    // System.exit(0);
                    // }

                    // Update user on progress
                    printDownloadStatus();
                }

                //

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    });

    return r;

}

From source file:com.diversityarrays.kdxplore.boxplot.BoxPlotPanel.java

private void setSelectedTraitAndMeasurements() {
    boolean sync = getSyncWhat().isSync();

    PlotsByTraitInstance plotsByTi = sync ? new PlotsByTraitInstance() : null;

    List<KdxSample> selectedSamples = new ArrayList<>();

    if (minSelectedY != null && maxSelectedY != null) {

        for (Plot plot : plotInfoProvider.getPlots()) {

            Consumer<KdxSample> visitor = new Consumer<KdxSample>() {
                @Override//from  www  .  j  a va 2  s . co m
                public void accept(KdxSample s) {
                    TraitInstance ti = plotInfoProvider.getTraitInstanceForSample(s);
                    if (checkIfSelected(s, minSelectedY, maxSelectedY) == AxisType.Y) {
                        selectedSamples.add(s);

                        if (plotsByTi != null) {
                            plotsByTi.addPlot(ti, plot);
                        }
                    }
                }
            };

            if (usedPlotSpecimens.isEmpty() || usedPlotSpecimens.contains(plot)) {
                plotInfoProvider.visitSamplesForPlotOrSpecimen(plot, visitor);
            }
        }
    }

    // TODO review not do it when empty
    if (plotsByTi != null) { // && ! plotsByTi.isEmpty()) {
        selectedValueStore.setSelectedPlots(toolPanelId, plotsByTi);
    }

    if (curationControls != null) {
        curationControls.setSamples(selectedSamples);
        int index = messagesAndCurationTabbedPane.indexOfTab(TAB_CURATION);
        if (index >= 0) {
            messagesAndCurationTabbedPane.setSelectedIndex(index);
        }
        // Note that curationControls is only non-null if we have ONE TraitInstance
        // so all of the selectedSampled must be for that TraitInstance   
        curationControls.updateButtons();
    }

    fireSelectionStateChanged();
}

From source file:gedi.atac.Atac.java

public static void normalizationFactors(GenomicRegionStorage<? extends AlignedReadsData> storage,
        GenomicRegionStorage<?> peaks, String out, String peakout, String detailout, String... typePattern)
        throws IOException {

    int cond = storage.getRandomRecord().getNumConditions();
    int[][] allCounts = new int[typePattern.length][cond];
    int[][] peakCounts = new int[typePattern.length][cond];

    Pattern[] types = new Pattern[typePattern.length];
    for (int i = 0; i < types.length; i++)
        types[i] = Pattern.compile(typePattern[i]);

    new LineOrientedFile(detailout).delete();

    Set<ReferenceSequence> refs = new TreeSet<ReferenceSequence>();
    for (ReferenceSequence ref : storage.getReferenceSequences())
        refs.add(ref.toStrandIndependent());

    for (ReferenceSequence ref : refs) {

        int ty = 0;
        for (; ty < types.length && !types[ty].matcher(ref.toPlusMinusString()).find(); ty++)
            ;/*  w w  w  .  j  a  va2s .  c om*/

        if (ty < types.length)
            System.out.println(ref + " -> " + types[ty]);
        else
            System.out.println("Skipping " + ref);

        HashMap<ImmutableReferenceGenomicRegion<?>, int[]> detail = new HashMap<ImmutableReferenceGenomicRegion<?>, int[]>();

        int tyind = ty;
        Consumer<MutableReferenceGenomicRegion<? extends AlignedReadsData>> adder = new Consumer<MutableReferenceGenomicRegion<? extends AlignedReadsData>>() {

            @Override
            public void accept(MutableReferenceGenomicRegion<? extends AlignedReadsData> mrgr) {

                int f = GenomicRegionPosition.Start.position(ref, mrgr.getRegion(), 4);
                int b = GenomicRegionPosition.Stop.position(ref, mrgr.getRegion(), -4);

                int inpeak = 0;
                if (StreamSupport.stream(peaks.iterateIntersectingMutableReferenceGenomicRegions(
                        ref.toStrandIndependent(), f, f + 1), false).peek(peak -> {
                            int[] c = detail.computeIfAbsent(peak.toImmutable(), x -> new int[cond]);
                            for (int i = 0; i < c.length; i++)
                                c[i] += mrgr.getData().getTotalCountForConditionInt(i, ReadCountMode.All);
                        }).count() > 0)
                    inpeak++;

                if (StreamSupport.stream(peaks.iterateIntersectingMutableReferenceGenomicRegions(
                        ref.toStrandIndependent(), b, b + 1), false).peek(peak -> {
                            int[] c = detail.computeIfAbsent(peak.toImmutable(), x -> new int[cond]);
                            for (int i = 0; i < c.length; i++)
                                c[i] += mrgr.getData().getTotalCountForConditionInt(i, ReadCountMode.All);
                        }).count() > 0)
                    inpeak++;

                for (int i = 0; i < allCounts[tyind].length; i++) {
                    allCounts[tyind][i] += mrgr.getData().getTotalCountForConditionInt(i, ReadCountMode.All);
                    if (inpeak > 0)
                        peakCounts[tyind][i] += mrgr.getData().getTotalCountForConditionInt(i,
                                ReadCountMode.All) * inpeak;
                }
            }

        };
        if (ty < types.length) {
            storage.iterateMutableReferenceGenomicRegions(ref).forEachRemaining(adder);
            storage.iterateMutableReferenceGenomicRegions(ref.toPlusStrand()).forEachRemaining(adder);
            storage.iterateMutableReferenceGenomicRegions(ref.toMinusStrand()).forEachRemaining(adder);
        }

        LineOrientedFile d = new LineOrientedFile(detailout);
        if (d.exists())
            d.startAppending();
        else {
            d.startWriting();
            d.write("Peak\tType");
            for (int i = 0; i < cond; i++)
                d.writef("\t%d", i);
            d.writeLine();
        }

        for (ImmutableReferenceGenomicRegion<?> peak : detail.keySet()) {
            int[] count = detail.get(peak);
            d.writef("%s\t%s", peak.toLocationString(), typePattern[ty]);
            for (int c = 0; c < cond; c++)
                d.writef("\t%d", count[c]);
            d.writeLine();
        }
        d.finishWriting();

    }

    LineOrientedFile o = new LineOrientedFile(out);
    o.startWriting();
    o.write("Type\tCondition Index\tCount\n");
    for (int i = 0; i < types.length; i++) {
        for (int c = 0; c < allCounts[i].length; c++) {
            o.writef("%s\t%d\t%d\n", typePattern[i], c, allCounts[i][c]);
        }
    }
    o.finishWriting();

    o = new LineOrientedFile(peakout);
    o.startWriting();
    o.write("Type\tCondition Index\tCount\n");
    for (int i = 0; i < types.length; i++) {
        for (int c = 0; c < allCounts[i].length; c++) {
            o.writef("%s\t%d\t%d\n", typePattern[i], c, peakCounts[i][c]);
        }
    }
    o.finishWriting();
}

From source file:pt.ist.expenditureTrackingSystem.domain.organization.Unit.java

public static void getSubUnitsSet(final Set<Unit> result, final Party party) {
    party.getChildAccountabilityStream().map(a -> a.getChild()).filter(p -> p.isUnit())
            .map(p -> (module.organization.domain.Unit) p)
            .forEach(new Consumer<module.organization.domain.Unit>() {
                @Override//w  w w  .  j av  a 2  s  . c  om
                public void accept(final module.organization.domain.Unit u) {
                    if (u.getExpenditureUnit() != null) {
                        result.add(u.getExpenditureUnit());
                    } else {
                        getSubUnitsSet(result, u);
                    }
                }
            });
}