package com.example.hotel.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hotel.controller.common.BaseController;
import com.example.hotel.entity.Category;
import com.example.hotel.dto.JsonResult;
import com.example.hotel.service.CategoryService;
import com.example.hotel.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Controller
@RequestMapping(value = "/admin/category")
public class CategoryController extends BaseController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有分类并渲染category页面
     *
     * @return 模板路径admin/admin_category
     */
    @GetMapping
    public String categories(@RequestParam(value = "page", defaultValue = "0") Integer pageNumber, @RequestParam(value = "size", defaultValue = "10") Integer pageSize, @RequestParam(value = "sort", defaultValue = "cateSort") String sort, @RequestParam(value = "order", defaultValue = "desc") String order, Model model) {
        Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);
        Page<Category> categoryPage = categoryService.findAll(page);
        model.addAttribute("categories", categoryPage.getRecords());
        model.addAttribute("pageInfo", PageUtil.convertPageVo(page));
        return "admin/admin_category";
    }

    /**
     * 新增/修改分类目录
     *
     * @param category category对象
     * @return 重定向到/admin/category
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public JsonResult saveCategory(@ModelAttribute Category category) {
        categoryService.insertOrUpdate(category);
        return JsonResult.success("保存成功");
    }

    /**
     * 删除分类
     *
     * @param cateId 分类Id
     * @return JsonResult
     */
    @DeleteMapping(value = "/delete")
    @ResponseBody
    public JsonResult checkDelete(@RequestParam("id") Long cateId) {
        Integer count = categoryService.countPostByCateId(cateId);
        if (count != 0) {
            return JsonResult.error("该分类已经有了客房，无法删除");
        }
        categoryService.delete(cateId);
        return JsonResult.success("删除成功");
    }

    /**
     * 跳转到修改页面
     *
     * @param cateId cateId
     * @param model  model
     * @return 模板路径admin/admin_category
     */
    @GetMapping(value = "/edit")
    public String toEditCategory(Model model, @RequestParam(value = "page", defaultValue = "0") Integer pageNumber, @RequestParam(value = "size", defaultValue = "10") Integer pageSize, @RequestParam(value = "sort", defaultValue = "cateSort") String sort, @RequestParam(value = "order", defaultValue = "desc") String order, @RequestParam("id") Long cateId) {
        Page page = PageUtil.i

        // 更新的分类
        Category category = categoryService.get(cateId);
        if (category == null) {
            return this.renderNotFound();
        }
        model.addAttribute("updateCategory", category);
        // 所有分类
        Page<Category> categoryPage = categoryService.findAll(page);
        model.addAttribute("categories", categoryPage.getRecords());
        model.addAttribute("pageInfo", PageUtil.convertPageVo(page));
        return "admin/admin_category";
    }
}


@DeleteMapping(value = "/delete")
    @ResponseBody
    public JsonResult checkDelete(@RequestParam("id") Long cateId) {
        Integer count = categoryService.countPostByCateId(cateId);
        if (count != 0) {
            return JsonResult.error("该分类已经有了客房，无法删除");
        }
        categoryService.delete(cateId);
        return JsonResult.success("删除成功");
    }

package com.example.hotel.controller.admin;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hotel.controller.common.BaseController;
import com.example.hotel.entity.Category;
import com.example.hotel.dto.JsonResult;
import com.example.hotel.service.CategoryService;
import com.example.hotel.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Controller
@RequestMapping(value = "/admin/category")
public class CategoryController extends BaseController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有分类并渲染category页面
     *
     * @return 模板路径admin/admin_category
     */
    @GetMapping
    public String categories(@RequestParam(value = "page", defaultValue = "0") Integer pageNumber, @RequestParam(value = "size", defaultValue = "10") Integer pageSize, @RequestParam(value = "sort", defaultValue = "cateSort") String sort, @RequestParam(value = "order", defaultValue = "desc") String order, Model model) {
        Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);
        Page<Category> categoryPage = categoryService.findAll(page);
        model.addAttribute("categories", categoryPage.getRecords());
        model.addAttribute("pageInfo", PageUtil.convertPageVo(page));
        return "admin/admin_category";
    }

    /**
     * 新增/修改分类目录
     *
     * @param category category对象
     * @return 重定向到/admin/category
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public JsonResult saveCategory(@ModelAttribute Category category) {
        categoryService.insertOrUpdate(category);
        return JsonResult.success("保存成功");
    }

    /**
     * 删除分类
     *
     * @param cateId 分类Id
     * @return JsonResult
     */

    /**
     * 跳转到修改页面
     *
     * @param cateId cateId
     * @param model  model
     * @return 模板路径admin/admin_category
     */
    @GetMapping(value = "/edit")
    public String toEditCategory(Model model, @RequestParam(value = "page", defaultValue = "0") Integer pageNumber, @RequestParam(value = "size", defaultValue = "10") Integer pageSize, @RequestParam(value = "sort", defaultValue = "cateSort") String sort, @RequestParam(value = "order", defaultValue = "desc") String order, @RequestParam("id") Long cateId) {
        Page page = PageUtil.initMpPage(pageNumber, pageSize, sort, order);
        // 更新的分类
        Category category = categoryService.get(cateId);
        if (category == null) {
            return this.renderNotFound();
        }
        model.addAttribute("updateCategory", category);
        // 所有分类
        Page<Category> categoryPage = categoryService.findAll(page);
        model.addAttribute("categories", categoryPage.getRecords());
        model.addAttribute("pageInfo", PageUtil.convertPageVo(page));
        return "admin/admin_category";
    }
}


@Override
    public void start(final Stage primaryStage)

package de.gsi.chart.samples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.gsi.chart.XYChart;
import de.gsi.chart.axes.spi.DefaultNumericAxis;
import de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;
import de.gsi.chart.plugins.EditAxis;
import de.gsi.chart.plugins.Zoomer;
import de.gsi.chart.renderer.ContourType;
import de.gsi.chart.renderer.spi.ContourDataSetRenderer;
import de.gsi.chart.renderer.spi.utils.ColorGradient;
import de.gsi.chart.ui.geometry.Side;
import de.gsi.dataset.DataSet;
import de.gsi.dataset.spi.DataSetBuilder;
import de.gsi.dataset.utils.ProcessingProfiler;

/**
 * @author rstein
 */
public class ContourChartSample extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);

    private static DataSet createData() {
        final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };
        final double[] y = x;
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private static DataSet createTestData() {
        final int nPoints = 1000;
        final double f = 0.1;
        final double[] x = new double[nPoints];
        final double[] y = new double[nPoints];
        for (int i = 0; i < x.length; i++) {
            final double val = (i / (double) x.length - 0.5) * 10;
            x[i] = val;
            y[i] = val;
        }
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {
        final DefaultNumericAxis xAxis = new DefaultNumericAxis();
        xAxis.setAnimated(false);
        xAxis.setAutoRangeRounding(false);
        xAxis.setName("X Position");
        xAxis.setAutoRanging(true);
        final DefaultNumericAxis yAxis = new DefaultNumericAxis();
        yAxis.setAnimated(false);
        yAxis.setAutoRangeRounding(false);
        yAxis.setName("Y Position");
        yAxis.setAutoRanging(true);
        final DefaultNumericAxis zAxis = new DefaultNumericAxis();
        zAxis.setAnimated(false);
        zAxis.setAutoRangeRounding(false);
        zAxis.setName("z Amplitude");
        zAxis.setAutoRanging(true);
        zAxis.setSide(Side.RIGHT);
        zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);
        final XYChart chart = new XYChart(xAxis, yAxis);
        chart.getAxes().add(zAxis);
        chart.setTitle("Test data");
        chart.setAnimated(false);
        chart.getRenderers().clear();
        chart.setLegendVisible(false);
        final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();
        contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);
        chart.getRenderers().setAll(contourRenderer);
        // false: for color gradient map, true: for true contour map
        contourRenderer.setContourType(colorMap);
        contourRenderer.getDatasets().add(readImage());
        slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());
        slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());
        slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());
        slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        chart.getPlugins().add(new Zoomer());
        chart.getPlugins().add(new EditAxis());
        HBox.setHgrow(chart, Priority.ALWAYS);
        return chart;
    }

    public DataSet readImage() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream("./testdata/image.txt"))))) {
            @SuppressWarnings("unused")
            String // NOPMD variable is needed to skip/check line that contains the dimension of the following
            skipLine;
            // line to be read which we derive from the data itself
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] x = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] y = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] z = reader.readLine().split(" ");
            final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();
            final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();
            final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();
            return new DataSetBuilder("contour data").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();
        } catch (final Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.atError().setCause(e).log("data read error");
            }
        }
        return null;
    }

