View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.platform;
16  
17  import java.awt.Toolkit;
18  import java.awt.datatransfer.Clipboard;
19  import java.awt.datatransfer.DataFlavor;
20  import java.awt.datatransfer.StringSelection;
21  import java.awt.datatransfer.Transferable;
22  import java.awt.datatransfer.UnsupportedFlavorException;
23  import java.io.IOException;
24  
25  import org.htmlunit.ClipboardHandler;
26  
27  /**
28   * {@link ClipboardHandler} using the {@link Clipboard}.
29   *
30   * @author Ronald Brill
31   */
32  public class AwtClipboardHandler implements ClipboardHandler {
33  
34      /**
35       * {@inheritDoc}
36       */
37      @Override
38      public String getClipboardContent() {
39          String result = "";
40          final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
41          final Transferable contents = clipboard.getContents(null);
42          if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
43              try {
44                  result = (String) contents.getTransferData(DataFlavor.stringFlavor);
45              }
46              catch (final UnsupportedFlavorException | IOException ignored) {
47                  // TODO
48              }
49          }
50          return result;
51      }
52  
53      /**
54       * {@inheritDoc}
55       */
56      @Override
57      public void setClipboardContent(final String string) {
58          final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
59          final StringSelection stringSelection = new StringSelection(string);
60          clipboard.setContents(stringSelection, null);
61      }
62  }