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:org.apache.pulsar.sql.presto.PulsarMetadata.java

@Override
public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) {
    PulsarTableHandle pulsarTableHandle = convertTableHandle(tableHandle);

    ConnectorTableMetadata tableMetaData = getTableMetadata(pulsarTableHandle.toSchemaTableName(), false);
    if (tableMetaData == null) {
        return new HashMap<>();
    }// w w w .  j  a  v  a  2 s .c o  m

    ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder();

    tableMetaData.getColumns().forEach(new Consumer<ColumnMetadata>() {
        @Override
        public void accept(ColumnMetadata columnMetadata) {

            PulsarColumnMetadata pulsarColumnMetadata = (PulsarColumnMetadata) columnMetadata;

            PulsarColumnHandle pulsarColumnHandle = new PulsarColumnHandle(connectorId,
                    pulsarColumnMetadata.getNameWithCase(), pulsarColumnMetadata.getType(),
                    pulsarColumnMetadata.isHidden(), pulsarColumnMetadata.isInternal(),
                    pulsarColumnMetadata.getFieldNames(), pulsarColumnMetadata.getPositionIndices());

            columnHandles.put(columnMetadata.getName(), pulsarColumnHandle);
        }
    });

    PulsarInternalColumn.getInternalFields().stream().forEach(new Consumer<PulsarInternalColumn>() {
        @Override
        public void accept(PulsarInternalColumn pulsarInternalColumn) {
            PulsarColumnHandle pulsarColumnHandle = pulsarInternalColumn.getColumnHandle(connectorId, false);
            columnHandles.put(pulsarColumnHandle.getName(), pulsarColumnHandle);
        }
    });

    return columnHandles.build();
}

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

