1
0
mirror of https://github.com/mitb-archive/filebot synced 2024-12-23 08:18:52 -05:00

Fix various compiler warnings

This commit is contained in:
Reinhard Pointner 2016-03-10 06:28:22 +00:00
parent 537144187a
commit d76f625328
26 changed files with 112 additions and 168 deletions

View File

@ -8,7 +8,7 @@
<classpathentry kind="lib" path="lib/jars/simmetrics.jar"/>
<classpathentry kind="lib" path="lib/jars/xmlrpc.jar"/>
<classpathentry kind="lib" path="lib/ivy/jar/ehcache.jar" sourcepath="lib/ivy/source/ehcache.jar"/>
<classpathentry kind="lib" path="lib/ivy/jar/glazedlists_java15.jar"/>
<classpathentry kind="lib" path="lib/ivy/jar/glazedlists_java15.jar" sourcepath="lib/ivy/source/glazedlists_java15.jar"/>
<classpathentry kind="lib" path="lib/ivy/jar/icu4j.jar"/>
<classpathentry kind="lib" path="lib/ivy/jar/jna.jar"/>
<classpathentry kind="lib" path="lib/ivy/jar/junit.jar"/>

View File

@ -24,6 +24,7 @@ public enum CacheType {
this.diskPersistent = diskPersistent;
}
@SuppressWarnings("deprecation")
CacheConfiguration getConfiguration(String name) {
// Strategy.LOCALTEMPSWAP is not restartable so we can't but use the deprecated disk persistent code (see http://stackoverflow.com/a/24623527/1514467)
return new CacheConfiguration().name(name).maxEntriesLocalHeap(diskPersistent ? 200 : 0).maxEntriesLocalDisk(0).eternal(false).timeToLiveSeconds(timeToLiveSeconds).timeToIdleSeconds(timeToLiveSeconds).overflowToDisk(diskPersistent).diskPersistent(diskPersistent);

View File

@ -1,7 +1,5 @@
package net.filebot.archive;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -16,7 +14,6 @@ import net.sf.sevenzipjbinding.PropID;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveOpenCallback, Closeable {
/**
@ -29,10 +26,8 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO
*/
private String name;
/**
* This method should at least provide the name of the last
* opened volume (propID=PropID.NAME).
* This method should at least provide the name of the last opened volume (propID=PropID.NAME).
*
* @see IArchiveOpenVolumeCallback#getProperty(PropID)
*/
@ -41,16 +36,13 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO
switch (propID) {
case NAME:
return name;
default:
return null;
}
return null;
}
/**
* The name of the required volume will be calculated out of the
* name of the first volume and a volume index. In case of RAR file,
* the substring ".partNN." in the name of the volume file will
* indicate a volume with id NN. For example:
* The name of the required volume will be calculated out of the name of the first volume and a volume index. In case of RAR file, the substring ".partNN." in the name of the volume file will indicate a volume with id NN. For example:
* <ul>
* <li>test.rar - single part archive or multi-part archive with a single volume</li>
* <li>test.part23.rar - 23-th part of a multi-part archive</li>
@ -85,7 +77,7 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO
} catch (FileNotFoundException fileNotFoundException) {
// Required volume doesn't exist. This happens if the volume:
// 1. never exists. 7-Zip doesn't know how many volumes should
// exist, so it have to try each volume.
// exist, so it have to try each volume.
// 2. should be there, but doesn't. This is an error case.
// Since normal and error cases are possible,
@ -96,7 +88,6 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO
}
}
/**
* Close all opened streams
*/
@ -107,12 +98,10 @@ class ArchiveOpenVolumeCallback implements IArchiveOpenVolumeCallback, IArchiveO
}
}
@Override
public void setCompleted(Long files, Long bytes) throws SevenZipException {
}
@Override
public void setTotal(Long files, Long bytes) throws SevenZipException {
}

View File

