RemotePrinterStatusRefresh.java 18.0 KB
Newer Older
1
/*
2
 * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

24
/*
25
 * @test
26
 * @bug 8153732 8212202 8221263 8221412 8222108
27 28
 * @requires (os.family == "Windows")
 * @summary Windows remote printer changes do not reflect in lookupPrintServices()
29
 * @run main/manual/othervm -Dsun.java2d.print.minRefreshTime=120 RemotePrinterStatusRefresh
30 31
 */

32 33 34 35
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
36
import java.awt.event.ActionEvent;
37 38 39 40 41
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
42
import java.util.concurrent.CountDownLatch;
43 44 45
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.swing.AbstractListModel;
46 47
import javax.swing.BorderFactory;
import javax.swing.Box;
48 49 50
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.GroupLayout;
51 52 53
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
54
import javax.swing.JList;
55
import javax.swing.JPanel;
56
import javax.swing.JScrollPane;
57
import javax.swing.JTextArea;
58
import javax.swing.JTextField;
59
import javax.swing.SwingUtilities;
60
import javax.swing.Timer;
61

62 63 64 65
import static javax.swing.BorderFactory.createTitledBorder;

public class RemotePrinterStatusRefresh extends WindowAdapter {

66 67 68
    private static final long DEFAULT_REFRESH_TIME = 240L;
    private static final long MINIMAL_REFRESH_TIME = 120L;

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    private static final long refreshTime = getRefreshTime();

    private static final long TIMEOUT = refreshTime * 4 + 60;


    private static final CountDownLatch latch = new CountDownLatch(1);
    private static volatile RemotePrinterStatusRefresh test;

    private volatile boolean testResult;
    private volatile boolean testTimedOut;

    private final JFrame frame;

    private JButton refreshButton;
    private JButton passButton;
    private JButton failButton;

    private final ServiceItemListModel beforeList;
    private final ServiceItemListModel afterList;

    private JTextField nextRefresh;
    private JTextField timeLeft;

    private final Timer timer;
    private final long startTime;


    private static class ServiceItem {
        private enum State {
            REMOVED, UNCHANGED, ADDED
99 100
        }

101 102 103 104 105 106
        final String name;
        State state;

        private ServiceItem(final String name) {
            this.name = name;
            state = State.UNCHANGED;
107 108
        }

109 110 111
        @Override
        public String toString() {
            return name;
112 113
        }

114 115 116 117 118
        @Override
        public boolean equals(Object obj) {
            return (obj instanceof ServiceItem)
                    && ((ServiceItem) obj).name.equals(name);
        }
119

120 121 122 123
        @Override
        public int hashCode() {
            return name.hashCode();
        }
124 125
    }

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    private static class ServiceItemListModel extends AbstractListModel<ServiceItem> {
        private final List<ServiceItem> list;

        private ServiceItemListModel(List<ServiceItem> list) {
            this.list = list;
        }

        @Override
        public int getSize() {
            return list.size();
        }

        @Override
        public ServiceItem getElementAt(int index) {
            return list.get(index);
        }

        private void refreshList(List<ServiceItem> newList) {
            list.clear();
            list.addAll(newList);
            fireChanged();
147 148
        }

149 150
        private void fireChanged() {
            fireContentsChanged(this, 0, list.size() - 1);
151 152 153
        }
    }

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    private static class ServiceItemListRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list,
                                                      Object value,
                                                      int index,
                                                      boolean isSelected,
                                                      boolean cellHasFocus) {
            Component component =
                    super.getListCellRendererComponent(list, value, index,
                                                       isSelected, cellHasFocus);
            switch (((ServiceItem) value).state) {
                case REMOVED:
                    component.setBackground(Color.RED);
                    component.setForeground(Color.WHITE);
                    break;
                case ADDED:
                    component.setBackground(Color.GREEN);
                    component.setForeground(Color.BLACK);
                    break;
                case UNCHANGED:
                default:
                    break;
176
            }
177
            return component;
178 179 180
        }
    }

181 182 183 184 185 186
    private static final String INSTRUCTIONS_TEXT =
            "Please follow the steps for this manual test:\n"
                    + "Step 0: \"Before\" list is populated with currently "
                    +          "configured printers.\n"
                    + "Step 1: Add or Remove a network printer using "
                    +          "Windows Control Panel.\n"
187
                    + "Step 2: Wait for 2\u20134 minutes after adding or removing.\n"
188 189 190 191 192 193 194 195 196 197 198 199 200
                    + "             \"Next printer refresh in\" gives you a "
                    +          "rough estimation on when update will happen.\n"
                    + "Step 3: Click Refresh."
                    +          "\"After\" list is populated with updated list "
                    +          "of printers.\n"
                    + "Step 4: Compare the list of printers in \"Before\" and "
                    +          "\"After\" lists.\n"
                    + "              Added printers are highlighted with "
                    +               "green color, removed ones \u2014 with "
                    +               "red color.\n"
                    + "Step 5: Click Pass if the list of printers is correctly "
                    +          "updated.\n"
                    + "Step 6: If the list is not updated, wait for another "