{
        primaryStage.setTitle("ContourChart Sample");
        // number of contour levels
        final Slider nCountourLevelSlider = new Slider(0, 100, 20);
        // number of contour segments
        final Slider nSegmentSlider = new Slider(0, 10_000, 500);
        // number of contour segments
        final Slider minHexSizeSlider = new Slider(1, 100, 5);
        final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);
        final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);
        final HBox hBox = new HBox(chartPane1, chartPane2);
        VBox.setVgrow(hBox, Priority.ALWAYS);
        final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);
        final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);
        nCountourLevelSlider.setShowTickLabels(true);
        nCountourLevelSlider.setShowTickMarks(true);
        nCountourLevelSlider.setMajorTickUnit(10);
        nCountourLevelSlider.setMinorTickCount(5);
        nCountourLevelSlider.setBlockIncrement(1);
        HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);
        final HBox hBoxSlider1 = new HBox(new Label("n countours:"), nCountourLevelSlider);
        nSegmentSlider.setShowTickLabels(true);
        nSegmentSlider.setShowTickMarks(true);
        nSegmentSlider.setMajorTickUnit(200);
        nSegmentSlider.setMinorTickCount(50);
        nSegmentSlider.setBlockIncrement(10);
        HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);
        final HBox hBoxSlider2 = new HBox(new Label("n segments :"), nSegmentSlider);
        minHexSizeSlider.setShowTickLabels(true);
        minHexSizeSlider.setShowTickMarks(true);
        minHexSizeSlider.setMajorTickUnit(10);
        minHexSizeSlider.setMinorTickCount(10);
        minHexSizeSlider.setBlockIncrement(1);
        HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);
        final HBox hBoxSlider3 = new HBox(new Label("minHexSizeSize :"), minHexSizeSlider);
        ContourChartSample.bindAxis(chartPane1, chartPane2);
        final ComboBox<ContourType> cb1 = new ComboBox<>();
        cb1.getItems().addAll(ContourType.values());
        cb1.setValue(renderer1.getContourType());
        cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ColormapComboBox colorGradient1 = new ColormapComboBox();
        colorGradient1.getItems().addAll(ColorGradient.colorGradients());
        colorGradient1.setValue(renderer1.getColorGradient());
        colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());
        colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ComboBox<ContourType> cb2 = new ComboBox<>();
        cb2.getItems().addAll(ContourType.values());
        cb2.setValue(renderer2.getContourType());
        cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final ColormapComboBox colorGradient2 = new ColormapComboBox();
        colorGradient2.setValue(renderer2.getColorGradient());
        colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());
        colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final HBox parameter = new HBox(new Label("Countour1: "), cb1, colorGradient1, new Label(" Countour2: "), cb2, colorGradient2);
        final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);
        final Scene scene = new Scene(vBox, 1600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
        primaryStage.setOnCloseRequest(evt -> Platform.exit());
    }

    private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {
        final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();
        final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();
        final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();
        final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();
        final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();
        final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();
        xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());
        yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());
        xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());
        yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());
        xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());
        yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());
        zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());
        zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());
        zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());
        zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());
        zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());
    }

    /**
     * @param args the command line arguments
     */
    public static void main(final String[] args) {
        ProcessingProfiler.setVerboseOutputState(true);
        Application.launch(args);
    }
}


{
        ProcessingProfiler.setVerboseOutputState(true);
        Application.launch(args);
    }

package de.gsi.chart.samples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.gsi.chart.XYChart;
import de.gsi.chart.axes.spi.DefaultNumericAxis;
import de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;
import de.gsi.chart.plugins.EditAxis;
import de.gsi.chart.plugins.Zoomer;
import de.gsi.chart.renderer.ContourType;
import de.gsi.chart.renderer.spi.ContourDataSetRenderer;
import de.gsi.chart.renderer.spi.utils.ColorGradient;
import de.gsi.chart.ui.geometry.Side;
import de.gsi.dataset.DataSet;
import de.gsi.dataset.spi.DataSetBuilder;
import de.gsi.dataset.utils.ProcessingProfiler;

/**
 * @author rstein
 */
