Example usage for java.lang Math min

List of usage examples for java.lang Math min

Introduction

In this page you can find the example usage for java.lang Math min.

Prototype

@HotSpotIntrinsicCandidate
public static double min(double a, double b) 

Source Link

Document

Returns the smaller of two double values.

Usage

From source file:org.eclipse.swt.snippets.Snippet51.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 51");
    shell.setBounds(10, 10, 300, 300);/*from  w  ww .j a  v  a2  s.  co  m*/
    shell.setLayout(new GridLayout(2, true));
    final Table table = new Table(shell, SWT.NONE);
    GridData data = new GridData(GridData.FILL_BOTH);
    data.horizontalSpan = 2;
    table.setLayoutData(data);
    for (int i = 0; i < 99; i++) {
        new TableItem(table, SWT.NONE).setText("item " + i);
    }
    Button upButton = new Button(shell, SWT.PUSH);
    upButton.setText("Scroll up one page");
    upButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    upButton.addListener(SWT.Selection, event -> {
        int height = table.getClientArea().height;
        int visibleItemCount = height / table.getItemHeight();
        int topIndex = table.getTopIndex();
        int newTopIndex = Math.max(0, topIndex - visibleItemCount);
        if (topIndex != newTopIndex) {
            table.setTopIndex(newTopIndex);
        }
    });
    Button downButton = new Button(shell, SWT.PUSH);
    downButton.setText("Scroll down one page");
    downButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    downButton.addListener(SWT.Selection, event -> {
        int height = table.getClientArea().height;
        int visibleItemCount = height / table.getItemHeight();
        int topIndex = table.getTopIndex();
        int newTopIndex = Math.min(table.getItemCount(), topIndex + visibleItemCount);
        if (topIndex != newTopIndex) {
            table.setTopIndex(newTopIndex);
        }
    });
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:aurelienribon.texturepackergui.Main.java

public static void main(String[] args) {
    Parameters params = new Parameters(args);
    Project project = params.project;// w w w  . ja  v  a 2s  .co  m

    if (project == null) {
        String str = "";
        str += "input=" + params.input + "\n";
        str += "output=" + params.output + "\n";
        str += params.settings;
        project = Project.fromString(str);
    }

    if (params.silent) {
        if (project.input.equals("") || project.output.equals("")) {
            System.err.println("Input and output directories have to be set");
        } else {
            try {
                project.pack();
            } catch (GdxRuntimeException ex) {
                System.err.println("Packing unsuccessful. " + ex.getMessage());
            }
        }
        return;
    }

    final Project prj = project;
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException ex) {
            } catch (InstantiationException ex) {
            } catch (IllegalAccessException ex) {
            } catch (UnsupportedLookAndFeelException ex) {
            }

            Canvas canvas = new Canvas();
            LwjglCanvas glCanvas = new LwjglCanvas(canvas, true);

            MainWindow mw = new MainWindow(prj, canvas, glCanvas.getCanvas());
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            mw.setSize(Math.min(1100, screenSize.width - 100), Math.min(670, screenSize.height - 100));
            mw.setLocationRelativeTo(null);
            mw.setVisible(true);
        }
    });
}

From source file:Snippet48.java