public BoxPlotPanel(PlotInfoProvider pip, VisualisationToolId<?> vtoolId, SelectedValueStore svs, String title,
        VisToolData data, Supplier<TraitColorProvider> colorProviderFactory,
        SuppressionHandler suppressionHandler) {
    super(title, vtoolId, svs, nextId++, data.traitInstances, data.context.getTrial(), suppressionHandler);

    int ndecs = 0;
    for (TraitInstance ti : traitInstances) {
        String vr = ti.trait.getTraitValRule();
        if (!Check.isEmpty(vr)) {
            try {
                ValidationRule vrule = ValidationRule.create(vr);
                ndecs = Math.max(ndecs, vrule.getNumberOfDecimalPlaces());
            } catch (UnsupportedOperationException | InvalidRuleException snh) {
                throw new RuntimeException(ti.trait.getTraitValRule(), snh);
            }//from  w  ww. j a  v  a  2s .  com
        }
    }
    this.maxNumberOfDecimalPlaces = ndecs;

    Function<TraitInstance, List<KdxSample>> sampleProvider = new Function<TraitInstance, List<KdxSample>>() {
        @Override
        public List<KdxSample> apply(TraitInstance ti) {
            return pip.getSampleMeasurements(ti);
        }
    };
    tivrByTi = VisToolUtil.buildTraitInstanceValueRetrieverMap(trial, traitInstances, sampleProvider);

    this.plotInfoProvider = pip;
    this.colorProviderFactory = colorProviderFactory;

    if (Check.isEmpty(data.plotSpecimensToGraph)) {
        plotSpecimens = new ArrayList<>();
        VisToolUtil.collectPlotSpecimens(plotInfoProvider.getPlots(), new Consumer<PlotOrSpecimen>() {
            @Override
            public void accept(PlotOrSpecimen pos) {
                plotSpecimens.add(pos);
            }
        });
        selectedPlotSpecimenCount = 0;
    } else {
        plotSpecimens = data.plotSpecimensToGraph;
        selectedPlotSpecimenCount = plotSpecimens.size();
    }

    JComponent controlsOrLabel;

    String messageLine = selectedPlotSpecimenCount <= 0 ? null
            : Msg.MSG_ONLY_FOR_N_PLOTS(selectedPlotSpecimenCount);

    if (traitInstances.size() == 1) {
        curationControls = new CurationControls(true, // askAboutValueForUnscored
                suppressionHandler, selectedValueStore, toolPanelId, messageLine, traitNameStyle,
                Arrays.asList(traitInstances.get(0)));
        curationControls.setBorder(new EmptyBorder(2, 4, 2, 4));

        controlsOrLabel = curationControls;
    } else {
        StringBuilder sb = new StringBuilder("<HTML>"); //$NON-NLS-1$
        if (messageLine != null) {
            sb.append(messageLine).append("<br>"); //$NON-NLS-1$
        }
        sb.append(Msg.HTML_CURATION_NOT_AVAILABLE_WITH_MULTIPLE_TRAITS());
        controlsOrLabel = new JLabel(sb.toString());
    }

    messagesAndCurationTabbedPane = new JTabbedPane();
    messagesAndCurationTabbedPane.addTab(TAB_MESSAGES, new JScrollPane(reportTextArea));
    messagesAndCurationTabbedPane.addTab(TAB_CURATION, controlsOrLabel);

    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, messagesAndCurationTabbedPane, new JLabel()); // placeholder

    splitPane.setOneTouchExpandable(true);
    splitPane.setResizeWeight(0.0);

    Box controls = generateControls();

    add(controlsOrLabel, BorderLayout.NORTH);
    add(splitPane, BorderLayout.CENTER);
    add(controls, BorderLayout.SOUTH);

    generateGraph(Why.INITIAL);

    minSpinnerModel.addChangeListener(spinnerChangeListener);
    maxSpinnerModel.addChangeListener(spinnerChangeListener);

    NumberEditor formatterMin;
    NumberEditor formatterMax;

    stillChanging = true;
    try {
        if (maxNumberOfDecimalPlaces <= 0) {
            // integer
            minSpinnerModel.setStepSize(1);
            maxSpinnerModel.setStepSize(1);

            formatterMin = new JSpinner.NumberEditor(minSpinner, "0"); //$NON-NLS-1$
            formatterMax = new JSpinner.NumberEditor(maxSpinner, "0"); //$NON-NLS-1$
        } else {
            double stepSize = Math.pow(10, -maxNumberOfDecimalPlaces);

            minSpinnerModel.setStepSize(stepSize);
            maxSpinnerModel.setStepSize(stepSize);

            StringBuilder sb = new StringBuilder("0."); //$NON-NLS-1$
            for (int i = maxNumberOfDecimalPlaces; --i >= 0;) {
                sb.append("0"); //$NON-NLS-1$
            }
            String fmt = sb.toString();
            formatterMin = new JSpinner.NumberEditor(minSpinner, fmt);
            formatterMax = new JSpinner.NumberEditor(maxSpinner, fmt);
        }
    } finally {
        stillChanging = false;
    }

    formatterMin.setEnabled(true);
    formatterMax.setEnabled(true);

    minSpinner.setEditor(formatterMin);
    maxSpinner.setEditor(formatterMax);

    minSpinner.setBorder(new EmptyBorder(3, 5, 3, 5));
    maxSpinner.setBorder(new EmptyBorder(3, 5, 3, 5));

    setSpinnerRanges();
}

From source file:de.jackwhite20.japs.client.cache.impl.PubSubCacheImpl.java

@Override
public <T> void getClass(String key, Consumer<T> consumer, Class<T> clazz) {

    if (key == null || key.isEmpty()) {
        throw new IllegalArgumentException("key cannot be null or empty");
    }/* ww w  .  ja  v a  2 s  .c  o  m*/

    if (consumer == null) {
        throw new IllegalArgumentException("consumer cannot be null or empty");
    }

    if (clazz == null) {
        throw new IllegalArgumentException("clazz cannot be null or empty");
    }

    int id = CALLBACK_COUNTER.getAndIncrement();

    // TODO: 14.06.2016 Maybe improve
    // Get the class as string and deserialize it
    callbacks.put(id, new Consumer<String>() {

        @Override
        public void accept(String s) {

            consumer.accept(gson.fromJson(s, clazz));
        }
    });

    JSONObject jsonObject = new JSONObject().put("op", OpCode.OP_CACHE_GET.getCode()).put("key", key).put("id",
            id);

    write(jsonObject);
}

From source file:com.diversityarrays.kdxplore.scatterplot.ScatterPlotPanel.java