@ -1,6 +1,8 @@
package net.filebot.archive;
import static java.nio.charset.StandardCharsets.*;
import static java.util.Arrays.*;
import static net.filebot.Logging.*;
import java.io.File;
import java.io.FileFilter;
@ -40,21 +42,20 @@ public class SevenZipExecutable implements ArchiveExtractor {
protected CharSequence execute(String... command) throws IOException {
Process process = new ProcessBuilder(command).redirectError(Redirect.INHERIT).start();
ByteBufferOutputStream bb = new ByteBufferOutputStream(8 * 1024);
bb.transferFully(process.getInputStream());
try (ByteBufferOutputStream bb = new ByteBufferOutputStream(8 * 1024)) {
bb.transferFully(process.getInputStream());
try {
int returnCode = process.waitFor();
CharSequence output = UTF_8.decode(bb.getByteBuffer());
String output = UTF_8.decode(bb.getByteBuffer()).toString();
// DEBUG
// System.out.println("Execute: " + Arrays.asList(command));
// System.out.println(output);
debug.fine(format("Execute: %s", asList(command)));
debug.finest(output);
if (returnCode == 0) {
return output;
} else {
throw new IOException(String.format("%s failed with exit code %d: %s", get7zCommand(), returnCode, output.toString().replaceAll("\\s+", " ").trim()));
throw new IOException(String.format("%s failed with exit code %d: %s", get7zCommand(), returnCode, output.replaceAll("\\s+", " ").trim()));
}
} catch (InterruptedException e) {
throw new IOException(String.format("%s timed out", get7zCommand()), e);

View File

@ -16,12 +16,10 @@ import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import javax.script.Bindings;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;

View File

@ -27,9 +27,9 @@ import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
@ -301,7 +301,7 @@ public class MediaBindingBean {
String codec = getMediaInfo(StreamKind.Video, 0, "Encoded_Library_Name", "Encoded_Library/Name", "CodecID/Hint", "Format");
// get first token (e.g. DivX 5 => DivX)
return new Scanner(codec).next();
return new StringTokenizer(codec).nextToken();
}
@Define("ac")

View File

@ -512,7 +512,7 @@ public class MediaDetection {
for (CollationKey[] name : names) {
IndexEntry<SearchResult> bestMatch = null;
for (IndexEntry<SearchResult> it : index) {
CollationKey[] commonName = nameMatcher.matchFirstCommonSequence(name, it.getLenientKey());
CollationKey[] commonName = nameMatcher.matchFirstCommonSequence(new CollationKey[][] { name, it.getLenientKey() });
if (commonName != null && commonName.length >= it.getLenientKey().length && (bestMatch == null || commonName.length > bestMatch.getLenientKey().length)) {
bestMatch = it;
}
@ -871,9 +871,9 @@ public class MediaDetection {
for (IndexEntry<Movie> movie : getMovieIndex()) {
for (CollationKey[] name : names) {
CollationKey[] commonName = nameMatcher.matchFirstCommonSequence(name, movie.getLenientKey());
CollationKey[] commonName = nameMatcher.matchFirstCommonSequence(new CollationKey[][] { name, movie.getLenientKey() });
if (commonName != null && commonName.length >= movie.getLenientKey().length) {
CollationKey[] strictCommonName = nameMatcher.matchFirstCommonSequence(name, movie.getStrictKey());
CollationKey[] strictCommonName = nameMatcher.matchFirstCommonSequence(new CollationKey[][] { name, movie.getStrictKey() });
if (strictCommonName != null && strictCommonName.length >= movie.getStrictKey().length) {
// prefer strict match
matchMap.put(movie.getObject(), movie.getStrictName());
@ -998,7 +998,7 @@ public class MediaDetection {
for (Movie movie : options) {
for (String alias : movie.getEffectiveNames()) {
CollationKey[] movieSeq = HighPerformanceMatcher.prepare(normalizePunctuation(alias));
CollationKey[] commonSeq = nameMatcher.matchFirstCommonSequence(nameSeq, movieSeq);
CollationKey[] commonSeq = nameMatcher.matchFirstCommonSequence(new CollationKey[][] { nameSeq, movieSeq });
if (commonSeq != null && commonSeq.length >= movieSeq.length) {
movies.add(movie);

View File

@ -41,7 +41,7 @@ public class CommonSequenceMatcher {
return synth(matchFirstCommonSequence(words));
}
public <E extends Comparable<E>> E[] matchFirstCommonSequence(E[]... names) {
public <E extends Comparable<E>> E[] matchFirstCommonSequence(E[][] names) {
E[] common = null;
for (E[] words : names) {

View File

@ -55,7 +55,7 @@ public class FileBotList<E> extends JComponent {
public void setModel(EventList<E> model) {
this.model = model;
list.setModel(new EventListModel<E>(model));
list.setModel(new EventListModel(model));
}
public JList getListComponent() {
@ -110,15 +110,16 @@ public class FileBotList<E> extends JComponent {
@Override
public void actionPerformed(ActionEvent e) {
int index = list.getSelectedIndex();
Object values[] = list.getSelectedValues();
for (Object value : values)
for (Object value : list.getSelectedValuesList()) {
getModel().remove(value);
}
int maxIndex = list.getModel().getSize() - 1;
if (index > maxIndex)
if (index > maxIndex) {
index = maxIndex;
}
list.setSelectedIndex(index);
}

View File

@ -40,7 +40,7 @@ public class SelectButtonTextField<T> extends JComponent {
private SelectButton<T> selectButton = new SelectButton<T>();
private JComboBox editor = new JComboBox();
private JComboBox<Object> editor = new JComboBox<Object>();
public SelectButtonTextField() {
selectButton.addActionListener(textFieldFocusOnClick);
@ -53,7 +53,7 @@ public class SelectButtonTextField<T> extends JComponent {
editor.setPrototypeDisplayValue("X");
editor.setRenderer(new CompletionCellRenderer());
editor.setUI(new TextFieldComboBoxUI());
editor.setUI(new TextFieldComboBoxUI(selectButton));
editor.setMaximumRowCount(10);
SwingUI.installAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.CTRL_MASK), new SpinClientAction(-1));
@ -102,6 +102,7 @@ public class SelectButtonTextField<T> extends JComponent {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setBorder(new EmptyBorder(1, 4, 1, 4));
String highlightText = SelectButtonTextField.this.getText().substring(0, ((TextFieldComboBoxUI) editor.getUI()).getEditor().getSelectionStart());
// highlight the matching sequence
@ -124,7 +125,13 @@ public class SelectButtonTextField<T> extends JComponent {
}
}
private class TextFieldComboBoxUI extends BasicComboBoxUI {
private static class TextFieldComboBoxUI extends BasicComboBoxUI {
private SelectButton<?> button;
public TextFieldComboBoxUI(SelectButton<?> button) {
this.button = button;
}
@Override
protected JButton createArrowButton() {
@ -192,13 +199,13 @@ public class SelectButtonTextField<T> extends JComponent {
@Override
public void show(Component invoker, int x, int y) {
super.show(invoker, x - selectButton.getWidth(), y);
super.show(invoker, x - button.getWidth(), y);
}
@Override
protected Rectangle computePopupBounds(int px, int py, int pw, int ph) {
Rectangle bounds = super.computePopupBounds(px, py, pw, ph);
bounds.width += selectButton.getWidth();
bounds.width += button.getWidth();
return bounds;
}

View File

@ -116,7 +116,7 @@ public class FileTree extends JTree {
@Override
public void actionPerformed(ActionEvent event) {
UserFiles.revealFiles((Collection<File>) getValue("files"));
UserFiles.revealFiles((Collection) getValue("files"));
}
}

View File

@ -72,7 +72,8 @@ class FileTreeTransferablePolicy extends BackgroundFileTransferablePolicy<TreeNo
FastFile root = FastFile.create(filter(files, FOLDERS))[0];
// publish on EDT
publish(getTreeNode(root));
TreeNode[] node = { getTreeNode(root) };
publish(node);
} catch (InterruptedException e) {
// supposed to happen if background execution was aborted
}

View File

@ -15,7 +15,6 @@ import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
@ -306,11 +305,10 @@ public class EpisodeListPanel extends AbstractSearchPanel<EpisodeListProvider, E
@Override
public void exportToClipboard(JComponent c, Clipboard clipboard, int action) throws IllegalStateException {
Object[] selection = list.getListComponent().getSelectedValues();
Episode[] episodes = Arrays.copyOf(selection, selection.length, Episode[].class);
Episode[] selection = ((List<?>) list.getListComponent().getSelectedValuesList()).stream().map(Episode.class::cast).toArray(Episode[]::new);
Transferable episodeArray = new ArrayTransferable<Episode>(episodes);
Transferable stringSelection = new StringSelection(StringUtilities.join(episodes, "\n"));
Transferable episodeArray = new ArrayTransferable<Episode>(selection);
Transferable stringSelection = new StringSelection(StringUtilities.join(selection, "\n"));
clipboard.setContents(new CompositeTranserable(episodeArray, stringSelection), null);
}

View File

@ -1,7 +1,5 @@
package net.filebot.ui.rename;
import java.io.File;
import java.text.Format;
import java.util.Map;
@ -12,7 +10,6 @@ import net.filebot.format.ExpressionFormat;
import net.filebot.format.MediaBindingBean;
import net.filebot.similarity.Match;
class ExpressionFormatter implements MatchFormatter {
private final String expression;
@ -21,7 +18,6 @@ class ExpressionFormatter implements MatchFormatter {
private Format preview;
private Class<?> target;
public ExpressionFormatter(String expression, Format preview, Class<?> target) {
if (expression == null || expression.isEmpty())
throw new IllegalArgumentException("Expression must not be null or empty");
@ -32,20 +28,17 @@ class ExpressionFormatter implements MatchFormatter {
}
@Override
public boolean canFormat(Match<?, ?> match) {
// target object is required, file is optional
return target.isInstance(match.getValue()) && (match.getCandidate() == null || match.getCandidate() instanceof File);
}
@Override
public String preview(Match<?, ?> match) {
return preview != null ? preview.format(match.getValue()) : match.getValue().toString();
}
@Override
public synchronized String format(Match<?, ?> match, Map<?, ?> context) throws ScriptException {
// lazy initialize script engine
@ -54,7 +47,7 @@ class ExpressionFormatter implements MatchFormatter {
}
// evaluate the expression using the given bindings
Object bindingBean = new MediaBindingBean(match.getValue(), (File) match.getCandidate(), (Map<File, Object>) context);
Object bindingBean = new MediaBindingBean(match.getValue(), (File) match.getCandidate(), (Map) context);
String result = format.format(bindingBean).trim();
// if result is empty, check for script exceptions

View File

@ -252,7 +252,7 @@ public class PresetEditor extends JDialog {
JComboBox<Datasource> combo = new JComboBox<Datasource>(providers);
combo.setRenderer(new ListCellRenderer<Object>() {
private final ListCellRenderer<Object> parent = (ListCellRenderer<Object>) combo.getRenderer();
private final ListCellRenderer<Object> parent = (ListCellRenderer) combo.getRenderer();
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
@ -289,7 +289,7 @@ public class PresetEditor extends JDialog {
JComboBox<Language> combo = new JComboBox<Language>(languages);
combo.setRenderer(new ListCellRenderer<Language>() {
private final ListCellRenderer<Language> parent = (ListCellRenderer<Language>) combo.getRenderer();
private final ListCellRenderer<Language> parent = (ListCellRenderer) combo.getRenderer();
@Override
public Component getListCellRendererComponent(JList<? extends Language> list, Language value, int index, boolean isSelected, boolean cellHasFocus) {
@ -318,7 +318,7 @@ public class PresetEditor extends JDialog {
JComboBox<RenameAction> combo = new JComboBox<RenameAction>(actions);
combo.setRenderer(new ListCellRenderer<RenameAction>() {
private final ListCellRenderer<RenameAction> parent = (ListCellRenderer<RenameAction>) combo.getRenderer();
private final ListCellRenderer<RenameAction> parent = (ListCellRenderer) combo.getRenderer();
@Override
public Component getListCellRendererComponent(JList<? extends RenameAction> list, RenameAction value, int index, boolean isSelected, boolean cellHasFocus) {

View File

@ -132,6 +132,8 @@ class RenameListCellRenderer extends DefaultFancyListCellRenderer {
case STARTED:
setIcon(ResourceManager.getIcon("worker.started"));
break;
default:
break;
}
if (renameModel.hasComplement(index)) {

View File

@ -131,7 +131,8 @@ class ChecksumTableTransferablePolicy extends BackgroundFileTransferablePolicy<C
ChecksumCell correct = new ChecksumCell(name, file, singletonMap(type, hash));
ChecksumCell current = createComputationCell(name, baseFolder, type);
publish(correct, current);
ChecksumCell[] columns = { correct, current };
publish(columns);
}
} finally {
parser.close();
@ -158,14 +159,17 @@ class ChecksumTableTransferablePolicy extends BackgroundFileTransferablePolicy<C
String name = normalizePathSeparators(relativeFile.getPath());
// publish computation cell first
publish(createComputationCell(name, root, model.getHashType()));
ChecksumCell[] computeCell = { createComputationCell(name, root, model.getHashType()) };
publish(computeCell);
// publish verification cell, if we can
Map<File, String> hashByVerificationFile = verificationTracker.get().getHashByVerificationFile(absoluteFile);
for (Entry<File, String> entry : hashByVerificationFile.entrySet()) {
HashType hashType = verificationTracker.get().getVerificationFileType(entry.getKey());
publish(new ChecksumCell(name, entry.getKey(), singletonMap(hashType, entry.getValue())));
ChecksumCell[] verifyCell = { new ChecksumCell(name, entry.getKey(), singletonMap(hashType, entry.getValue())) };
publish(verifyCell);
}
}
}

View File

@ -1,11 +1,10 @@
package net.filebot.ui.subtitle;
import static java.util.stream.Collectors.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;
import java.nio.ByteBuffer;
import java.util.AbstractList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -19,46 +18,27 @@ import net.filebot.ui.transfer.ClipboardHandler;
import net.filebot.ui.transfer.TransferableExportHandler;
import net.filebot.vfs.MemoryFile;
class MemoryFileListExportHandler implements TransferableExportHandler, ClipboardHandler {
public boolean canExport(JComponent component) {
JList list = (JList) component;
JList<?> list = (JList<?>) component;
// can't export anything, if nothing is selected
return !list.isSelectionEmpty();
}
public List<MemoryFile> export(JComponent component) {
JList list = (JList) component;
JList<?> list = (JList<?>) component;
// get selected values
final Object[] selection = list.getSelectedValues();
// as file list
return new AbstractList<MemoryFile>() {
@Override
public MemoryFile get(int index) {
return (MemoryFile) selection[index];
}
@Override
public int size() {
return selection.length;
}
};
// get selected values as list
return list.getSelectedValuesList().stream().map(MemoryFile.class::cast).collect(toList());
}
@Override
public int getSourceActions(JComponent component) {
return canExport(component) ? TransferHandler.COPY_OR_MOVE : TransferHandler.NONE;
}
@Override
public Transferable createTransferable(JComponent component) {
Map<String, ByteBuffer> vfs = new HashMap<String, ByteBuffer>();
@ -70,13 +50,11 @@ class MemoryFileListExportHandler implements TransferableExportHandler, Clipboar
return new ByteBufferTransferable(vfs);
}
@Override
public void exportToClipboard(JComponent component, Clipboard clip, int action) {
clip.setContents(createTransferable(component), null);
}
@Override
public void exportDone(JComponent source, Transferable data, int action) {

View File

@ -135,7 +135,7 @@ class SubtitleDownloadComponent extends JComponent {
@Override
public void actionPerformed(ActionEvent e) {
fetch(packageList.getSelectedValues());
fetch(packageList.getSelectedValuesList().toArray());
}
});
@ -144,7 +144,7 @@ class SubtitleDownloadComponent extends JComponent {
@Override
public void actionPerformed(ActionEvent e) {
open(fileList.getSelectedValues());
open(fileList.getSelectedValuesList().toArray());
}
});
}
@ -345,8 +345,7 @@ class SubtitleDownloadComponent extends JComponent {
// fetch on double click
if (SwingUtilities.isLeftMouseButton(e) && (e.getClickCount() == 2)) {
JList list = (JList) e.getSource();
fetch(list.getSelectedValues());
fetch(list.getSelectedValuesList().toArray());
}
}
@ -371,7 +370,7 @@ class SubtitleDownloadComponent extends JComponent {
list.setSelectedIndex(index);
}
final Object[] selection = list.getSelectedValues();
final Object[] selection = list.getSelectedValuesList().toArray();
if (selection.length > 0) {
JPopupMenu contextMenu = new JPopupMenu();
@ -415,7 +414,7 @@ class SubtitleDownloadComponent extends JComponent {
JList list = (JList) e.getSource();
// open selection
open(list.getSelectedValues());
open(list.getSelectedValuesList().toArray());
}
}
@ -440,7 +439,7 @@ class SubtitleDownloadComponent extends JComponent {
list.setSelectedIndex(index);
}
final Object[] selection = list.getSelectedValues();
final Object[] selection = list.getSelectedValuesList().toArray();
if (selection.length > 0) {
JPopupMenu contextMenu = new JPopupMenu();

View File

@ -1,14 +1,11 @@
package net.filebot.ui.transfer;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.lang.reflect.Array;
public class ArrayTransferable<T> implements Transferable {
public static DataFlavor flavor(Class<?> componentType) {
@ -17,12 +14,10 @@ public class ArrayTransferable<T> implements Transferable {
private final T[] array;
public ArrayTransferable(T... array) {
public ArrayTransferable(T[] array) {
this.array = array;
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
@ -32,13 +27,11 @@ public class ArrayTransferable<T> implements Transferable {
return null;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { new DataFlavor(array.getClass(), "Array") };
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return array.getClass().equals(flavor.getRepresentationClass());

View File

@ -64,7 +64,7 @@ public abstract class BackgroundFileTransferablePolicy<V> extends FileTransferab
protected abstract void process(Exception exception);
protected final void publish(V... chunks) {
protected final void publish(V[] chunks) {
BackgroundWorker worker = threadLocalWorker.get();
if (worker == null) {
@ -116,7 +116,7 @@ public abstract class BackgroundFileTransferablePolicy<V> extends FileTransferab
return null;
}
public void offer(V... chunks) {
public void offer(V[] chunks) {
if (!isCancelled()) {
publish(chunks);
}

View File

@ -1,9 +1,13 @@
package net.filebot.ui.transfer;
import static java.util.Arrays.*;
import static java.util.stream.Collectors.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.util.Objects;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.swing.JComponent;
import javax.swing.JList;
@ -11,70 +15,45 @@ import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.tree.TreePath;
import net.filebot.util.StringUtilities;
public class DefaultClipboardHandler implements ClipboardHandler {
protected final String newLine = System.getProperty("line.separator");
@Override
public void exportToClipboard(JComponent component, Clipboard clip, int action) throws IllegalStateException {
StringBuilder sb = new StringBuilder();
clip.setContents(new StringSelection(export(component)), null);
}
protected String export(JComponent component) {
if (component instanceof JList) {
export(sb, (JList) component);
} else if (component instanceof JTree) {
export(sb, (JTree) component);
} else if (component instanceof JTable) {
export(sb, (JTable) component);
return export((JList) component);
}
clip.setContents(new StringSelection(sb.toString()), null);
if (component instanceof JTree) {
return export((JTree) component);
}
if (component instanceof JTable) {
return export((JTable) component);
}
throw new IllegalArgumentException("JComponent not supported: " + component);
}
protected void export(StringBuilder sb, JList list) {
for (Object value : list.getSelectedValues()) {
sb.append(value == null ? "" : value).append(newLine);
}
// delete last newline
sb.delete(sb.length() - newLine.length(), sb.length());
protected String export(Stream<?> values) {
return StringUtilities.join(values, System.lineSeparator());
}
protected void export(StringBuilder sb, JTree tree) {
for (TreePath path : tree.getSelectionPaths()) {
Object value = path.getLastPathComponent();
sb.append(value == null ? "" : value).append(newLine);
}
// delete last newline
sb.delete(sb.length() - newLine.length(), sb.length());
protected String export(JList list) {
return export(list.getSelectedValuesList().stream());
}
protected String export(JTree tree) {
return export(stream(tree.getSelectionPaths()).map(TreePath::getLastPathComponent));
}
protected void export(StringBuilder sb, JTable table) {
for (int row : table.getSelectedRows()) {
int modelRow = table.getRowSorter().convertRowIndexToModel(row);
for (int column = 0; column < table.getColumnCount(); column++) {
Object value = table.getModel().getValueAt(modelRow, column);
if (value != null) {
sb.append(value);
}
if (column < table.getColumnCount() - 1) {
sb.append("\t");
}
}
sb.append(newLine);
}
// delete last newline
sb.delete(sb.length() - newLine.length(), sb.length());
protected String export(JTable table) {
return export(stream(table.getSelectedRows()).map(row -> table.getRowSorter().convertRowIndexToModel(row)).mapToObj(row -> {
return IntStream.range(0, table.getColumnCount()).mapToObj(column -> {
return table.getModel().getValueAt(row, column);
}).map(v -> Objects.toString(v, "")).collect(joining("\t"));
}));
}
}

View File

@ -75,11 +75,15 @@ public final class StringUtilities {
}
public static String join(Collection<?> values, CharSequence delimiter) {
return join(values.stream(), delimiter, "", "");
return join(values.stream(), delimiter);
}
public static String join(Object[] values, CharSequence delimiter) {
return join(stream(values), delimiter, "", "");
return join(stream(values), delimiter);
}
public static String join(Stream<?> values, CharSequence delimiter) {
return join(values, delimiter, "", "");
}
public static String join(Stream<?> values, CharSequence delimiter, CharSequence prefix, CharSequence suffix) {

View File

@ -1,13 +1,10 @@
package net.filebot.util.ui;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.SwingWorker.StateValue;
public abstract class SwingWorkerPropertyChangeAdapter implements PropertyChangeListener {
@Override
@ -21,7 +18,6 @@ public abstract class SwingWorkerPropertyChangeAdapter implements PropertyChange
}
}
protected void state(PropertyChangeEvent evt) {
switch ((StateValue) evt.getNewValue()) {
case STARTED:
@ -30,22 +26,20 @@ public abstract class SwingWorkerPropertyChangeAdapter implements PropertyChange
case DONE:
done(evt);
break;
default:
break;
}
}
protected void progress(PropertyChangeEvent evt) {
}
protected void started(PropertyChangeEvent evt) {
}
protected void done(PropertyChangeEvent evt) {
}
protected void event(String name, Object oldValue, Object newValue) {
}

View File

@ -153,6 +153,7 @@ public final class WebRequest {
}
ByteBufferOutputStream buffer = new ByteBufferOutputStream(contentLength >= 0 ? contentLength : 4 * 1024);
try {
// read all
buffer.transferFully(in);

View File

@ -9,6 +9,7 @@ import java.nio.channels.Channels;
import org.junit.Test;
@SuppressWarnings("resource")
public class ByteBufferOutputStreamTest {
@Test