public static void main(String[] args) {
    Display display = new Display();
    final Shell shell = new Shell(display,
            SWT.SHELL_TRIM | SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE | SWT.V_SCROLL | SWT.H_SCROLL);
    Image originalImage = null;/* w w  w .j a  va 2  s.co  m*/
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setText("Open an image file or cancel");
    String string = dialog.open();
    if (string != null) {
        originalImage = new Image(display, string);
    }
    if (originalImage == null) {
        int width = 150, height = 200;
        originalImage = new Image(display, width, height);
        GC gc = new GC(originalImage);
        gc.fillRectangle(0, 0, width, height);
        gc.drawLine(0, 0, width, height);
        gc.drawLine(0, height, width, 0);
        gc.drawText("Default Image", 10, 10);
        gc.dispose();
    }
    final Image image = originalImage;
    final Point origin = new Point(0, 0);
    final ScrollBar hBar = shell.getHorizontalBar();
    hBar.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            int hSelection = hBar.getSelection();
            int destX = -hSelection - origin.x;
            Rectangle rect = image.getBounds();
            shell.scroll(destX, 0, 0, 0, rect.width, rect.height, false);
            origin.x = -hSelection;
        }
    });
    final ScrollBar vBar = shell.getVerticalBar();
    vBar.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            int vSelection = vBar.getSelection();
            int destY = -vSelection - origin.y;
            Rectangle rect = image.getBounds();
            shell.scroll(0, destY, 0, 0, rect.width, rect.height, false);
            origin.y = -vSelection;
        }
    });
    shell.addListener(SWT.Resize, new Listener() {
        public void handleEvent(Event e) {
            Rectangle rect = image.getBounds();
            Rectangle client = shell.getClientArea();
            hBar.setMaximum(rect.width);
            vBar.setMaximum(rect.height);
            hBar.setThumb(Math.min(rect.width, client.width));
            vBar.setThumb(Math.min(rect.height, client.height));
            int hPage = rect.width - client.width;
            int vPage = rect.height - client.height;
            int hSelection = hBar.getSelection();
            int vSelection = vBar.getSelection();
            if (hSelection >= hPage) {
                if (hPage <= 0)
                    hSelection = 0;
                origin.x = -hSelection;
            }
            if (vSelection >= vPage) {
                if (vPage <= 0)
                    vSelection = 0;
                origin.y = -vSelection;
            }
            shell.redraw();
        }
    });
    shell.addListener(SWT.Paint, new Listener() {
        public void handleEvent(Event e) {
            GC gc = e.gc;
            gc.drawImage(image, origin.x, origin.y);
            Rectangle rect = image.getBounds();
            Rectangle client = shell.getClientArea();
            int marginWidth = client.width - rect.width;
            if (marginWidth > 0) {
                gc.fillRectangle(rect.width, 0, marginWidth, client.height);
            }
            int marginHeight = client.height - rect.height;
            if (marginHeight > 0) {
                gc.fillRectangle(0, rect.height, client.width, marginHeight);
            }
        }
    });
    shell.setSize(200, 150);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:org.eclipse.swt.snippets.Snippet48.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 48");
    shell.setLayout(new FillLayout());
    Image originalImage = null;//from w w  w . j a  va2s.com
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setText("Open an image file or cancel");
    String string = dialog.open();
    if (string != null) {
        originalImage = new Image(display, string);
    }
    if (originalImage == null) {
        int width = 150, height = 200;
        originalImage = new Image(display, width, height);
        GC gc = new GC(originalImage);
        gc.fillRectangle(0, 0, width, height);
        gc.drawLine(0, 0, width, height);
        gc.drawLine(0, height, width, 0);
        gc.drawText("Default Image", 10, 10);
        gc.dispose();
    }
    final Image image = originalImage;
    final Point origin = new Point(0, 0);
    final Canvas canvas = new Canvas(shell,
            SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE | SWT.V_SCROLL | SWT.H_SCROLL);
    final ScrollBar hBar = canvas.getHorizontalBar();
    hBar.addListener(SWT.Selection, e -> {
        int hSelection = hBar.getSelection();
        int destX = -hSelection - origin.x;
        Rectangle rect = image.getBounds();
        canvas.scroll(destX, 0, 0, 0, rect.width, rect.height, false);
        origin.x = -hSelection;
    });
    final ScrollBar vBar = canvas.getVerticalBar();
    vBar.addListener(SWT.Selection, e -> {
        int vSelection = vBar.getSelection();
        int destY = -vSelection - origin.y;
        Rectangle rect = image.getBounds();
        canvas.scroll(0, destY, 0, 0, rect.width, rect.height, false);
        origin.y = -vSelection;
    });
    canvas.addListener(SWT.Resize, e -> {
        Rectangle rect = image.getBounds();
        Rectangle client = canvas.getClientArea();
        hBar.setMaximum(rect.width);
        vBar.setMaximum(rect.height);
        hBar.setThumb(Math.min(rect.width, client.width));
        vBar.setThumb(Math.min(rect.height, client.height));
        int hPage = rect.width - client.width;
        int vPage = rect.height - client.height;
        int hSelection = hBar.getSelection();
        int vSelection = vBar.getSelection();
        if (hSelection >= hPage) {
            if (hPage <= 0)
                hSelection = 0;
            origin.x = -hSelection;
        }
        if (vSelection >= vPage) {
            if (vPage <= 0)
                vSelection = 0;
            origin.y = -vSelection;
        }
        canvas.redraw();
    });
    canvas.addListener(SWT.Paint, e -> {
        GC gc = e.gc;
        gc.drawImage(image, origin.x, origin.y);
        Rectangle rect = image.getBounds();
        Rectangle client = canvas.getClientArea();
        int marginWidth = client.width - rect.width;
        if (marginWidth > 0) {
            gc.fillRectangle(rect.width, 0, marginWidth, client.height);
        }
        int marginHeight = client.height - rect.height;
        if (marginHeight > 0) {
            gc.fillRectangle(0, rect.height, client.width, marginHeight);
        }
    });
    Rectangle rect = image.getBounds();
    shell.setSize(Math.max(200, rect.width - 100), Math.max(150, rect.height - 100));
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    originalImage.dispose();
    display.dispose();
}