public ScatterPlotPanel(PlotInfoProvider infoProvider, VisualisationToolId<?> vtoolId, SelectedValueStore svs,
        String title, VisToolData data, Supplier<TraitColorProvider> colorProviderFactory,
        SuppressionHandler sh) {/*from  ww w  .  j a  v a 2s  .co m*/
    super(title, vtoolId, svs, nextId++, data.traitInstances, data.context.getTrial(), sh);

    this.plotInfoProvider = infoProvider;

    if (data.plotSpecimensToGraph == null) {
        plotSpecimens = new ArrayList<>();
        VisToolUtil.collectPlotSpecimens(plotInfoProvider.getPlots(), new Consumer<PlotOrSpecimen>() {
            @Override
            public void accept(PlotOrSpecimen pos) {
                plotSpecimens.add(pos);
            }
        });
    } else {
        plotSpecimens = data.plotSpecimensToGraph;
    }

    List<List<Comparable<?>>> instanceValuesList = new ArrayList<>();

    this.colorProviderFactory = colorProviderFactory;

    Function<TraitInstance, List<KdxSample>> sampleProvider = new Function<TraitInstance, List<KdxSample>>() {
        @Override
        public List<KdxSample> apply(TraitInstance ti) {
            return infoProvider.getSampleMeasurements(ti);
        }
    };
    tivrByTi = VisToolUtil.buildTraitInstanceValueRetrieverMap(trial, traitInstances, sampleProvider);

    int plotLength = instanceValuesList.size();
    if (plotLength < 3) {
        plotLength = 3;
    }

    xInstance = traitInstances.get(0);
    TraitInstance firstValueInstance = null;

    for (int i = 1; i < traitInstances.size(); i++) {
        TraitInstance ti = traitInstances.get(i);
        if (firstValueInstance == null) {
            firstValueInstance = ti;
        }
        valueInstances.add(ti);
        valueInstanceByTraitIdAndNumber.put(InstanceIdentifierUtil.getInstanceIdentifier(ti), ti);
    }

    xAxisName = traitNameStyle.makeTraitInstanceName(xInstance);

    if (traitInstances.size() == 2) {
        yAxisName = traitNameStyle.makeTraitInstanceName(firstValueInstance);
    } else {
        yAxisName = "Sample Measurement Value";
    }

    chartPanel.addChartMouseListener(chartMouseListener);

    Bag<String> missingOrBad = new TreeBag<String>();
    Bag<String> suppressed = new TreeBag<String>();

    generateChart(true, missingOrBad, suppressed);

    ChangeListener listener = new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            if (!stillChanging) {
                clearExternallySelectedPlots();

                setXYValues();
                drawRectangle();
                if (mouseDownPoint != null && mouseUpPoint != null) {
                    buildMinMaxPoints();
                    setSelectedTraitAndMeasurements();
                }
            }
        }
    };

    minxSpinner.addChangeListener(listener);
    minySpinner.addChangeListener(listener);
    maxxSpinner.addChangeListener(listener);
    maxySpinner.addChangeListener(listener);

    stillChanging = true;
    minxModel.setValue(dataxMin);
    maxxModel.setValue(dataxMax);

    minyModel.setValue(datayMin);
    maxyModel.setValue(datayMax);

    minxModel.setMinimum(dataxMin);
    minxModel.setMaximum(dataxMax);
    minyModel.setMinimum(datayMin);
    minyModel.setMaximum(datayMax);

    maxxModel.setMinimum(dataxMin);
    maxxModel.setMaximum(dataxMax);
    maxyModel.setMinimum(datayMin);
    maxyModel.setMaximum(datayMax);
    stillChanging = false;

    Box hbox = Box.createHorizontalBox();
    hbox.add(syncedOption);

    addSpinners(hbox, minxSpinner, minySpinner);
    hbox.add(new JLabel(" " + Msg.LABEL_MIN_TO_MAX_SEPARATOR() + " ")); //$NON-NLS-1$ //$NON-NLS-2$
    addSpinners(hbox, maxxSpinner, maxySpinner);

    List<TraitInstance> curationControlInstances = traitInstances;
    curationControlInstances.remove(xInstance);

    curationControls = new CurationControls(true, // askAboutValueForUnscored
            suppressionHandler, selectedValueStore,
            //              plotInfoProvider, 
            toolPanelId, null, traitNameStyle, curationControlInstances);

    reportTextArea = new JTextArea();
    reportTextArea.setEditable(false);

    tabMessages = Msg.TAB_MESSAGES();
    tabCuration = Msg.TAB_CURATION();
    tabbedPane.addTab(tabMessages, new JScrollPane(reportTextArea));
    tabbedPane.addTab(tabCuration, curationControls);

    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tabbedPane, chartPanel);

    splitPane.setOneTouchExpandable(true);
    splitPane.setResizeWeight(0.0);
    add(splitPane, BorderLayout.CENTER);
    add(hbox, BorderLayout.SOUTH);

    splitPane.repaint(); // TODO why is this here?

    String msg = VisToolData.createReportText(missingOrBad, suppressed);
    if (Check.isEmpty(msg)) {
        tabbedPane.setSelectedIndex(tabbedPane.indexOfTab(tabCuration));
    } else {
        reportTextArea.setText(msg);
        tabbedPane.setSelectedIndex(tabbedPane.indexOfTab(tabMessages));
    }

    setPreferredSize(new Dimension(600, 500));
}