public class ContourChartSample extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);

    private static DataSet createData() {
        final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };
        final double[] y = x;
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private static DataSet createTestData() {
        final int nPoints = 1000;
        final double f = 0.1;
        final double[] x = new double[nPoints];
        final double[] y = new double[nPoints];
        for (int i = 0; i < x.length; i++) {
            final double val = (i / (double) x.length - 0.5) * 10;
            x[i] = val;
            y[i] = val;
        }
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {
        final DefaultNumericAxis xAxis = new DefaultNumericAxis();
        xAxis.setAnimated(false);
        xAxis.setAutoRangeRounding(false);
        xAxis.setName("X Position");
        xAxis.setAutoRanging(true);
        final DefaultNumericAxis yAxis = new DefaultNumericAxis();
        yAxis.setAnimated(false);
        yAxis.setAutoRangeRounding(false);
        yAxis.setName("Y Position");
        yAxis.setAutoRanging(true);
        final DefaultNumericAxis zAxis = new DefaultNumericAxis();
        zAxis.setAnimated(false);
        zAxis.setAutoRangeRounding(false);
        zAxis.setName("z Amplitude");
        zAxis.setAutoRanging(true);
        zAxis.setSide(Side.RIGHT);
        zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);
        final XYChart chart = new XYChart(xAxis, yAxis);
        chart.getAxes().add(zAxis);
        chart.setTitle("Test data");
        chart.setAnimated(false);
        chart.getRenderers().clear();
        chart.setLegendVisible(false);
        final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();
        contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);
        chart.getRenderers().setAll(contourRenderer);
        // false: for color gradient map, true: for true contour map
        contourRenderer.setContourType(colorMap);
        contourRenderer.getDatasets().add(readImage());
        slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());
        slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());
        slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());
        slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        chart.getPlugins().add(new Zoomer());
        chart.getPlugins().add(new EditAxis());
        HBox.setHgrow(chart, Priority.ALWAYS);
        return chart;
    }

    public DataSet readImage() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream("./testdata/image.txt"))))) {
            @SuppressWarnings("unused")
            String // NOPMD variable is needed to skip/check line that contains the dimension of the following
            skipLine;
            // line to be read which we derive from the data itself
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] x = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] y = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] z = reader.readLine().split(" ");
            final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();
            final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();
            final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();
            return new DataSetBuilder("contour data").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();
        } catch (final Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.atError().setCause(e).log("data read error");
            }
        }
        return null;
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("ContourChart Sample");
        // number of contour levels
        final Slider nCountourLevelSlider = new Slider(0, 100, 20);
        // number of contour segments
        final Slider nSegmentSlider = new Slider(0, 10_000, 500);
        // number of contour segments
        final Slider minHexSizeSlider = new Slider(1, 100, 5);
        final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);
        final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);
        final HBox hBox = new HBox(chartPane1, chartPane2);
        VBox.setVgrow(hBox, Priority.ALWAYS);
        final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);
        final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);
        nCountourLevelSlider.setShowTickLabels(true);
        nCountourLevelSlider.setShowTickMarks(true);
        nCountourLevelSlider.setMajorTickUnit(10);
        nCountourLevelSlider.setMinorTickCount(5);
        nCountourLevelSlider.setBlockIncrement(1);
        HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);
        final HBox hBoxSlider1 = new HBox(new Label("n countours:"), nCountourLevelSlider);
        nSegmentSlider.setShowTickLabels(true);
        nSegmentSlider.setShowTickMarks(true);
        nSegmentSlider.setMajorTickUnit(200);
        nSegmentSlider.setMinorTickCount(50);
        nSegmentSlider.setBlockIncrement(10);
        HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);
        final HBox hBoxSlider2 = new HBox(new Label("n segments :"), nSegmentSlider);
        minHexSizeSlider.setShowTickLabels(true);
        minHexSizeSlider.setShowTickMarks(true);
        minHexSizeSlider.setMajorTickUnit(10);
        minHexSizeSlider.setMinorTickCount(10);
        minHexSizeSlider.setBlockIncrement(1);
        HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);
        final HBox hBoxSlider3 = new HBox(new Label("minHexSizeSize :"), minHexSizeSlider);
        ContourChartSample.bindAxis(chartPane1, chartPane2);
        final ComboBox<ContourType> cb1 = new ComboBox<>();
        cb1.getItems().addAll(ContourType.values());
        cb1.setValue(renderer1.getContourType());
        cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ColormapComboBox colorGradient1 = new ColormapComboBox();
        colorGradient1.getItems().addAll(ColorGradient.colorGradients());
        colorGradient1.setValue(renderer1.getColorGradient());
        colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());
        colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ComboBox<ContourType> cb2 = new ComboBox<>();
        cb2.getItems().addAll(ContourType.values());
        cb2.setValue(renderer2.getContourType());
        cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final ColormapComboBox colorGradient2 = new ColormapComboBox();
        colorGradient2.setValue(renderer2.getColorGradient());
        colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());
        colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final HBox parameter = new HBox(new Label("Countour1: "), cb1, colorGradient1, new Label(" Countour2: "), cb2, colorGradient2);
        final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);
        final Scene scene = new Scene(vBox, 1600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
        primaryStage.setOnCloseRequest(evt -> Platform.exit());
    }

    private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {
        final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();
        final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();
        final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();
        final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();
        final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();
        final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();
        xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());
        yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());
        xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());
        yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());
        xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());
        yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());
        zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());
        zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());
        zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());
        zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());
        zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());
    }

    /**
     * @param args the command line arguments
     */
    public static void main(final String[] args)


Box hBoxSlider2 = new HBox(new Label("n segments :"), nSegmentSlider);

package de.gsi.chart.samples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.gsi.chart.XYChart;
import de.gsi.chart.axes.spi.DefaultNumericAxis;
import de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;
import de.gsi.chart.plugins.EditAxis;
import de.gsi.chart.plugins.Zoomer;
import de.gsi.chart.renderer.ContourType;
import de.gsi.chart.renderer.spi.ContourDataSetRenderer;
import de.gsi.chart.renderer.spi.utils.ColorGradient;
import de.gsi.chart.ui.geometry.Side;
import de.gsi.dataset.DataSet;
import de.gsi.dataset.spi.DataSetBuilder;
import de.gsi.dataset.utils.ProcessingProfiler;

/**
 * @author rstein
 */
public class ContourChartSample extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);

    private static DataSet createData() {
        final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };
        final double[] y = x;
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private static DataSet createTestData() {
        final int nPoints = 1000;
        final double f = 0.1;
        final double[] x = new double[nPoints];
        final double[] y = new double[nPoints];
        for (int i = 0; i < x.length; i++) {
            final double val = (i / (double) x.length - 0.5) * 10;
            x[i] = val;
            y[i] = val;
        }
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {
        final DefaultNumericAxis xAxis = new DefaultNumericAxis();
        xAxis.setAnimated(false);
        xAxis.setAutoRangeRounding(false);
        xAxis.setName("X Position");
        xAxis.setAutoRanging(true);
        final DefaultNumericAxis yAxis = new DefaultNumericAxis();
        yAxis.setAnimated(false);
        yAxis.setAutoRangeRounding(false);
        yAxis.setName("Y Position");
        yAxis.setAutoRanging(true);
        final DefaultNumericAxis zAxis = new DefaultNumericAxis();
        zAxis.setAnimated(false);
        zAxis.setAutoRangeRounding(false);
        zAxis.setName("z Amplitude");
        zAxis.setAutoRanging(true);
        zAxis.setSide(Side.RIGHT);
        zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);
        final XYChart chart = new XYChart(xAxis, yAxis);
        chart.getAxes().add(zAxis);
        chart.setTitle("Test data");
        chart.setAnimated(false);
        chart.getRenderers().clear();
        chart.setLegendVisible(false);
        final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();
        contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);
        chart.getRenderers().setAll(contourRenderer);
        // false: for color gradient map, true: for true contour map
        contourRenderer.setContourType(colorMap);
        contourRenderer.getDatasets().add(readImage());
        slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());
        slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());
        slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());
        slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        chart.getPlugins().add(new Zoomer());
        chart.getPlugins().add(new EditAxis());
        HBox.setHgrow(chart, Priority.ALWAYS);
        return chart;
    }

    public DataSet readImage() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream("./testdata/image.txt"))))) {
            @SuppressWarnings("unused")
            String // NOPMD variable is needed to skip/check line that contains the dimension of the following
            skipLine;
            // line to be read which we derive from the data itself
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] x = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] y = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] z = reader.readLine().split(" ");
            final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();
            final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();
            final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();
            return new DataSetBuilder("contour data").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();
        } catch (final Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.atError().setCause(e).log("data read error");
            }
        }
        return null;
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("ContourChart Sample");
        // number of contour levels
        final Slider nCountourLevelSlider = new Slider(0, 100, 20);
        // number of contour segments
        final Slider nSegmentSlider = new Slider(0, 10_000, 500);
        // number of contour segments
        final Slider minHexSizeSlider = new Slider(1, 100, 5);
        final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);
        final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);
        final HBox hBox = new HBox(chartPane1, chartPane2);
        VBox.setVgrow(hBox, Priority.ALWAYS);
        final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);
        final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);
        nCountourLevelSlider.setShowTickLabels(true);
        nCountourLevelSlider.setShowTickMarks(true);
        nCountourLevelSlider.setMajorTickUnit(10);
        nCountourLevelSlider.setMinorTickCount(5);
        nCountourLevelSlider.setBlockIncrement(1);
        HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);
        final HBox hBoxSlider1 = new HBox(new Label("n countours:"), nCountourLevelSlider);
        nSegmentSlider.setShowTickLabels(true);
        nSegmentSlider.setShowTickMarks(true);
        nSegmentSlider.setMajorTickUnit(200);
        nSegmentSlider.setMinorTickCount(50);
        nSegmentSlider.setBlockIncrement(10);
        HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);
        final H

        minHexSizeSlider.setShowTickLabels(true);
        minHexSizeSlider.setShowTickMarks(true);
        minHexSizeSlider.setMajorTickUnit(10);
        minHexSizeSlider.setMinorTickCount(10);
        minHexSizeSlider.setBlockIncrement(1);
        HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);
        final HBox hBoxSlider3 = new HBox(new Label("minHexSizeSize :"), minHexSizeSlider);
        ContourChartSample.bindAxis(chartPane1, chartPane2);
        final ComboBox<ContourType> cb1 = new ComboBox<>();
        cb1.getItems().addAll(ContourType.values());
        cb1.setValue(renderer1.getContourType());
        cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ColormapComboBox colorGradient1 = new ColormapComboBox();
        colorGradient1.getItems().addAll(ColorGradient.colorGradients());
        colorGradient1.setValue(renderer1.getColorGradient());
        colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());
        colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ComboBox<ContourType> cb2 = new ComboBox<>();
        cb2.getItems().addAll(ContourType.values());
        cb2.setValue(renderer2.getContourType());
        cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final ColormapComboBox colorGradient2 = new ColormapComboBox();
        colorGradient2.setValue(renderer2.getColorGradient());
        colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());
        colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final HBox parameter = new HBox(new Label("Countour1: "), cb1, colorGradient1, new Label(" Countour2: "), cb2, colorGradient2);
        final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);
        final Scene scene = new Scene(vBox, 1600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
        primaryStage.setOnCloseRequest(evt -> Platform.exit());
    }

    private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {
        final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();
        final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();
        final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();
        final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();
        final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();
        final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();
        xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());
        yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());
        xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());
        yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());
        xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());
        yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());
        zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());
        zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());
        zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());
        zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());
        zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());
    }

    /**
     * @param args the command line arguments
     */
    public static void main(final String[] args) {
        ProcessingProfiler.setVerboseOutputState(true);
        Application.launch(args);
    }
}