201
                    +          "2\u20134 minutes, and then click Refresh again.\n"
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
                    + "Step 7: If the list does not update, click Fail.\n"
                    + "\n"
                    + "You have to click Refresh to enable Pass and Fail buttons. "
                    + "If no button is pressed,\n"
                    + "the test will time out. "
                    + "Closing the window also fails the test.";

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeAndWait(RemotePrinterStatusRefresh::createUI);

        latch.await();
        if (!test.testResult) {
            throw new RuntimeException("Test failed"
                + (test.testTimedOut ? " because of time out" : ""));
        }
    }

    private static long getRefreshTime() {
        String refreshTime =
221 222
                System.getProperty("sun.java2d.print.minRefreshTime",
                                   Long.toString(DEFAULT_REFRESH_TIME));
223 224
        try {
            long value = Long.parseLong(refreshTime);
225
            return value < MINIMAL_REFRESH_TIME ? MINIMAL_REFRESH_TIME : value;
226
        } catch (NumberFormatException e) {
227
            return DEFAULT_REFRESH_TIME;
228 229 230 231 232 233 234 235 236 237 238
        }
    }

    private static void createUI() {
        test = new RemotePrinterStatusRefresh();
    }

    private RemotePrinterStatusRefresh() {
        frame = new JFrame("RemotePrinterStatusRefresh");
        frame.addWindowListener(this);

239

240 241 242
        JPanel northPanel = new JPanel(new BorderLayout());
        northPanel.add(createInfoPanel(), BorderLayout.NORTH);
        northPanel.add(createInstructionsPanel(), BorderLayout.SOUTH);
243 244


245 246 247 248
        beforeList = new ServiceItemListModel(
                Collections.unmodifiableList(collectPrinterList()));
        afterList = new ServiceItemListModel(new ArrayList<>());
        logList("Before:", beforeList.list);
249

250 251 252 253
        JPanel listPanel = new JPanel(new GridLayout(1, 2));
        listPanel.setBorder(createTitledBorder("Print Services"));
        listPanel.add(createListPanel(beforeList, "Before:", 'b'));
        listPanel.add(createListPanel(afterList, "After:", 'a'));
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(northPanel, BorderLayout.NORTH);
        mainPanel.add(listPanel, BorderLayout.CENTER);
        mainPanel.add(createButtonPanel(), BorderLayout.SOUTH);


        frame.add(mainPanel);
        frame.pack();
        refreshButton.requestFocusInWindow();
        frame.setVisible(true);


        timer = new Timer(1000, this::updateTimeLeft);
        timer.start();
        startTime = System.currentTimeMillis();
        updateTimeLeft(null);
272 273
    }

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    private JPanel createInfoPanel() {
        JLabel javaLabel = new JLabel("Java version:");
        JTextField javaVersion =
                new JTextField(System.getProperty("java.runtime.version"));
        javaVersion.setEditable(false);
        javaLabel.setLabelFor(javaVersion);

        JLabel refreshTimeLabel = new JLabel("Refresh interval:");
        long minutes = refreshTime / 60;
        long seconds = refreshTime % 60;
        String interval = String.format("%1$d seconds%2$s",
                refreshTime,
                minutes > 0
                    ? String.format(" (%1$d %2$s%3$s)",
                        minutes,
                        minutes > 1 ? "minutes" : "minute",
                        seconds > 0
                            ? String.format(" %1$d %2$s",
                                seconds,
                                seconds > 1 ? "seconds" : "second")
                            : "")
                    : ""
        );
        JTextField refreshInterval = new JTextField(interval);
        refreshInterval.setEditable(false);
        refreshTimeLabel.setLabelFor(refreshInterval);

        JLabel nextRefreshLabel = new JLabel("Next printer refresh in:");
        nextRefresh = new JTextField();
        nextRefresh.setEditable(false);
        nextRefreshLabel.setLabelFor(nextRefresh);

        JLabel timeoutLabel = new JLabel("Time left:");
        timeLeft = new JTextField();
        timeLeft.setEditable(false);
        timeoutLabel.setLabelFor(timeLeft);

        JPanel infoPanel = new JPanel();
        GroupLayout layout = new GroupLayout(infoPanel);
        infoPanel.setLayout(layout);
        infoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
        layout.setAutoCreateGaps(true);
        layout.setHorizontalGroup(
            layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(javaLabel)
                    .addComponent(refreshTimeLabel)
                    .addComponent(nextRefreshLabel)
                    .addComponent(timeoutLabel)
                )
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, true)
                    .addComponent(javaVersion)
                    .addComponent(refreshInterval)
                    .addComponent(nextRefresh)
                    .addComponent(timeLeft)
                )
        );
        layout.setVerticalGroup(
            layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(javaLabel)
                    .addComponent(javaVersion)
                )
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(refreshTimeLabel)
                    .addComponent(refreshInterval))
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(nextRefreshLabel)
                    .addComponent(nextRefresh))
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(timeoutLabel)
                    .addComponent(timeLeft))
        );
        return infoPanel;
    }

    private JPanel createInstructionsPanel() {
        JPanel instructionsPanel = new JPanel(new BorderLayout());
        JTextArea instructionText = new JTextArea(INSTRUCTIONS_TEXT);
        instructionText.setEditable(false);
        instructionsPanel.setBorder(createTitledBorder("Test Instructions"));
        instructionsPanel.add(new JScrollPane(instructionText));
        return  instructionsPanel;
    }

    private JPanel createListPanel(final ServiceItemListModel model,
                                   final String title,
                                   final char mnemonic) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        JList<ServiceItem> list = new JList<>(model);
        list.setCellRenderer(new ServiceItemListRenderer());

        JLabel label = new JLabel(title);
        label.setLabelFor(list);
        label.setDisplayedMnemonic(mnemonic);
        JPanel labelPanel = new JPanel();
        labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS));
        labelPanel.add(label, BorderLayout.EAST);
        labelPanel.add(Box.createHorizontalGlue());

        panel.add(labelPanel);
        panel.add(new JScrollPane(list));
        return panel;
    }

    private JPanel createButtonPanel() {
        refreshButton = new JButton("Refresh");
        refreshButton.addActionListener(this::refresh);

384
        passButton = new JButton("Pass");
385 386
        passButton.addActionListener(this::pass);
        passButton.setEnabled(false);
387 388

        failButton = new JButton("Fail");
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
        failButton.addActionListener(this::fail);
        failButton.setEnabled(false);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(refreshButton);
        buttonPanel.add(passButton);
        buttonPanel.add(failButton);
        buttonPanel.add(Box.createHorizontalGlue());
        return buttonPanel;
    }

    private static List<ServiceItem> collectPrinterList() {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        List<ServiceItem> list = new ArrayList<>(printServices.length);
        for (PrintService service : printServices) {
            list.add(new ServiceItem(service.getName()));
        }
        return list;
    }

    private static void logList(final String title, final List<ServiceItem> list) {
        System.out.println(title);
        for (ServiceItem item : list) {
            System.out.println(item.name);
        }
        System.out.println();
    }