From source file:dk.dma.ais.decode.DecodeTest.java

public void makeTrackTest() throws IOException {
    // Open input stream
    // URL url = ClassLoader.getSystemResource("small_cb_example.txt");
    // Assert.assertNotNull(url);
    // InputStream inputStream = url.openStream();
    // Assert.assertNotNull(inputStream);
    String filename = "/Users/oleborup/pride_of_hull_311062900.txt";
    // String filename = "/Users/oleborup/pride_of_rotterdam_244980000.txt";
    final ArrayList<AisPositionMessage> posMessages = new ArrayList<>();

    try (FileInputStream inputStream = new FileInputStream(filename);
            AisPacketReader r = new AisPacketReader(inputStream);) {

        // Make AIS reader instance
        r.forEachRemaining(new Consumer<AisPacket>() {
            @Override// www .j  a  va 2 s  .  c om
            public void accept(AisPacket packet) {
                Date t = packet.getTimestamp();
                if (t == null) {
                    return;
                }
                // Filter on country
                AisPacketTags tags = packet.getTags();
                if (tags == null) {
                    return;
                }
                Country country = tags.getSourceCountry();
                if (country == null) {
                    return;
                }
                if (!country.getTwoLetter().equals("NL") && !country.getTwoLetter().equals("GB")) {
                    return;
                }
                AisMessage message = packet.tryGetAisMessage();
                if (message == null || !(message instanceof AisPositionMessage)) {
                    return;
                }
                posMessages.add((AisPositionMessage) message);
            }
        });
    }
    System.out.println("Position messages: " + posMessages.size());

    ArrayList<String> positions = new ArrayList<>();
    Integer mmsi = null;
    Position lastPos = null;
    Position refPos = Position.create(52.58, 2.3);
    for (AisPositionMessage posMessage : posMessages) {
        Position pos = posMessage.getPos().getGeoLocation();
        if (pos == null) {
            continue;
        }
        if (refPos.rhumbLineDistanceTo(pos) > 500000) {
            continue;
        }
        if (mmsi == null) {
            mmsi = posMessage.getUserId();
        }
        if (lastPos != null) {
            // Downsample on distance
            if (lastPos.rhumbLineDistanceTo(pos) < 1000) {
                continue;
            }
        }
        String strPos = String.format(Locale.US, "%f,%f,0", pos.getLongitude(), pos.getLatitude());
        positions.add(strPos);
        lastPos = pos;
    }

    System.out.println("Positions in KML: " + positions.size());
    StringBuilder buf = new StringBuilder();
    buf.append("<kml><Document><name>Tracks</name><open>1</open><Folder><name>" + mmsi + "</name>");
    buf.append("<Placemark><name>" + mmsi + "</name><LineString><coordinates>\n");
    buf.append(StringUtils.join(positions, " "));
    buf.append("\n</coordinates></LineString></Placemark></Folder></Document></kml>");
    try (PrintWriter out = new PrintWriter(filename + ".kml")) {
        out.print(buf);
    }
}

From source file:dk.dma.ais.reader.AisReader.java