public static void main(final String[] args) {
        ProcessingProfiler.setVerboseOutputState(true);
        Application.launch(args);
    }

package de.gsi.chart.samples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.gsi.chart.XYChart;
import de.gsi.chart.axes.spi.DefaultNumericAxis;
import de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;
import de.gsi.chart.plugins.EditAxis;
import de.gsi.chart.plugins.Zoomer;
import de.gsi.chart.renderer.ContourType;
import de.gsi.chart.renderer.spi.ContourDataSetRenderer;
import de.gsi.chart.renderer.spi.utils.ColorGradient;
import de.gsi.chart.ui.geometry.Side;
import de.gsi.dataset.DataSet;
import de.gsi.dataset.spi.DataSetBuilder;
import de.gsi.dataset.utils.ProcessingProfiler;

/**
 * @author rstein
 */
public class ContourChartSample extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);

    private static DataSet createData() {
        final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };
        final double[] y = x;
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private static DataSet createTestData() {
        final int nPoints = 1000;
        final double f = 0.1;
        final double[] x = new double[nPoints];
        final double[] y = new double[nPoints];
        for (int i = 0; i < x.length; i++) {
            final double val = (i / (double) x.length - 0.5) * 10;
            x[i] = val;
            y[i] = val;
        }
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {
        final DefaultNumericAxis xAxis = new DefaultNumericAxis();
        xAxis.setAnimated(false);
        xAxis.setAutoRangeRounding(false);
        xAxis.setName("X Position");
        xAxis.setAutoRanging(true);
        final DefaultNumericAxis yAxis = new DefaultNumericAxis();
        yAxis.setAnimated(false);
        yAxis.setAutoRangeRounding(false);
        yAxis.setName("Y Position");
        yAxis.setAutoRanging(true);
        final DefaultNumericAxis zAxis = new DefaultNumericAxis();
        zAxis.setAnimated(false);
        zAxis.setAutoRangeRounding(false);
        zAxis.setName("z Amplitude");
        zAxis.setAutoRanging(true);
        zAxis.setSide(Side.RIGHT);
        zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);
        final XYChart chart = new XYChart(xAxis, yAxis);
        chart.getAxes().add(zAxis);
        chart.setTitle("Test data");
        chart.setAnimated(false);
        chart.getRenderers().clear();
        chart.setLegendVisible(false);
        final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();
        contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);
        chart.getRenderers().setAll(contourRenderer);
        // false: for color gradient map, true: for true contour map
        contourRenderer.setContourType(colorMap);
        contourRenderer.getDatasets().add(readImage());
        slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());
        slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());
        slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());
        slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        chart.getPlugins().add(new Zoomer());
        chart.getPlugins().add(new EditAxis());
        HBox.setHgrow(chart, Priority.ALWAYS);
        return chart;
    }

    public DataSet readImage() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream("./testdata/image.txt"))))) {
            @SuppressWarnings("unused")
            String // NOPMD variable is needed to skip/check line that contains the dimension of the following
            skipLine;
            // line to be read which we derive from the data itself
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] x = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] y = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] z = reader.readLine().split(" ");
            final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();
            final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();
            final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();
            return new DataSetBuilder("contour data").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();
        } catch (final Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.atError().setCause(e).log("data read error");
            }
        }
        return null;
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("ContourChart Sample");
        // number of contour levels
        final Slider nCountourLevelSlider = new Slider(0, 100, 20);
        // number of contour segments
        final Slider nSegmentSlider = new Slider(0, 10_000, 500);
        // number of contour segments
        final Slider minHexSizeSlider = new Slider(1, 100, 5);
        final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);
        final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);
        final HBox hBox = new HBox(chartPane1, chartPane2);
        VBox.setVgrow(hBox, Priority.ALWAYS);
        final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);
        final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);
        nCountourLevelSlider.setShowTickLabels(true);
        nCountourLevelSlider.setShowTickMarks(true);
        nCountourLevelSlider.setMajorTickUnit(10);
        nCountourLevelSlider.setMinorTickCount(5);
        nCountourLevelSlider.setBlockIncrement(1);
        HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);
        final HBox hBoxSlider1 = new HBox(new Label("n countours:"), nCountourLevelSlider);
        nSegmentSlider.setShowTickLabels(true);
        nSegmentSlider.setShowTickMarks(true);
        nSegmentSlider.setMajorTickUnit(200);
        nSegmentSlider.setMinorTickCount(50);
        nSegmentSlider.setBlockIncrement(10);
        HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);
        final HBox hBoxSlider2 = new HBox(new Label("n segments :"), nSegmentSlider);
        minHexSizeSlider.setShowTickLabels(true);
        minHexSizeSlider.setShowTickMarks(true);
        minHexSizeSlider.setMajorTickUnit(10);
        minHexSizeSlider.setMinorTickCount(10);
        minHexSizeSlider.setBlockIncrement(1);
        HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);
        final HBox hBoxSlider3 = new HBox(new Label("minHexSizeSize :"), minHexSizeSlider);
        ContourChartSample.bindAxis(chartPane1, chartPane2);
        final ComboBox<ContourType> cb1 = new ComboBox<>();
        cb1.getItems().addAll(ContourType.values());
        cb1.setValue(renderer1.getContourType());
        cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ColormapComboBox colorGradient1 = new ColormapComboBox();
        colorGradient1.getItems().addAll(ColorGradient.colorGradients());
        colorGradient1.setValue(renderer1.getColorGradient());
        colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());
        colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ComboBox<ContourType> cb2 = new ComboBox<>();
        cb2.getItems().addAll(ContourType.values());
        cb2.setValue(renderer2.getContourType());
        cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final ColormapComboBox colorGradient2 = new ColormapComboBox();
        colorGradient2.setValue(renderer2.getColorGradient());
        colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());
        colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final HBox parameter = new HBox(new Label("Countour1: "), cb1, colorGradient1, new Label(" Countour2: "), cb2, colorGradient2);
        final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);
        final Scene scene = new Scene(vBox, 1600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
        primaryStage.setOnCloseRequest(evt -> Platform.exit());
    }

    private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {
        final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();
        final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();
        final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();
        final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();
        final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();
        final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();
        xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());
        yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());
        xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());
        yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());
        xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());
        yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());
        zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());
        zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());
        zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());
        zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());
        zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());
    }

    /**
     * @param args the command line arguments
     */