From source file:flink.benchmark.AdvertisingTopologyNative.java

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

    ParameterTool parameterTool = ParameterTool.fromArgs(args);

    Map conf = Utils.findAndReadConfigFile(parameterTool.getRequired("confPath"), true);
    int kafkaPartitions = ((Number) conf.get("kafka.partitions")).intValue();
    int hosts = ((Number) conf.get("process.hosts")).intValue();
    int cores = ((Number) conf.get("process.cores")).intValue();

    ParameterTool flinkBenchmarkParams = ParameterTool.fromMap(getFlinkConfs(conf));

    LOG.info("conf: {}", conf);
    LOG.info("Parameters used: {}", flinkBenchmarkParams.toMap());

    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().setGlobalJobParameters(flinkBenchmarkParams);

    // Set the buffer timeout (default 100)
    // Lowering the timeout will lead to lower latencies, but will eventually reduce throughput.
    env.setBufferTimeout(flinkBenchmarkParams.getLong("flink.buffer-timeout", 100));

    if (flinkBenchmarkParams.has("flink.checkpoint-interval")) {
        // enable checkpointing for fault tolerance
        env.enableCheckpointing(flinkBenchmarkParams.getLong("flink.checkpoint-interval", 1000));
    }//from  w  w  w . j  a v a  2s.  co  m
    // set default parallelism for all operators (recommended value: number of available worker CPU cores in the cluster (hosts * cores))
    env.setParallelism(hosts * cores);

    DataStream<String> messageStream = env
            .addSource(new FlinkKafkaConsumer082<String>(flinkBenchmarkParams.getRequired("topic"),
                    new SimpleStringSchema(), flinkBenchmarkParams.getProperties()))
            .setParallelism(Math.min(hosts * cores, kafkaPartitions));

    messageStream.rebalance()
            // Parse the String as JSON
            .flatMap(new DeserializeBolt())

            //Filter the records if event type is "view"
            .filter(new EventFilterBolt())

            // project the event
            .<Tuple2<String, String>>project(2, 5)

            // perform join with redis data
            .flatMap(new RedisJoinBolt())

            // process campaign
            .keyBy(0).flatMap(new CampaignProcessor());

    env.execute();
}

From source file:org.eclipse.swt.snippets.Snippet111.java