/**
 * Returns a ais packet stream.// w  w  w. j ava  2 s . co  m
 * 
 * @return the stream
 */
public AisPacketStream stream() {
    final AisPacketStream s = AisPacketStream.newStream();
    registerPacketHandler(new Consumer<AisPacket>() {
        public void accept(AisPacket p) {
            s.add(p);
        }
    });
    return s.immutableStream();// Only adds from reader
}

From source file:dk.dma.epd.shore.EPDShore.java

/**
 * Constructor//from  ww w.  j ava 2s .c om
 * 
 * @param path
 *            the home path to use
 */
private EPDShore(String path) throws IOException {
    super();

    if (!StringUtils.isEmpty(path)) {
        homePath = Paths.get(path);
    } else {
        homePath = determineHomePath(Paths.get(System.getProperty("user.home"), ".epd-shore"));
    }

    new Bootstrap().run(this, new String[] { "epd-shore.properties", "settings.properties", "transponder.xml" },
            new String[] { "workspaces", "routes", "shape/GSHHS_shp", "identities" });

    // Set up log4j logging
    LOG = LoggerFactory.getLogger(EPDShore.class);

    // Set default exception handler
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());

    LOG.info("Starting eNavigation Prototype Display Shore - version " + VersionInfo.getVersionAndBuild());
    LOG.info("Copyright (C) 2012 Danish Maritime Authority");
    LOG.info("This program comes with ABSOLUTELY NO WARRANTY.");
    LOG.info("This is free software, and you are welcome to redistribute it under certain conditions.");
    LOG.info("For details see LICENSE file.");

    // Create the bean context (map handler)
    // mapHandler = new MapHandler();
    beanHandler = new BeanContextServicesSupport();

    // Load settings or get defaults and add to bean context
    settings = new EPDSettings();
    LOG.info("Using settings file: " + getSettings().getSettingsFile());
    settings.loadFromFile();
    beanHandler.add(settings);

    // Determine if instance already running and if that is allowed

    OneInstanceGuard guard = new OneInstanceGuard(getHomePath().resolve("epd.lock").toString());
    if (guard.isAlreadyRunning()) {
        handleEpdAlreadyRunning();
    }

    // Enable GPS timer by adding it to bean context
    PntTime.init(settings.getSensorSettings().isUseTimeFromPnt());
    beanHandler.add(PntTime.getInstance());

    // aisHandler = new AisHandlerCommon();
    aisHandler = new AisHandler(settings.getAisSettings());
    aisHandler.loadView();
    EPD.startThread(aisHandler, "AisHandler");
    beanHandler.add(aisHandler);

    // Add StaticImages handler
    staticImages = new StaticImages();
    beanHandler.add(staticImages);

    // Load routeManager
    routeManager = RouteManager.loadRouteManager();
    beanHandler.add(routeManager);

    falManager = FALManager.loadFALManager();
    beanHandler.add(falManager);

    // To be changed to load similar to routeManager
    // voyageManager = new VoyageManager();
    voyageManager = VoyageManager.loadVoyageManager();
    beanHandler.add(voyageManager);

    sruManager = SRUManager.loadSRUManager();
    beanHandler.add(sruManager);

    // Create shore services
    shoreServicesCommon = new ShoreServices(getSettings().getEnavSettings());
    beanHandler.add(shoreServicesCommon);

    // Create mona lisa route exchange
    monaLisaRouteExchange = new MonaLisaRouteOptimization();
    beanHandler.add(monaLisaRouteExchange);

    // Create Maritime Cloud service
    maritimeCloudService = new MaritimeCloudService();
    beanHandler.add(maritimeCloudService);
    maritimeCloudService.start();

    // Create strategic route Handler;
    strategicRouteHandler = new StrategicRouteHandler();
    beanHandler.add(strategicRouteHandler);

    // Create intended route handler
    intendedRouteHandler = new IntendedRouteHandler();
    beanHandler.add(intendedRouteHandler);

    // Create the route suggestion handler
    // routeSuggestionHandler = new RouteSuggestionHandler();
    routeSuggestionHandler = RouteSuggestionHandler.loadRouteSuggestionHandler();
    beanHandler.add(routeSuggestionHandler);

    // Create a new MSI-NM handler
    msiNmHandler = new MsiNmServiceHandlerCommon();
    beanHandler.add(msiNmHandler);

    // Create a chat service handler
    chatServiceHandler = new ChatServiceHandlerCommon();
    beanHandler.add(chatServiceHandler);

    // Create identity handler
    identityHandler = new IdentityHandler();
    beanHandler.add(identityHandler);

    // Start sensors
    startSensors();

    pluginLoader = new PluginLoader(getProperties(), getHomePath(), getPropertyFileName());

    try {
        pluginLoader.createPluginComponents(new Consumer<Object>() {
            public void accept(Object comp) {
                beanHandler.add(comp);
            }
        });
    } catch (Exception e) {
        LOG.error("Failed to load plugin container " + e.getMessage());
    }

    final CountDownLatch guiCreated = new CountDownLatch(1);

    // Create and show GUI
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            createAndShowGUI();
            guiCreated.countDown();
        }
    });

    // Wait for gui to be created
    try {
        guiCreated.await();

    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for GUI to be created", e);
    }

    // Create vocthandler
    voctHandler = new VoctHandler();
    beanHandler.add(voctHandler);

    // Create voct manager
    voctManager = new VOCTManager();
    beanHandler.add(voctManager);
    voctManager.loadVOCTManager();

    // Create FAL Handler
    falHandler = new FALHandler();
    beanHandler.add(falHandler);

    // Create embedded transponder frame
    transponderFrame = new TransponderFrame(getHomePath().resolve("transponder.xml").toString(), true,
            mainFrame);
    mainFrame.getTopMenu().setTransponderFrame(transponderFrame);
    beanHandler.add(transponderFrame);

    if (settings.getSensorSettings().isStartTransponder()) {
        transponderFrame.startTransponder();
    }
}

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