for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(y[yIndex] * x[xIndex]);
            }
        }

package de.gsi.chart.samples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.gsi.chart.XYChart;
import de.gsi.chart.axes.spi.DefaultNumericAxis;
import de.gsi.chart.plugins.ColormapSelector.ColormapComboBox;
import de.gsi.chart.plugins.EditAxis;
import de.gsi.chart.plugins.Zoomer;
import de.gsi.chart.renderer.ContourType;
import de.gsi.chart.renderer.spi.ContourDataSetRenderer;
import de.gsi.chart.renderer.spi.utils.ColorGradient;
import de.gsi.chart.ui.geometry.Side;
import de.gsi.dataset.DataSet;
import de.gsi.dataset.spi.DataSetBuilder;
import de.gsi.dataset.utils.ProcessingProfiler;

/**
 * @author rstein
 */
public class ContourChartSample extends Application {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContourChartSample.class);

    private static DataSet createData() {
        final double[] x = { -12, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12 };
        final double[] y = x;
        final double[][] z = new double[x.length][y.length];

        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private static DataSet createTestData() {
        final int nPoints = 1000;
        final double f = 0.1;
        final double[] x = new double[nPoints];
        final double[] y = new double[nPoints];
        for (int i = 0; i < x.length; i++) {
            final double val = (i / (double) x.length - 0.5) * 10;
            x[i] = val;
            y[i] = val;
        }
        final double[][] z = new double[x.length][y.length];
        for (int yIndex = 0; yIndex < y.length; yIndex++) {
            for (int xIndex = 0; xIndex < x.length; xIndex++) {
                z[xIndex][yIndex] = Math.sin(2.0 * Math.PI * f * x[xIndex]) * Math.cos(2.0 * Math.PI * f * y[yIndex]);
            }
        }
        return new DataSetBuilder("demoDataSet").setValues(DataSet.DIM_X, x).setValues(DataSet.DIM_Y, y).setValues(DataSet.DIM_Z, z).build();
    }

    private XYChart getChartPane(final Slider slider1, final Slider slider2, final Slider slider3, final ContourType colorMap) {
        final DefaultNumericAxis xAxis = new DefaultNumericAxis();
        xAxis.setAnimated(false);
        xAxis.setAutoRangeRounding(false);
        xAxis.setName("X Position");
        xAxis.setAutoRanging(true);
        final DefaultNumericAxis yAxis = new DefaultNumericAxis();
        yAxis.setAnimated(false);
        yAxis.setAutoRangeRounding(false);
        yAxis.setName("Y Position");
        yAxis.setAutoRanging(true);
        final DefaultNumericAxis zAxis = new DefaultNumericAxis();
        zAxis.setAnimated(false);
        zAxis.setAutoRangeRounding(false);
        zAxis.setName("z Amplitude");
        zAxis.setAutoRanging(true);
        zAxis.setSide(Side.RIGHT);
        zAxis.getProperties().put(Zoomer.ZOOMER_OMIT_AXIS, true);
        final XYChart chart = new XYChart(xAxis, yAxis);
        chart.getAxes().add(zAxis);
        chart.setTitle("Test data");
        chart.setAnimated(false);
        chart.getRenderers().clear();
        chart.setLegendVisible(false);
        final ContourDataSetRenderer contourRenderer = new ContourDataSetRenderer();
        contourRenderer.getAxes().addAll(xAxis, yAxis, zAxis);
        chart.getRenderers().setAll(contourRenderer);
        // false: for color gradient map, true: for true contour map
        contourRenderer.setContourType(colorMap);
        contourRenderer.getDatasets().add(readImage());
        slider1.valueProperty().bindBidirectional(contourRenderer.quantisationLevelsProperty());
        slider1.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider2.valueProperty().bindBidirectional(contourRenderer.maxContourSegmentsProperty());
        slider2.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        slider3.valueProperty().bindBidirectional(contourRenderer.minHexTileSizeProperty());
        slider3.valueProperty().addListener((ch, o, n) -> chart.requestLayout());
        chart.getPlugins().add(new Zoomer());
        chart.getPlugins().add(new EditAxis());
        HBox.setHgrow(chart, Priority.ALWAYS);
        return chart;
    }

    public DataSet readImage() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(ContourChartSample.class.getResourceAsStream("./testdata/image.txt"))))) {
            @SuppressWarnings("unused")
            String // NOPMD variable is needed to skip/check line that contains the dimension of the following
            skipLine;
            // line to be read which we derive from the data itself
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] x = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] y = reader.readLine().split(" ");
            if ((skipLine = reader.readLine()) == null) {
                throw new IllegalStateException("expected non-null line");
            }
            final String[] z = reader.readLine().split(" ");
            final double[] xValues = Arrays.stream(x).mapToDouble(Double::valueOf).toArray();
            final double[] yValues = Arrays.stream(y).mapToDouble(Double::valueOf).toArray();
            final double[] zValues = Arrays.stream(z).mapToDouble(Double::valueOf).toArray();
            return new DataSetBuilder("contour data").setValues(DataSet.DIM_X, xValues).setValues(DataSet.DIM_Y, yValues).setValues(DataSet.DIM_Z, zValues).build();
        } catch (final Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.atError().setCause(e).log("data read error");
            }
        }
        return null;
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("ContourChart Sample");
        // number of contour levels
        final Slider nCountourLevelSlider = new Slider(0, 100, 20);
        // number of contour segments
        final Slider nSegmentSlider = new Slider(0, 10_000, 500);
        // number of contour segments
        final Slider minHexSizeSlider = new Slider(1, 100, 5);
        final XYChart chartPane1 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.CONTOUR);
        final XYChart chartPane2 = getChartPane(nCountourLevelSlider, nSegmentSlider, minHexSizeSlider, ContourType.HEATMAP);
        final HBox hBox = new HBox(chartPane1, chartPane2);
        VBox.setVgrow(hBox, Priority.ALWAYS);
        final ContourDataSetRenderer renderer1 = (ContourDataSetRenderer) chartPane1.getRenderers().get(0);
        final ContourDataSetRenderer renderer2 = (ContourDataSetRenderer) chartPane2.getRenderers().get(0);
        nCountourLevelSlider.setShowTickLabels(true);
        nCountourLevelSlider.setShowTickMarks(true);
        nCountourLevelSlider.setMajorTickUnit(10);
        nCountourLevelSlider.setMinorTickCount(5);
        nCountourLevelSlider.setBlockIncrement(1);
        HBox.setHgrow(nCountourLevelSlider, Priority.ALWAYS);
        final HBox hBoxSlider1 = new HBox(new Label("n countours:"), nCountourLevelSlider);
        nSegmentSlider.setShowTickLabels(true);
        nSegmentSlider.setShowTickMarks(true);
        nSegmentSlider.setMajorTickUnit(200);
        nSegmentSlider.setMinorTickCount(50);
        nSegmentSlider.setBlockIncrement(10);
        HBox.setHgrow(nSegmentSlider, Priority.ALWAYS);
        final HBox hBoxSlider2 = new HBox(new Label("n segments :"), nSegmentSlider);
        minHexSizeSlider.setShowTickLabels(true);
        minHexSizeSlider.setShowTickMarks(true);
        minHexSizeSlider.setMajorTickUnit(10);
        minHexSizeSlider.setMinorTickCount(10);
        minHexSizeSlider.setBlockIncrement(1);
        HBox.setHgrow(minHexSizeSlider, Priority.ALWAYS);
        final HBox hBoxSlider3 = new HBox(new Label("minHexSizeSize :"), minHexSizeSlider);
        ContourChartSample.bindAxis(chartPane1, chartPane2);
        final ComboBox<ContourType> cb1 = new ComboBox<>();
        cb1.getItems().addAll(ContourType.values());
        cb1.setValue(renderer1.getContourType());
        cb1.valueProperty().bindBidirectional(renderer1.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ColormapComboBox colorGradient1 = new ColormapComboBox();
        colorGradient1.getItems().addAll(ColorGradient.colorGradients());
        colorGradient1.setValue(renderer1.getColorGradient());
        colorGradient1.valueProperty().bindBidirectional(renderer1.colorGradientProperty());
        colorGradient1.valueProperty().addListener((ch, old, selection) -> chartPane1.requestLayout());
        final ComboBox<ContourType> cb2 = new ComboBox<>();
        cb2.getItems().addAll(ContourType.values());
        cb2.setValue(renderer2.getContourType());
        cb2.valueProperty().bindBidirectional(renderer2.contourTypeProperty());
        cb1.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final ColormapComboBox colorGradient2 = new ColormapComboBox();
        colorGradient2.setValue(renderer2.getColorGradient());
        colorGradient2.valueProperty().bindBidirectional(renderer2.colorGradientProperty());
        colorGradient2.valueProperty().addListener((ch, old, selection) -> chartPane2.requestLayout());
        final HBox parameter = new HBox(new Label("Countour1: "), cb1, colorGradient1, new Label(" Countour2: "), cb2, colorGradient2);
        final VBox vBox = new VBox(hBox, hBoxSlider1, hBoxSlider2, hBoxSlider3, parameter);
        final Scene scene = new Scene(vBox, 1600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
        primaryStage.setOnCloseRequest(evt -> Platform.exit());
    }

    private static void bindAxis(final XYChart chartPane1, final XYChart chartPane2) {
        final DefaultNumericAxis xAxis1 = (DefaultNumericAxis) chartPane1.getXAxis();
        final DefaultNumericAxis yAxis1 = (DefaultNumericAxis) chartPane1.getYAxis();
        final DefaultNumericAxis xAxis2 = (DefaultNumericAxis) chartPane2.getXAxis();
        final DefaultNumericAxis yAxis2 = (DefaultNumericAxis) chartPane2.getYAxis();
        final DefaultNumericAxis zAxis1 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane1.getRenderers().get(0)).getZAxis();
        final DefaultNumericAxis zAxis2 = (DefaultNumericAxis) ((ContourDataSetRenderer) chartPane2.getRenderers().get(0)).getZAxis();
        xAxis1.autoRangingProperty().bindBidirectional(xAxis2.autoRangingProperty());
        yAxis1.autoRangingProperty().bindBidirectional(yAxis2.autoRangingProperty());
        xAxis1.maxProperty().bindBidirectional(xAxis2.maxProperty());
        yAxis1.maxProperty().bindBidirectional(yAxis2.maxProperty());
        xAxis1.minProperty().bindBidirectional(xAxis2.minProperty());
        yAxis1.minProperty().bindBidirectional(yAxis2.minProperty());
        zAxis1.autoRangingProperty().bindBidirectional(zAxis2.autoRangingProperty());
        zAxis1.autoGrowRangingProperty().bindBidirectional(zAxis2.autoGrowRangingProperty());
        zAxis1.invertAxisProperty().bindBidirectional(zAxis2.invertAxisProperty());
        zAxis1.maxProperty().bindBidirectional(zAxis2.maxProperty());
        zAxis1.minProperty().bindBidirectional(zAxis2.minProperty());
    }

    /**
     * @param args the command line arguments
     */
    public static void main(final String[] args) {
        ProcessingProfiler.setVerboseOutputState(true);
        Application.launch(args);
    }
}