public static void main(String[] args) {
    final Display display = new Display();
    final Color black = display.getSystemColor(SWT.COLOR_BLACK);
    Shell shell = new Shell(display);
    shell.setText("Snippet 111");
    shell.setLayout(new FillLayout());
    final Tree tree = new Tree(shell, SWT.BORDER);
    for (int i = 0; i < 16; i++) {
        TreeItem itemI = new TreeItem(tree, SWT.NONE);
        itemI.setText("Item " + i);
        for (int j = 0; j < 16; j++) {
            TreeItem itemJ = new TreeItem(itemI, SWT.NONE);
            itemJ.setText("Item " + j);
        }// w  ww. j  av a  2 s  . co  m
    }
    final TreeItem[] lastItem = new TreeItem[1];
    final TreeEditor editor = new TreeEditor(tree);
    tree.addListener(SWT.Selection, event -> {
        final TreeItem item = (TreeItem) event.item;
        if (item != null && item == lastItem[0]) {
            boolean showBorder = true;
            final Composite composite = new Composite(tree, SWT.NONE);
            if (showBorder)
                composite.setBackground(black);
            final Text text = new Text(composite, SWT.NONE);
            final int inset = showBorder ? 1 : 0;
            composite.addListener(SWT.Resize, e1 -> {
                Rectangle rect1 = composite.getClientArea();
                text.setBounds(rect1.x + inset, rect1.y + inset, rect1.width - inset * 2,
                        rect1.height - inset * 2);
            });
            Listener textListener = e2 -> {
                switch (e2.type) {
                case SWT.FocusOut:
                    item.setText(text.getText());
                    composite.dispose();
                    break;
                case SWT.Verify:
                    String newText = text.getText();
                    String leftText = newText.substring(0, e2.start);
                    String rightText = newText.substring(e2.end, newText.length());
                    GC gc = new GC(text);
                    Point size = gc.textExtent(leftText + e2.text + rightText);
                    gc.dispose();
                    size = text.computeSize(size.x, SWT.DEFAULT);
                    editor.horizontalAlignment = SWT.LEFT;
                    Rectangle itemRect = item.getBounds(), rect2 = tree.getClientArea();
                    editor.minimumWidth = Math.max(size.x, itemRect.width) + inset * 2;
                    int left = itemRect.x, right = rect2.x + rect2.width;
                    editor.minimumWidth = Math.min(editor.minimumWidth, right - left);
                    editor.minimumHeight = size.y + inset * 2;
                    editor.layout();
                    break;
                case SWT.Traverse:
                    switch (e2.detail) {
                    case SWT.TRAVERSE_RETURN:
                        item.setText(text.getText());
                        //FALL THROUGH
                    case SWT.TRAVERSE_ESCAPE:
                        composite.dispose();
                        e2.doit = false;
                    }
                    break;
                }
            };
            text.addListener(SWT.FocusOut, textListener);
            text.addListener(SWT.Traverse, textListener);
            text.addListener(SWT.Verify, textListener);
            editor.setEditor(composite, item);
            text.setText(item.getText());
            text.selectAll();
            text.setFocus();
        }
        lastItem[0] = item;
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:org.eclipse.swt.snippets.Snippet296.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 296");
    shell.setBounds(10, 10, 300, 300);/* www .ja  v a 2 s  .c o  m*/
    final ScrolledComposite sc = new ScrolledComposite(shell, SWT.VERTICAL);
    sc.setBounds(10, 10, 280, 200);
    final int clientWidth = sc.getClientArea().width;

    final Tree tree = new Tree(sc, SWT.NONE);
    for (int i = 0; i < 99; i++) {
        TreeItem item = new TreeItem(tree, SWT.NONE);
        item.setText("item " + i);
        new TreeItem(item, SWT.NONE).setText("child");
    }
    sc.setContent(tree);
    int prefHeight = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
    tree.setSize(clientWidth, prefHeight);
    /*
     * The following listener ensures that the Tree is always large
     * enough to not need to show its own vertical scrollbar.
     */
    tree.addTreeListener(new TreeListener() {
        @Override
        public void treeExpanded(TreeEvent e) {
            int prefHeight = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
            tree.setSize(clientWidth, prefHeight);
        }

        @Override
        public void treeCollapsed(TreeEvent e) {
            int prefHeight = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
            tree.setSize(clientWidth, prefHeight);
        }
    });
    /*
     * The following listener ensures that a newly-selected item
     * in the Tree is always visible.
     */
    tree.addSelectionListener(widgetSelectedAdapter(e -> {
        TreeItem[] selectedItems = tree.getSelection();
        if (selectedItems.length > 0) {
            Rectangle itemRect = selectedItems[0].getBounds();
            Rectangle area = sc.getClientArea();
            Point origin = sc.getOrigin();
            if (itemRect.x < origin.x || itemRect.y < origin.y
                    || itemRect.x + itemRect.width > origin.x + area.width
                    || itemRect.y + itemRect.height > origin.y + area.height) {
                sc.setOrigin(itemRect.x, itemRect.y);
            }
        }
    }));
    /*
     * The following listener scrolls the Tree one item at a time
     * in response to MouseWheel events.
     */
    tree.addListener(SWT.MouseWheel, event -> {
        Point origin = sc.getOrigin();
        if (event.count < 0) {
            origin.y = Math.min(origin.y + tree.getItemHeight(), tree.getSize().y);
        } else {
            origin.y = Math.max(origin.y - tree.getItemHeight(), 0);
        }
        sc.setOrigin(origin);
    });

    Button downButton = new Button(shell, SWT.PUSH);
    downButton.setBounds(10, 220, 120, 30);
    downButton.setText("Down 10px");
    downButton.addListener(SWT.Selection, event -> sc.setOrigin(0, sc.getOrigin().y + 10));
    Button upButton = new Button(shell, SWT.PUSH);
    upButton.setBounds(140, 220, 120, 30);
    upButton.setText("Up 10px");
    upButton.addListener(SWT.Selection, event -> sc.setOrigin(0, sc.getOrigin().y - 10));
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:ImageScrollFlickerFree.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    Image originalImage = null;/*from w w w. j  ava 2  s  . c  om*/
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setText("Open an image file or cancel");
    String string = dialog.open();
    if (string != null) {
        originalImage = new Image(display, string);
    }
    if (originalImage == null) {
        int width = 150, height = 200;
        originalImage = new Image(display, width, height);
        GC gc = new GC(originalImage);
        gc.fillRectangle(0, 0, width, height);
        gc.drawLine(0, 0, width, height);
        gc.drawLine(0, height, width, 0);
        gc.drawText("Default Image", 10, 10);
        gc.dispose();
    }
    final Image image = originalImage;
    final Point origin = new Point(0, 0);
    final Canvas canvas = new Canvas(shell,
            SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE | SWT.V_SCROLL | SWT.H_SCROLL);
    final ScrollBar hBar = canvas.getHorizontalBar();
    hBar.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            int hSelection = hBar.getSelection();
            int destX = -hSelection - origin.x;
            Rectangle rect = image.getBounds();
            canvas.scroll(destX, 0, 0, 0, rect.width, rect.height, false);
            origin.x = -hSelection;
        }
    });
    final ScrollBar vBar = canvas.getVerticalBar();
    vBar.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            int vSelection = vBar.getSelection();
            int destY = -vSelection - origin.y;
            Rectangle rect = image.getBounds();
            canvas.scroll(0, destY, 0, 0, rect.width, rect.height, false);
            origin.y = -vSelection;
        }
    });
    canvas.addListener(SWT.Resize, new Listener() {
        public void handleEvent(Event e) {
            Rectangle rect = image.getBounds();
            Rectangle client = canvas.getClientArea();
            hBar.setMaximum(rect.width);
            vBar.setMaximum(rect.height);
            hBar.setThumb(Math.min(rect.width, client.width));
            vBar.setThumb(Math.min(rect.height, client.height));
            int hPage = rect.width - client.width;
            int vPage = rect.height - client.height;
            int hSelection = hBar.getSelection();
            int vSelection = vBar.getSelection();
            if (hSelection >= hPage) {
                if (hPage <= 0)
                    hSelection = 0;
                origin.x = -hSelection;
            }
            if (vSelection >= vPage) {
                if (vPage <= 0)
                    vSelection = 0;
                origin.y = -vSelection;
            }
            canvas.redraw();
        }
    });
    canvas.addListener(SWT.Paint, new Listener() {
        public void handleEvent(Event e) {
            GC gc = e.gc;
            gc.drawImage(image, origin.x, origin.y);
            Rectangle rect = image.getBounds();
            Rectangle client = canvas.getClientArea();
            int marginWidth = client.width - rect.width;
            if (marginWidth > 0) {
                gc.fillRectangle(rect.width, 0, marginWidth, client.height);
            }
            int marginHeight = client.height - rect.height;
            if (marginHeight > 0) {
                gc.fillRectangle(0, rect.height, client.width, marginHeight);
            }
        }
    });
    shell.setSize(200, 150);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    originalImage.dispose();
    display.dispose();
}