public static void findAcquisitionProcessesPendingAuthorization(final Party party,
        final Set<AcquisitionProcess> result, final boolean recurseSubUnits) {
    if (recurseSubUnits) {
        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/* ww w  .  ja  va  2 s.  c o m*/
                    public void accept(module.organization.domain.Unit childUnit) {
                        if (childUnit.getExpenditureUnit() != null) {
                            final Unit expenditureUnit = childUnit.getExpenditureUnit();
                            if (expenditureUnit instanceof CostCenter || expenditureUnit instanceof Project) {
                                expenditureUnit.findAcquisitionProcessesPendingAuthorization(result,
                                        recurseSubUnits);
                            }
                        }
                        findAcquisitionProcessesPendingAuthorization(childUnit, result, recurseSubUnits);
                    }
                });
    }
}

From source file:com.taobao.android.builder.tools.bundleinfo.BundleGraphExecutor.java

public static void execute(List<BundleInfo> bundleInfos, int parableCount, BundleItemRunner bundleItemRunner)
        throws IOException, InterruptedException {

    Map<String, BundleInfo> bundleInfoMap = new HashMap<>();
    bundleInfos.forEach(new Consumer<BundleInfo>() {
        @Override//  ww w . j av  a2s.c om
        public void accept(BundleInfo bundleInfo) {
            bundleInfoMap.put(bundleInfo.getPkgName(), bundleInfo);
        }
    });

    Map<String, BundleItem> bundleItemMap = getBundleItemMap(bundleInfoMap);

    handleCircleDependency(bundleItemMap);

    int size = bundleItemMap.size();

    ExecutorServicesHelper executorServicesHelper = new ExecutorServicesHelper("bundleGraph", logger,
            parableCount);

    int index = 0;
    int j = 0;
    while (index <= size) {

        List<String> keys = new ArrayList<>();
        List<Runnable> runnables = new ArrayList<>();

        for (String key : bundleItemMap.keySet()) {

            //System.out.println("test" + key);
            BundleItem bundleItem = bundleItemMap.get(key);

            if (bundleItem.canResolve()) {

                index++;
                //bundleItem.resolve();
                keys.add(key);

                final String name = index + bundleItem.bundleInfo.getPkgName();
                runnables.add(new Runnable() {
                    @Override
                    public void run() {
                        logger.warn("start to do bundle proguard for " + name);
                        bundleItemRunner.execute(bundleItem);
                        logger.warn("end do bundle proguard for " + name);
                    }
                });

            }
        }

        Profiler.enter("execute stage " + j++ + " runnables " + runnables.size());
        executorServicesHelper.execute(runnables);
        Profiler.release();

        if (keys.isEmpty()) {
            break;
        }

        for (String key : keys) {
            bundleItemMap.get(key).resolve();
            bundleItemMap.remove(key);
        }
    }

    if (index != size) {
        throw new GradleException("bundleGraph is some thing wrong");
    }

}