public ZooKeeperEphemeralStoreBuilder<T> setUseNewWatcher(boolean useNewWatcher)

package com.linkedin.d2.discovery.stores.zk.builder;

import com.linkedin.d2.discovery.PropertySerializer;
import com.linkedin.d2.discovery.stores.zk.ZKConnection;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;
import com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;
import com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import javax.annotation.Nullable;

/**
 * Builder class for {@link ZooKeeperEphemeralStore}
 *
 * @author Francesco Capponi (example@nnthink.com)
 */
public class ZooKeeperEphemeralStoreBuilder<T> implements ZooKeeperStoreBuilder<ZooKeeperEphemeralStore<T>> {

    private static final String URIS_VALUES_DIRECTORY = "urisValues";

    private ZKConnection _client;

    private PropertySerializer<T> _serializer;

    private ZooKeeperPropertyMerger<T> _merger;

    private String _path;

    private boolean _watchChildNodes = false;

    private boolean _useNewWatcher = false;

    private String _fsD2DirPathForBackup = null;

    private ScheduledExecutorService _executorService;

    private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;

    private ZookeeperChildFilter _zookeeperChildFilter = null;

    private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;

    private List<Consumer<ZooKeeperEphemeralStore<T>>> _onBuildListeners = new ArrayList<>();