From source file:org.eclipse.swt.snippets.Snippet322.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 322");
    shell.setBounds(10, 10, 300, 300);//  w ww .  j a  v  a 2s.co  m
    final ScrolledComposite sc = new ScrolledComposite(shell, SWT.VERTICAL);
    sc.setBounds(10, 10, 280, 200);
    final int clientWidth = sc.getClientArea().width;

    final Tree tree = new Tree(sc, SWT.NONE);
    for (int i = 0; i < 99; i++) {
        TreeItem item = new TreeItem(tree, SWT.NONE);
        item.setText("item " + i);
        new TreeItem(item, SWT.NONE).setText("child");
    }
    sc.setContent(tree);
    int prefHeight = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
    tree.setSize(clientWidth, prefHeight);
    /*
     * The following listener ensures that the Tree is always large
     * enough to not need to show its own vertical scrollbar.
     */
    tree.addTreeListener(new TreeListener() {
        @Override
        public void treeExpanded(TreeEvent e) {
            int prefHeight = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
            tree.setSize(clientWidth, prefHeight);
        }

        @Override
        public void treeCollapsed(TreeEvent e) {
            int prefHeight = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
            tree.setSize(clientWidth, prefHeight);
        }
    });
    /*
     * The following listener ensures that a newly-selected item
     * in the Tree is always visible.
     */
    tree.addSelectionListener(widgetSelectedAdapter(e -> {
        TreeItem[] selectedItems = tree.getSelection();
        if (selectedItems.length > 0) {
            Rectangle itemRect = selectedItems[0].getBounds();
            Rectangle area = sc.getClientArea();
            Point origin = sc.getOrigin();
            if (itemRect.x < origin.x || itemRect.y < origin.y
                    || itemRect.x + itemRect.width > origin.x + area.width
                    || itemRect.y + itemRect.height > origin.y + area.height) {
                sc.setOrigin(itemRect.x, itemRect.y);
            }
        }
    }));
    /*
     * The following listener scrolls the Tree one item at a time
     * in response to MouseWheel events.
     */
    tree.addListener(SWT.MouseWheel, event -> {
        Point origin = sc.getOrigin();
        if (event.count < 0) {
            origin.y = Math.min(origin.y + tree.getItemHeight(), tree.getSize().y);
        } else {
            origin.y = Math.max(origin.y - tree.getItemHeight(), 0);
        }
        sc.setOrigin(origin);
    });

    Button disableButton = new Button(shell, SWT.PUSH);
    disableButton.setBounds(10, 220, 120, 30);
    disableButton.setText("Disable");
    disableButton.addListener(SWT.Selection, event -> tree.setEnabled(false));
    Button enableButton = new Button(shell, SWT.PUSH);
    enableButton.setBounds(140, 220, 120, 30);
    enableButton.setText("Enable");
    enableButton.addListener(SWT.Selection, event -> tree.setEnabled(true));

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.maxpowered.amazon.advertising.api.app.App.java