From source file:org.apache.pulsar.functions.worker.FunctionActioner.java

public void terminateFunction(FunctionRuntimeInfo functionRuntimeInfo) {
    FunctionDetails details = functionRuntimeInfo.getFunctionInstance().getFunctionMetaData()
            .getFunctionDetails();// www .j  a va2  s. co m
    log.info("{}/{}/{}-{} Terminating function...", details.getTenant(), details.getNamespace(),
            details.getName(), functionRuntimeInfo.getFunctionInstance().getInstanceId());
    String fqfn = FunctionDetailsUtils.getFullyQualifiedName(details);

    stopFunction(functionRuntimeInfo);
    //cleanup subscriptions
    if (details.getSource().getCleanupSubscription()) {
        Map<String, Function.ConsumerSpec> consumerSpecMap = details.getSource().getInputSpecsMap();
        consumerSpecMap.entrySet().forEach(new Consumer<Map.Entry<String, Function.ConsumerSpec>>() {
            @Override
            public void accept(Map.Entry<String, Function.ConsumerSpec> stringConsumerSpecEntry) {

                Function.ConsumerSpec consumerSpec = stringConsumerSpecEntry.getValue();
                String topic = stringConsumerSpecEntry.getKey();

                String subscriptionName = isBlank(functionRuntimeInfo.getFunctionInstance()
                        .getFunctionMetaData().getFunctionDetails().getSource().getSubscriptionName())
                                ? InstanceUtils.getDefaultSubscriptionName(functionRuntimeInfo
                                        .getFunctionInstance().getFunctionMetaData().getFunctionDetails())
                                : functionRuntimeInfo.getFunctionInstance().getFunctionMetaData()
                                        .getFunctionDetails().getSource().getSubscriptionName();

                try {
                    RuntimeUtils.Actions.newBuilder().addAction(RuntimeUtils.Actions.Action.builder()
                            .actionName(String.format("Cleaning up subscriptions for function %s", fqfn))
                            .numRetries(10).sleepBetweenInvocationsMs(1000).supplier(() -> {
                                try {
                                    if (consumerSpec.getIsRegexPattern()) {
                                        pulsarAdmin.namespaces().unsubscribeNamespace(
                                                TopicName.get(topic).getNamespace(), subscriptionName);
                                    } else {
                                        pulsarAdmin.topics().deleteSubscription(topic, subscriptionName);
                                    }
                                } catch (PulsarAdminException e) {
                                    if (e instanceof PulsarAdminException.NotFoundException) {
                                        return RuntimeUtils.Actions.ActionResult.builder().success(true)
                                                .build();
                                    } else {
                                        // for debugging purposes
                                        List<Map<String, String>> existingConsumers = Collections.emptyList();
                                        try {
                                            TopicStats stats = pulsarAdmin.topics().getStats(topic);
                                            SubscriptionStats sub = stats.subscriptions
                                                    .get(InstanceUtils.getDefaultSubscriptionName(details));
                                            if (sub != null) {
                                                existingConsumers = sub.consumers.stream()
                                                        .map(consumerStats -> consumerStats.metadata)
                                                        .collect(Collectors.toList());
                                            }
                                        } catch (PulsarAdminException e1) {

                                        }

                                        String errorMsg = e.getHttpError() != null ? e.getHttpError()
                                                : e.getMessage();
                                        return RuntimeUtils.Actions.ActionResult.builder().success(false)
                                                .errorMsg(String.format("%s - existing consumers: %s", errorMsg,
                                                        existingConsumers))
                                                .build();
                                    }
                                }

                                return RuntimeUtils.Actions.ActionResult.builder().success(true).build();

                            }).build()).run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}