418

419 420 421 422 423 424 425 426 427 428 429 430 431
    private static void compareLists(final ServiceItemListModel before, final ServiceItemListModel after) {
        boolean beforeUpdated = false;
        boolean afterUpdated = false;

        for (ServiceItem item : before.list) {
            if (!after.list.contains(item)) {
                item.state = ServiceItem.State.REMOVED;
                beforeUpdated = true;
            } else if (item.state != ServiceItem.State.UNCHANGED) {
                item.state = ServiceItem.State.UNCHANGED;
                beforeUpdated = true;
            }
        }
432

433 434 435 436 437 438 439 440 441
        for (ServiceItem item : after.list) {
            if (!before.list.contains(item)) {
                item.state = ServiceItem.State.ADDED;
                afterUpdated = true;
            } else if (item.state != ServiceItem.State.UNCHANGED) {
                item.state = ServiceItem.State.UNCHANGED;
                afterUpdated = true;
            }
        }
442

443 444 445 446 447 448 449
        if (beforeUpdated) {
            before.fireChanged();
        }
        if (afterUpdated) {
            after.fireChanged();
        }
    }
450

451 452 453 454 455
    @Override
    public void windowClosing(WindowEvent e) {
        System.out.println("The window closed");
        disposeUI();
    }
456

457 458 459 460 461
    private void disposeUI() {
        timer.stop();
        latch.countDown();
        frame.dispose();
    }
462

463 464 465 466 467 468 469 470 471
    @SuppressWarnings("unused")
    private void refresh(ActionEvent e) {
        System.out.println("Refresh button pressed");
        afterList.refreshList(collectPrinterList());
        compareLists(beforeList, afterList);
        passButton.setEnabled(true);
        failButton.setEnabled(true);
        logList("After:", afterList.list);
    }
472

473 474 475 476 477
    @SuppressWarnings("unused")
    private void pass(ActionEvent e) {
        System.out.println("Pass button pressed");
        testResult = true;
        disposeUI();
478 479
    }

480 481 482 483 484
    @SuppressWarnings("unused")
    private void fail(ActionEvent e) {
        System.out.println("Fail button pressed");
        testResult = false;
        disposeUI();
485
    }
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503

    @SuppressWarnings("unused")
    private void updateTimeLeft(ActionEvent e) {
        long elapsed = (System.currentTimeMillis() - startTime) / 1000;
        long left = TIMEOUT - elapsed;
        if (left < 0) {
            testTimedOut = true;
            disposeUI();
        }
        timeLeft.setText(formatTime(left));
        nextRefresh.setText(formatTime(refreshTime - (elapsed % refreshTime)));
    }

    private static String formatTime(final long seconds) {
        long minutes = seconds / 60;
        return String.format("%d:%02d", minutes, seconds - minutes * 60);
    }

504
}