public static void main(final String... args)
        throws FileNotFoundException, IOException, JAXBException, XMLStreamException, InterruptedException {
    try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml")) {
        /*//w  w  w .  jav a 2 s.  c o  m
         * Get default options based on spring configs
         */
        final String inputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_INPUT, STD_IN_STR);
        final String processedDefault = inputDefault.equals(STD_IN_STR) ? DEFAULT_PROCESSED_FILE_BASE
                : inputDefault + PROCESSED_EXT;
        final String outputDefault = getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_OUTPUT,
                STD_OUT_STR);
        int throttleDefault = Integer.valueOf(getOptionDefaultBasedOnSpringProperty(ctx, PROPERTY_APP_THROTTLE,
                String.valueOf(DEFAULT_APP_THROTTLE)));
        // Maximum of 25000 requests per hour
        throttleDefault = Math.min(throttleDefault, MAX_APP_THROTTLE);

        /*
         * Get options from the CLI args
         */
        final Options options = new Options();

        options.addOption("h", false, "Display this help.");
        options.addOption("i", true, "Set the file to read ASINs from. " + DEFAULT_STR + inputDefault);
        options.addOption("p", true, "Set the file to store processed ASINs in. " + DEFAULT_STR
                + processedDefault + " or '" + PROCESSED_EXT + "' appended to the input file name.");
        // Add a note that the output depends on the configured processors. If none are configured, it defaults to a
        // std.out processor
        options.addOption("o", true,
                "Set the file to write fetched info xml to via FileProcessor. " + DEFAULT_STR + outputDefault);
        options.addOption("1", false, "Override output file and always output fetched info xml to std.out.");
        options.addOption("t", true, "Set the requests per hour throttle (max of " + MAX_APP_THROTTLE + "). "
                + DEFAULT_STR + throttleDefault);

        final CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        boolean needsHelp = false;

        try {
            cmd = parser.parse(options, args);
        } catch (final ParseException e) {
            needsHelp = true;
        }

        if (cmd.hasOption("h") || needsHelp) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("App", options);
            return;
        }

        // Get throttle rate
        final int throttle = Math.min(
                cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : throttleDefault,
                MAX_APP_THROTTLE);
        LOG.debug("Throttle (default {}) is {} requests per hour", throttleDefault, throttle);
        // We don't want to hit our limit, just under an hour worth of milliseconds
        final int requestWait = 3540000 / throttle;

        // Get input stream
        String input;
        if (cmd.hasOption("i")) {
            input = cmd.getOptionValue("i");
        } else {
            input = inputDefault;
        }
        LOG.debug("Input name (default {}) is {}", inputDefault, input);

        // Get processed file
        String processed;
        if (cmd.hasOption("p")) {
            processed = cmd.getOptionValue("p");
        } else {
            processed = input + PROCESSED_EXT;
        }
        LOG.debug("Processed file name (default {}) is {}", processedDefault, processed);
        final File processedFile = new File(processed);
        processedFile.createNewFile();

        try (final InputStream inputStream = getInputStream(input)) {

            // Get output stream
            String output;
            if (cmd.hasOption("o")) {
                output = cmd.getOptionValue("o");
            } else {
                output = outputDefault;
            }
            if (cmd.hasOption("1")) {
                output = STD_OUT_STR;
            }
            LOG.debug("Output (default {}) name is {}", outputDefault, output);
            // Special logic to set the FileProcessor output
            if (output.equals(STD_OUT_STR)) {
                final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class);
                fileProcessor.setOutputStream(System.out);
            } else if (!output.equals(outputDefault)) {
                final FileProcessor fileProcessor = ctx.getBeanFactory().getBean(FileProcessor.class);
                fileProcessor.setOutputFile(output);
            }

            // This could be easily configured through CLI or properties
            final List<String> responseGroups = Lists.newArrayList();
            for (final ResponseGroup responseGroup : new ResponseGroup[] { ResponseGroup.IMAGES,
                    ResponseGroup.ITEM_ATTRIBUTES }) {
                responseGroups.add(responseGroup.getResponseGroupName());
            }
            final String responseGroupString = Joiner.on(",").join(responseGroups);

            // Search the list of remaining ASINs
            final ProductFetcher fetcher = ctx.getBeanFactory().getBean(ProductFetcher.class);
            fetcher.setProcessedFile(processedFile);
            fetcher.setRequestWait(requestWait);
            fetcher.setInputStream(inputStream);
            fetcher.setResponseGroups(responseGroupString);

            // This ensures that statistics of processed asins should almost always get printed at the end
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    fetcher.logStatistics();
                }
            });

            fetcher.fetchProductInformation();
        }
    }
}