    @Override
    public void setZkConnection(ZKConnection client) {
        _client = client;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setSerializer(PropertySerializer<T> serializer) {
        _serializer = serializer;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setMerger(ZooKeeperPropertyMerger<T> merger) {
        _merger = merger;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setPath(String path) {
        _path = path;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setWatchChildNodes(boolean watchChildNodes) {
        _watchChildNodes = watchChildNodes;
        return this;
    }

{
        _useNewWatcher = useNewWatcher;
        return this;
    }

    /**
     * Set null to disable
     */
    public ZooKeeperEphemeralStoreBuilder<T> setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {
        _fsD2DirPathForBackup = fsd2DirPathForBackup;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setExecutorService(ScheduledExecutorService executorService) {
        this._executorService = executorService;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperReadWindowMs(int zookeeperReadWindowMs) {
        this._zookeeperReadWindowMs = zookeeperReadWindowMs;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {
        this._zookeeperChildFilter = zookeeperChildFilter;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator) {
        this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;
        return this;
    }

    @Override
    public ZooKeeperEphemeralStoreBuilder<T> addOnBuildListener(Consumer<ZooKeeperEphemeralStore<T>> onBuildListener) {
        _onBuildListeners.add(onBuildListener);
        return this;
    }

    @Override
    public ZooKeeperEphemeralStore<T> build() {
        String backupStoreFilePath = null;
        if (_fsD2DirPathForBackup != null) {
            backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;
        }
        ZooKeeperEphemeralStore<T> zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);
        for (Consumer<ZooKeeperEphemeralStore<T>> onBuildListener : _onBuildListeners) {
            onBuildListener.accept(zooKeeperEphemeralStore);
        }
        return zooKeeperEphemeralStore;
    }
}


{
        this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;
        return this;
    }

package com.linkedin.d2.discovery.stores.zk.builder;

import com.linkedin.d2.discovery.PropertySerializer;
import com.linkedin.d2.discovery.stores.zk.ZKConnection;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;
import com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;
import com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import javax.annotation.Nullable;

/**
 * Builder class for {@link ZooKeeperEphemeralStore}
 *
 * @author Francesco Capponi (example@nnthink.com)
 */
public class ZooKeeperEphemeralStoreBuilder<T> implements ZooKeeperStoreBuilder<ZooKeeperEphemeralStore<T>> {

    private static final String URIS_VALUES_DIRECTORY = "urisValues";

    private ZKConnection _client;

    private PropertySerializer<T> _serializer;

    private ZooKeeperPropertyMerger<T> _merger;

    private String _path;

    private boolean _watchChildNodes = false;

    private boolean _useNewWatcher = false;

    private String _fsD2DirPathForBackup = null;

    private ScheduledExecutorService _executorService;

    private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;

    private ZookeeperChildFilter _zookeeperChildFilter = null;

    private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;

    private List<Consumer<ZooKeeperEphemeralStore<T>>> _onBuildListeners = new ArrayList<>();

    @Override
    public void setZkConnection(ZKConnection client) {
        _client = client;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setSerializer(PropertySerializer<T> serializer) {
        _serializer = serializer;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setMerger(ZooKeeperPropertyMerger<T> merger) {
        _merger = merger;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setPath(String path) {
        _path = path;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setWatchChildNodes(boolean watchChildNodes) {
        _watchChildNodes = watchChildNodes;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setUseNewWatcher(boolean useNewWatcher) {
        _useNewWatcher = useNewWatcher;
        return this;
    }

    /**
     * Set null to disable
     */
    public ZooKeeperEphemeralStoreBuilder<T> setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {
        _fsD2DirPathForBackup = fsd2DirPathForBackup;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setExecutorService(ScheduledExecutorService executorService) {
        this._executorService = executorService;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperReadWindowMs(int zookeeperReadWindowMs) {
        this._zookeeperReadWindowMs = zookeeperReadWindowMs;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {
        this._zookeeperChildFilter = zookeeperChildFilter;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator)

    @Override
    public ZooKeeperEphemeralStoreBuilder<T> addOnBuildListener(Consumer<ZooKeeperEphemeralStore<T>> onBuildListener) {
        _onBuildListeners.add(onBuildListener);
        return this;
    }

    @Override
    public ZooKeeperEphemeralStore<T> build() {
        String backupStoreFilePath = null;
        if (_fsD2DirPathForBackup != null) {
            backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;
        }
        ZooKeeperEphemeralStore<T> zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);
        for (Consumer<ZooKeeperEphemeralStore<T>> onBuildListener : _onBuildListeners) {
            onBuildListener.accept(zooKeeperEphemeralStore);
        }
        return zooKeeperEphemeralStore;
    }
}


package com.linkedin.d2.discovery.stores.zk.builder;

import com.linkedin.d2.discovery.PropertySerializer;
import com.linkedin.d2.discovery.stores.zk.ZKConnection;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;
import com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;
import com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import javax.annotation.Nullable;

/**
 * Builder class for {@link ZooKeeperEphemeralStore}
 *
 * @author Francesco Capponi (example@nnthink.com)
 */
public class ZooKeeperEphemeralStoreBuilder<T> implements ZooKeeperStoreBuilder<ZooKeeperEphemeralStore<T>> {

    private static final String URIS_VALUES_DIRECTORY = "urisValues";

    private ZKConnection _client;

    private PropertySerializer<T> _serializer;

    private ZooKeeperPropertyMerger<T> _merger;

    private String _path;

    private boolean _watchChildNodes = false;

    private boolean _useNewWatcher = false;

    private String _fsD2DirPathForBackup = null;

    private ScheduledExecutorService _executorService;

    private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;

    private ZookeeperChildFilter _zookeeperChildFilter = null;

    private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;

    private List<Consumer<ZooKeeperEphemeralStore<T>>> _onBuildListeners = new ArrayList<>();

    @Override
    public void setZkConnection(ZKConnection client) {
        _client = client;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setSerializer(PropertySerializer<T> serializer) {
        _serializer = serializer;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setMerger(ZooKeeperPropertyMerger<T> merger) {
        _merger = merger;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setPath(String path) {
        _path = path;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setWatchChildNodes(boolean watchChildNodes) {
        _watchChildNodes = watchChildNodes;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setUseNewWatcher(boolean useNewWatcher) {
        _useNewWatcher = useNewWatcher;
        return this;
    }

    /**
     * Set null to disable
     */
    public ZooKeeperEphemeralStoreBuilder<T> setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {
        _fsD2DirPathForBackup = fsd2DirPathForBackup;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setExecutorService(ScheduledExecutorService executorService) {
        this._executorService = executorService;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperReadWindowMs(int zookeeperReadWindowMs) {
        this._zookeeperReadWindowMs = zookeeperReadWindowMs;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {
        this._zookeeperChildFilter = zooke

        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator) {
        this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;
        return this;
    }

    @Override
    public ZooKeeperEphemeralStoreBuilder<T> addOnBuildListener(Consumer<ZooKeeperEphemeralStore<T>> onBuildListener) {
        _onBuildListeners.add(onBuildListener);
        return this;
    }

    @Override
    public ZooKeeperEphemeralStore<T> build() {
        String backupStoreFilePath = null;
        if (_fsD2DirPathForBackup != null) {
            backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;
        }
        ZooKeeperEphemeralStore<T> zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);
        for (Consumer<ZooKeeperEphemeralStore<T>> onBuildListener : _onBuildListeners) {
            onBuildListener.accept(zooKeeperEphemeralStore);
        }
        return zooKeeperEphemeralStore;
    }
}


public ZooKeeperEphemeralStoreBuilder<T> setBackupStoreFilePath(@Nullable String fsd2DirPathForBackup) {
        _fsD2DirPathForBackup = fsd2DirPathForBackup;
        return this;
    }

package com.linkedin.d2.discovery.stores.zk.builder;

import com.linkedin.d2.discovery.PropertySerializer;
import com.linkedin.d2.discovery.stores.zk.ZKConnection;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperPropertyMerger;
import com.linkedin.d2.discovery.stores.zk.ZooKeeperStore;
import com.linkedin.d2.discovery.stores.zk.ZookeeperChildFilter;
import com.linkedin.d2.discovery.stores.zk.ZookeeperEphemeralPrefixGenerator;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import javax.annotation.Nullable;

/**
 * Builder class for {@link ZooKeeperEphemeralStore}
 *
 * @author Francesco Capponi (example@nnthink.com)
 */
public class ZooKeeperEphemeralStoreBuilder<T> implements ZooKeeperStoreBuilder<ZooKeeperEphemeralStore<T>> {

    private static final String URIS_VALUES_DIRECTORY = "urisValues";

    private ZKConnection _client;

    private PropertySerializer<T> _serializer;

    private ZooKeeperPropertyMerger<T> _merger;

    private String _path;

    private boolean _watchChildNodes = false;

    private boolean _useNewWatcher = false;

    private String _fsD2DirPathForBackup = null;

    private ScheduledExecutorService _executorService;

    private int _zookeeperReadWindowMs = ZooKeeperStore.DEFAULT_READ_WINDOW_MS;

    private ZookeeperChildFilter _zookeeperChildFilter = null;

    private ZookeeperEphemeralPrefixGenerator _zookeeperEphemeralPrefixGenerator = null;

    private List<Consumer<ZooKeeperEphemeralStore<T>>> _onBuildListeners = new ArrayList<>();

    @Override
    public void setZkConnection(ZKConnection client) {
        _client = client;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setSerializer(PropertySerializer<T> serializer) {
        _serializer = serializer;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setMerger(ZooKeeperPropertyMerger<T> merger) {
        _merger = merger;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setPath(String path) {
        _path = path;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setWatchChildNodes(boolean watchChildNodes) {
        _watchChildNodes = watchChildNodes;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setUseNewWatcher(boolean useNewWatcher) {
        _useNewWatcher = useNewWatcher;
        return this;
    }

    /**
     * Set null to disable
     */

    public ZooKeeperEphemeralStoreBuilder<T> setExecutorService(ScheduledExecutorService executorService) {
        this._executorService = executorService;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperReadWindowMs(int zookeeperReadWindowMs) {
        this._zookeeperReadWindowMs = zookeeperReadWindowMs;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperChildFilter(ZookeeperChildFilter zookeeperChildFilter) {
        this._zookeeperChildFilter = zookeeperChildFilter;
        return this;
    }

    public ZooKeeperEphemeralStoreBuilder<T> setZookeeperEphemeralPrefixGenerator(ZookeeperEphemeralPrefixGenerator zookeeperEphemeralPrefixGenerator) {
        this._zookeeperEphemeralPrefixGenerator = zookeeperEphemeralPrefixGenerator;
        return this;
    }

    @Override
    public ZooKeeperEphemeralStoreBuilder<T> addOnBuildListener(Consumer<ZooKeeperEphemeralStore<T>> onBuildListener) {
        _onBuildListeners.add(onBuildListener);
        return this;
    }

    @Override
    public ZooKeeperEphemeralStore<T> build() {
        String backupStoreFilePath = null;
        if (_fsD2DirPathForBackup != null) {
            backupStoreFilePath = _fsD2DirPathForBackup + File.separator + URIS_VALUES_DIRECTORY;
        }
        ZooKeeperEphemeralStore<T> zooKeeperEphemeralStore = new ZooKeeperEphemeralStore<>(_client, _serializer, _merger, _path, _watchChildNodes, _useNewWatcher, backupStoreFilePath, _executorService, _zookeeperReadWindowMs, _zookeeperChildFilter, _zookeeperEphemeralPrefixGenerator);
        for (Consumer<ZooKeeperEphemeralStore<T>> onBuildListener : _onBuildListeners) {
            onBuildListener.accept(zooKeeperEphemeralStore);
        }
        return zooKeeperEphemeralStore;
    }
}


@Override
    protected void onCreate(Bundle savedInstanceState)

package com.coder.guoy.recyclerview.ui;

import android.os.Bundle;
import com.coder.guoy.recyclerview.R;
import com.coder.guoy.recyclerview.base.MvvmBaseActivity;
import com.coder.guoy.recyclerview.databinding.ActivityPlayMusicBinding;

/**
 * @Version:v1.0
 * @Author:Guoy
 * @CreateTime:2017年6月5日
 * @Descrpiton:自定义条形图
 */
public class PlayMusic extends MvvmBaseActivity<ActivityPlayMusicBinding> {

{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_music);
        showContentView();
        setTitle("自定义条形图");
    }
}


{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_music);
        showContentView();
        setTitle("自定义条形图");
    }

package com.coder.guoy.recyclerview.ui;

import android.os.Bundle;
import com.coder.guoy.recyclerview.R;
import com.coder.guoy.recyclerview.base.MvvmBaseActivity;
import com.coder.guoy.recyclerview.databinding.ActivityPlayMusicBinding;

/**
 * @Version:v1.0
 * @Author:Guoy
 * @CreateTime:2017年6月5日
 * @Descrpiton:自定义条形图
 */
public class PlayMusic extends MvvmBaseActivity<ActivityPlayMusicBinding> {

    @Override
    protected void onCreate(Bundle savedInstanceState)


package com.coder.guoy.recyclerview.ui;

import android.os.Bundle;
import com.coder.guoy.recyclerview.R;
import com.coder.guoy.recyclerview.base.MvvmBaseActivity;
import com.coder.guoy.recyclerview.databinding.ActivityPlayMusicBinding;

/**
 * @Version:v1.0
 * @Author:Guoy
 * @CreateTime:2017年6月5日
 * @Descrpiton:自定义条形图
 */
public class PlayMusic extends MvvmBaseActivity<ActivityPlayMusicBinding> {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_music);
        showContentView();
        set


public static void main(String[] args) throws Exception

{
        try {
            Cloneable ret = (Cloneable) new Object();
            for (int j = 0; j < 0; j++) {
                ret = new byte[0];
            }
            Cloneable tt = (Cloneable) ret;
        } catch (ClassCastException e) {
            System.out.println("Expected exception was thrown:");
            e.printStackTrace();
            System.out.println("PASSED!");
        } catch (Throwable e) {
            System.out.println("Unexpected exception was thrown:");
            e.printStackTrace();
            System.out.println("FAILED");
            System.exit(-99);
        }
    }
}


for (int j = 0; j < 0; j++) {
                ret = new byte[0];
            }

public class Test {

    public static void main(String[] args) throws Exception {
        try {
            Cloneable ret = (Cloneable) new Object();

            Cloneable tt = (Cloneable) ret;
        } catch (ClassCastException e) {
            System.out.println("Expected exception was thrown:");
            e.printStackTrace();
            System.out.println("PASSED!");
        } catch (Throwable e) {
            System.out.println("Unexpected exception was thrown:");
            e.printStackTrace();
            System.out.println("FAILED");
            System.exit(-99);
        }
    }
}


public void myConsumer() throws Exception

package com.jian8.juc.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ProdConsumer_BlockQueueDemo {

    public static void main(String[] args) {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t生产线程启动");
            try {
                myResource.myProd();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Prod").start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t消费线程启动");
            try {
                myResource.myConsumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Consumer").start();
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("5s后main叫停，线程结束");
        try {
            myResource.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyResource {

    // 默认开启，进行生产+消费
    private volatile boolean flag = true;

    private AtomicInteger atomicInteger = new AtomicInteger();

    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    public void myProd() throws Exception {
        String data = null;
        boolean retValue;
        while (flag) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + data + "成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + data + "失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t大老板叫停了，flag=false，生产结束");
    }

{
        String result = null;
        while (flag) {
            result = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (null == result || result.equalsIgnoreCase("")) {
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t超过2s没有取到蛋糕，消费退出");
                System.out.println();
                return;
            }
            System.out.println(Thread.currentThread().getName() + "\t消费队列" + result + "成功");
        }
    }

    public void stop() throws Exception {
        flag = false;
    }
}


{
        String result = null;
        while (flag) {
            result = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (null == result || result.equalsIgnoreCase("")) {
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t超过2s没有取到蛋糕，消费退出");
                System.out.println();
                return;
            }
            System.out.println(Thread.currentThread().getName() + "\t消费队列" + result + "成功");
        }
    }

package com.jian8.juc.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ProdConsumer_BlockQueueDemo {

    public static void main(String[] args) {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t生产线程启动");
            try {
                myResource.myProd();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Prod").start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t消费线程启动");
            try {
                myResource.myConsumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Consumer").start();
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("5s后main叫停，线程结束");
        try {
            myResource.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyResource {

    // 默认开启，进行生产+消费
    private volatile boolean flag = true;

    private AtomicInteger atomicInteger = new AtomicInteger();

    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    public void myProd() throws Exception {
        String data = null;
        boolean retValue;
        while (flag) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + data + "成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + data + "失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName() + "\t大老板叫停了，flag=false，生产结束");
    }

    public void myConsumer() throws Exception

    public void stop() throws Exception {
        flag = false;
    }
}


package com.jian8.juc.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ProdConsumer_BlockQueueDemo {

    public static void main(String[] args) {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t生产线程启动");
            try {
                myResource.myProd();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Prod").start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t消费线程启动");
            try {
                myResource.myConsumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Consumer").start();
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("5s后main叫停，线程结束");
        try {
            myResource.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyResource {

    // 默认开启，进行生产+消费
    private volatile boolean flag = true;

    private AtomicInteger atomicInteger = new AtomicInteger();

    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    public void myProd() throws Exception {
        String data = null;
        boolean retValue;
        while (flag) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + data + "成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "\t插入队列" + data + "失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().g

    }

    public void myConsumer() throws Exception {
        String result = null;
        while (flag) {
            result = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (null == result || result.equalsIgnoreCase("")) {
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t超过2s没有取到蛋糕，消费退出");
                System.out.println();
                return;
            }
            System.out.println(Thread.currentThread().getName() + "\t消费队列" + result + "成功");
        }
    }

    public void stop() throws Exception {
        flag = false;
    }
}