Clean up again

This commit is contained in:
huangyuhui
2017-01-27 22:41:34 +08:00
parent 809d7378e2
commit 972c4758b1
120 changed files with 353 additions and 1725 deletions

View File

@@ -47,12 +47,12 @@ public abstract class AbstractSwingWorker<T> extends SwingWorker<Void, T> {
return null;
}
public AbstractSwingWorker reg(Consumer<T> c) {
public AbstractSwingWorker<T> reg(Consumer<T> c) {
processListeners.add(Objects.requireNonNull(c));
return this;
}
public AbstractSwingWorker regDone(Runnable c) {
public AbstractSwingWorker<T> regDone(Runnable c) {
doneListeners.add(Objects.requireNonNull(c));
return this;
}

View File

@@ -18,6 +18,8 @@
package org.jackhuang.hellominecraft.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -57,10 +59,6 @@ public final class ArrayUtils {
return -1;
}
public static <T> int lastIndexOf(T[] array, T valueToFind) {
return lastIndexOf(array, valueToFind, 2147483647);
}
public static <T> int lastIndexOf(T[] array, T valueToFind, int startIndex) {
if (array == null)
return -1;
@@ -75,16 +73,16 @@ public final class ArrayUtils {
}
public static <T> ArrayList<T> merge(List<T> a, List<T> b) {
ArrayList al = new ArrayList(a.size() + b.size());
ArrayList<T> al = new ArrayList<>(a.size() + b.size());
al.addAll(a);
al.addAll(b);
return al;
}
public static List tryGetMapWithList(Map map, String key) {
List l = (List) map.get(key);
public static <T> List<T> tryGetMapWithList(Map<String, List<T>> map, String key) {
List<T> l = (List<T>) map.get(key);
if (l == null)
map.put(key, l = new ArrayList());
map.put(key, l = new ArrayList<>());
return l;
}
@@ -102,4 +100,8 @@ public final class ArrayUtils {
}
return -1;
}
public static <T> boolean hasDuplicateElements(T[] t) {
return new HashSet<>(Arrays.asList(t)).size() < t.length;
}
}

View File

@@ -35,10 +35,6 @@ public final class C {
public static final String URL_GITHUB = "https://github.com/huanghongxun/HMCL/issues";
public static final String URL_MINECRAFTFORUM = "http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-tools/1265720-hello-minecraft-launcher-1-9-3-mc-1-7-4-auto";
public static final String FILE_MINECRAFT_VERSIONS = "versions";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String URL_FORGE_LIST = "http://files.minecraftforge.net/maven/net/minecraftforge/forge/json";
public static final String URL_LITELOADER_LIST = "http://dl.liteloader.com/versions/versions.json";

View File

@@ -49,26 +49,14 @@ public class EventHandler<T> {
events.add(t);
}
public void unregister(Event<T> t) {
events.remove(t);
}
public void unregister(Consumer<T> t) {
events.remove(t);
}
public void unregister(Runnable t) {
events.remove(t);
}
public boolean execute(T x) {
boolean flag = true;
for (Object t : events)
if (t instanceof Event) {
if (!((Event) t).call(sender, x))
if (!((Event<T>) t).call(sender, x))
flag = false;
} else if (t instanceof Consumer)
((Consumer) t).accept(x);
((Consumer<T>) t).accept(x);
else if (t instanceof Runnable)
((Runnable) t).run();
return flag;

View File

@@ -1,49 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util;
import org.jackhuang.hellominecraft.util.func.Consumer;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
/**
*
* @author huangyuhui
*/
public class LauncherPrintStream extends PrintStream {
private final ArrayList<Consumer<String>> printListeners = new ArrayList<>();
public LauncherPrintStream(OutputStream paramOutputStream) {
super(paramOutputStream);
}
@Override
public final void println(String paramString) {
super.println(paramString);
for (Consumer<String> a1 : printListeners)
a1.accept(paramString);
}
public final LauncherPrintStream addPrintListener(Consumer<String> paraml) {
this.printListeners.add(paraml);
return this;
}
}

View File

@@ -68,7 +68,7 @@ public class MinecraftVersionRequest implements Serializable {
private static MinecraftVersionRequest getVersionOfOldMinecraft(ZipFile file, ZipEntry entry) throws IOException {
MinecraftVersionRequest r = new MinecraftVersionRequest();
byte[] tmp = IOUtils.readFully(file.getInputStream(entry)).toByteArray();
byte[] tmp = IOUtils.toByteArray(file.getInputStream(entry));
byte[] bytes = "Minecraft Minecraft ".getBytes("ASCII");
int j = ArrayUtils.matchArray(tmp, bytes);
@@ -92,7 +92,7 @@ public class MinecraftVersionRequest implements Serializable {
private static MinecraftVersionRequest getVersionOfNewMinecraft(ZipFile file, ZipEntry entry) throws IOException {
MinecraftVersionRequest r = new MinecraftVersionRequest();
byte[] tmp = IOUtils.readFully(file.getInputStream(entry)).toByteArray();
byte[] tmp = IOUtils.toByteArray(file.getInputStream(entry));
byte[] str = "-server.txt".getBytes("ASCII");
int j = ArrayUtils.matchArray(tmp, str);

View File

@@ -55,10 +55,6 @@ public final class NetUtils {
return get(url, IOUtils.DEFAULT_CHARSET);
}
public static String get(URL url) throws IOException {
return get(url, Proxy.NO_PROXY);
}
public static String get(URL url, Proxy proxy) throws IOException {
return readData(createConnection(url, proxy));
}
@@ -123,12 +119,4 @@ public final class NetUtils {
return null;
}
}
public static URL concatenateURL(URL url, String query) {
try {
return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + (url.getQuery() != null && url.getQuery().length() > 0 ? '&' : '?') + query);
} catch (MalformedURLException ex) {
throw new IllegalArgumentException("Could not concatenate given URL with GET arguments!", ex);
}
}
}

View File

@@ -17,7 +17,6 @@
*/
package org.jackhuang.hellominecraft.util;
import java.awt.Dimension;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
@@ -72,15 +71,6 @@ public final class StrUtils {
return base != null && base.startsWith(match);
}
public static boolean startsWithOne(String[] a, String match) {
if (a == null)
return false;
for (String b : a)
if (startsWith(match, b))
return true;
return false;
}
public static boolean startsWithOne(Collection<String> a, String match) {
if (a == null)
return false;
@@ -97,21 +87,6 @@ public final class StrUtils {
return false;
}
public static boolean containsOne(String base, String... match) {
for (String s : match)
if (base.contains(s))
return true;
return false;
}
public static boolean containsOne(List<String> base, List<String> match) {
for (String a : base)
for (String b : match)
if (a.toLowerCase().contains(b.toLowerCase()))
return true;
return false;
}
public static boolean containsOne(List<String> base, List<String> match, Predicate<String> pred) {
for (String a : base)
for (String b : match)
@@ -142,12 +117,12 @@ public final class StrUtils {
return ver;
}
public static String parseParams(String addBefore, Collection paramArrayOfObject, String paramString) {
return parseParams(addBefore, paramArrayOfObject.toArray(), paramString);
public static String parseParams(String addBefore, Collection<?> objects, String addAfter) {
return parseParams(addBefore, objects.toArray(), addAfter);
}
public static String parseParams(String addBefore, Object[] params, String addAfter) {
return parseParams(t -> addBefore, params, t -> addAfter);
public static String parseParams(String addBefore, Object[] objects, String addAfter) {
return parseParams(t -> addBefore, objects, t -> addAfter);
}
public static String parseParams(Function<Object, String> beforeFunc, Object[] params, Function<Object, String> afterFunc) {
@@ -179,37 +154,19 @@ public final class StrUtils {
return sb.toString();
}
public static boolean equals(String base, String to) {
if (base == null)
return to == null;
else
return base.equals(to);
}
public static Dimension parseDimension(String str) {
String[] tokenized = tokenize(str, "x,");
if (tokenized.length != 2)
return null;
int i = MathUtils.parseInt(tokenized[0], -1);
int j = MathUtils.parseInt(tokenized[1], -1);
if ((i < 0) || (j < 0))
return null;
return new Dimension(i, j);
}
public static String[] tokenize(String paramString1) {
return tokenize(paramString1, " \t\n\r\f");
}
public static String[] tokenize(String paramString1, String paramString2) {
ArrayList localArrayList = new ArrayList();
StringTokenizer tokenizer = new StringTokenizer(paramString1, paramString2);
public static String[] tokenize(String str, String delim) {
ArrayList<String> al = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(str, delim);
while (tokenizer.hasMoreTokens()) {
paramString2 = tokenizer.nextToken();
localArrayList.add(paramString2);
delim = tokenizer.nextToken();
al.add(delim);
}
return (String[]) localArrayList.toArray(new String[localArrayList.size()]);
return al.toArray(new String[al.size()]);
}
public static boolean isBlank(String s) {
@@ -226,14 +183,4 @@ public final class StrUtils {
t.printStackTrace(writer);
return trace.toString();
}
public static List<Integer> findAllPos(String t, String p) {
ArrayList<Integer> ret = new ArrayList<>();
int i = 0, index;
while ((index = t.indexOf(p, i)) != -1) {
ret.add(index);
i = index + p.length();
}
return ret;
}
}

View File

@@ -47,7 +47,7 @@ public final class UpdateChecker implements IUpdateChecker {
@Override
public AbstractSwingWorker<VersionNumber> process(final boolean showMessage) {
return new AbstractSwingWorker() {
return new AbstractSwingWorker<VersionNumber>() {
@Override
protected void work() throws Exception {
if (value == null) {
@@ -74,12 +74,12 @@ public final class UpdateChecker implements IUpdateChecker {
@Override
public synchronized AbstractSwingWorker<Map<String, String>> requestDownloadLink() {
return new AbstractSwingWorker() {
return new AbstractSwingWorker<Map<String, String>>() {
@Override
protected void work() throws Exception {
if (download_link == null)
try {
download_link = C.GSON.fromJson(NetUtils.get("http://huangyuhui.duapp.com/update_link.php?type=" + type), Map.class);
download_link = C.GSON.<Map<String, String>>fromJson(NetUtils.get("http://huangyuhui.duapp.com/update_link.php?type=" + type), Map.class);
} catch (JsonSyntaxException | IOException e) {
HMCLog.warn("Failed to get update link.", e);
}

View File

@@ -52,7 +52,7 @@ public final class Utils {
*/
public static void shutdownForcely(int status) throws Exception {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
Class z = Class.forName("java.lang.Shutdown");
Class<?> z = Class.forName("java.lang.Shutdown");
Method exit = z.getDeclaredMethod("exit", int.class);
exit.setAccessible(true);
exit.invoke(z, status);

View File

@@ -1,102 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.code;
/**
*
* @author huangyuhui
*/
public final class Base64 {
private Base64() {
}
public static char[] encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false;
boolean trip = false;
int val = (0xFF & (int) data[i]);
val <<= 8;
if ((i + 1) < data.length) {
val |= (0xFF & (int) data[i + 1]);
trip = true;
}
val <<= 8;
if ((i + 2) < data.length) {
val |= (0xFF & (int) data[i + 2]);
quad = true;
}
out[index + 3] = ALPHABET[(quad ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 2] = ALPHABET[(trip ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 1] = ALPHABET[val & 0x3F];
val >>= 6;
out[index + 0] = ALPHABET[val & 0x3F];
}
return out;
}
public static char[] encode(String s) {
return encode(s.getBytes(Charsets.UTF_8));
}
public static byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 && data[data.length - 1] == '=')
--len;
if (data.length > 1 && data[data.length - 2] == '=')
--len;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = CODES[data[ix] & 0xFF];
if (value >= 0) {
accum <<= 6;
shift += 6;
accum |= value;
if (shift >= 8) {
shift -= 8;
out[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != out.length)
throw new Error("miscalculated data length!");
return out;
}
private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();
private static final byte[] CODES = new byte[256];
static {
for (int i = 0; i < 256; i++)
CODES[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
CODES[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
CODES[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
CODES[i] = (byte) (52 + i - '0');
CODES['+'] = 62;
CODES['/'] = 63;
}
}

View File

@@ -18,13 +18,15 @@
package org.jackhuang.hellominecraft.util.code;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import org.jackhuang.hellominecraft.util.system.IOUtils;
public final class Charsets {
private Charsets() {
}
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
/*public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
public static final Charset US_ASCII = Charset.forName("US-ASCII");
@@ -32,15 +34,22 @@ public final class Charsets {
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");*/
public static final Charset UTF_8 = Charset.forName("UTF-8");
public static Charset toCharset(Charset charset) {
return charset == null ? Charset.defaultCharset() : charset;
}
public static final Charset DEFAULT_CHARSET = UTF_8;
public static Charset toCharset(String charset) {
return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
if (charset == null) return Charset.defaultCharset();
try {
return Charset.forName(charset);
} catch(UnsupportedCharsetException ignored) {
return Charset.defaultCharset();
}
}
public static Charset toCharset() {
return toCharset(System.getProperty("sun.jnu.encoding", IOUtils.DEFAULT_CHARSET));
}
}

View File

@@ -70,11 +70,6 @@ public final class DigestUtils {
return getDigest("SHA-512");
}
@Deprecated
public static MessageDigest getShaDigest() {
return getSha1Digest();
}
public static byte[] md2(byte[] data) {
return getMd2Digest().digest(data);
}
@@ -127,22 +122,6 @@ public final class DigestUtils {
return Hex.encodeHexString(md5(data));
}
@Deprecated
public static byte[] sha(byte[] data) {
return sha1(data);
}
@Deprecated
public static byte[] sha(InputStream data)
throws IOException {
return sha1(data);
}
@Deprecated
public static byte[] sha(String data) {
return sha1(data);
}
public static byte[] sha1(byte[] data) {
return getSha1Digest().digest(data);
}
@@ -247,22 +226,6 @@ public final class DigestUtils {
return Hex.encodeHexString(sha512(data));
}
@Deprecated
public static String shaHex(byte[] data) {
return sha1Hex(data);
}
@Deprecated
public static String shaHex(InputStream data)
throws IOException {
return sha1Hex(data);
}
@Deprecated
public static String shaHex(String data) {
return sha1Hex(data);
}
public static MessageDigest updateDigest(MessageDigest messageDigest, byte[] valueToDigest) {
messageDigest.update(valueToDigest);
return messageDigest;

View File

@@ -21,8 +21,6 @@ import java.nio.charset.Charset;
public final class Hex {
public static final Charset DEFAULT_CHARSET = Charsets.UTF_8;
public static final String DEFAULT_CHARSET_NAME = "UTF-8";
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
@@ -80,17 +78,13 @@ public final class Hex {
}
public Hex() {
this.charset = DEFAULT_CHARSET;
this(Charsets.DEFAULT_CHARSET);
}
public Hex(Charset charset) {
this.charset = charset;
}
public Hex(String charsetName) {
this(Charset.forName(charsetName));
}
public byte[] decode(byte[] array) throws Exception {
return decodeHex(new String(array, getCharset()).toCharArray());
}

View File

@@ -1,26 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.func;
/**
* @author huangyuhui
*/
public interface BiConsumer<V, V2> {
void call(V value, V2 value2);
}

View File

@@ -1,27 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.func;
/**
*
* @author huangyuhui
*/
public interface TriConsumer<V1, V2, V3> {
void onDone(V1 v1, V2 v2, V3 v3);
}

View File

@@ -21,7 +21,7 @@ import org.jackhuang.hellominecraft.util.logging.appender.IAppender;
public class AppenderControl {
private final ThreadLocal<AppenderControl> recursive = new ThreadLocal();
private final ThreadLocal<AppenderControl> recursive = new ThreadLocal<>();
private final IAppender appender;
private final Level level;
private final int intLevel;

View File

@@ -35,18 +35,10 @@ public class HMCLog {
LOGGER.warn(message);
}
public static void debug(String message) {
LOGGER.debug(message);
}
public static void warn(String msg, Throwable t) {
LOGGER.warn(msg, t);
}
public static void debug(String msg, Throwable t) {
LOGGER.debug(msg, t);
}
public static void err(String msg) {
LOGGER.error(msg);
}

View File

@@ -27,7 +27,6 @@ import java.util.regex.Pattern;
*/
public enum Level {
OFF(0, Color.gray),
FATAL(1, Color.red),
ERROR(2, Color.red),
WARN(3, Color.orange),
@@ -48,10 +47,6 @@ public enum Level {
return this.level <= level.level;
}
public boolean lessOrEqual(int level) {
return this.level <= level;
}
public static final Pattern MINECRAFT_LOGGER = Pattern.compile("\\[(?<timestamp>[0-9:]+)\\] \\[[^/]+/(?<level>[^\\]]+)\\]");
public static final String JAVA_SYMBOL = "([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$][a-zA-Z\\d_$]*";

View File

@@ -28,7 +28,6 @@ public abstract class AbstractLogger
public static final Class<? extends IMessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS = ParameterizedMessageFactory.class;
private static final String FQCN = AbstractLogger.class.getName();
private static final String THROWING = "throwing";
private static final String CATCHING = "catching";
private final String name;
@@ -68,50 +67,6 @@ public abstract class AbstractLogger
catching(Level.ERROR, t);
}
@Override
public void debug(IMessage msg) {
if (isEnabled(Level.DEBUG, msg, null))
log(Level.DEBUG, msg, null);
}
@Override
public void debug(IMessage msg, Throwable t) {
if (isEnabled(Level.DEBUG, msg, t))
log(Level.DEBUG, msg, t);
}
@Override
public void debug(Object message) {
if (isEnabled(Level.DEBUG, message, null))
log(Level.DEBUG, this.messageFactory.newMessage(message), null);
}
@Override
public void debug(Object message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t);
}
@Override
public void debug(String message) {
if (isEnabled(Level.DEBUG, message))
log(Level.DEBUG, this.messageFactory.newMessage(message), null);
}
@Override
public void debug(String message, Object[] params) {
if (isEnabled(Level.DEBUG, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.DEBUG, msg, msg.getThrowable());
}
}
@Override
public void debug(String message, Throwable t) {
if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t);
}
@Override
public void entry() {
entry(new Object[0]);
@@ -395,50 +350,6 @@ public abstract class AbstractLogger
return this.name;
}
@Override
public void trace(IMessage msg) {
if (isEnabled(Level.TRACE, msg, null))
log(Level.TRACE, msg, null);
}
@Override
public void trace(IMessage msg, Throwable t) {
if (isEnabled(Level.TRACE, msg, t))
log(Level.TRACE, msg, t);
}
@Override
public void trace(Object message) {
if (isEnabled(Level.TRACE, message, null))
log(Level.TRACE, this.messageFactory.newMessage(message), null);
}
@Override
public void trace(Object message, Throwable t) {
if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t);
}
@Override
public void trace(String message) {
if (isEnabled(Level.TRACE, message))
log(Level.TRACE, this.messageFactory.newMessage(message), null);
}
@Override
public void trace(String message, Object[] params) {
if (isEnabled(Level.TRACE, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.TRACE, msg, msg.getThrowable());
}
}
@Override
public void trace(String message, Throwable t) {
if (isEnabled(Level.TRACE, message, t))
log(Level.TRACE, this.messageFactory.newMessage(message), t);
}
@Override
public void warn(IMessage msg) {
if (isEnabled(Level.WARN, msg, null))

View File

@@ -30,20 +30,6 @@ public interface ILogger {
void catching(Throwable paramThrowable);
void debug(IMessage paramIMessage);
void debug(IMessage paramIMessage, Throwable paramThrowable);
void debug(Object paramObject);
void debug(Object paramObject, Throwable paramThrowable);
void debug(String paramString);
void debug(String paramString, Object[] paramArrayOfObject);
void debug(String paramString, Throwable paramThrowable);
void entry();
void entry(Object[] paramArrayOfObject);
@@ -126,20 +112,6 @@ public interface ILogger {
<T extends Throwable> T throwing(T paramT);
void trace(IMessage paramIMessage);
void trace(IMessage paramIMessage, Throwable paramThrowable);
void trace(Object paramObject);
void trace(Object paramObject, Throwable paramThrowable);
void trace(String paramString);
void trace(String paramString, Object[] paramArrayOfObject);
void trace(String paramString, Throwable paramThrowable);
void warn(IMessage paramIMessage);
void warn(IMessage paramIMessage, Throwable paramThrowable);

View File

@@ -31,7 +31,7 @@ import org.jackhuang.hellominecraft.util.logging.message.IMessageFactory;
public class Logger extends AbstractLogger {
protected volatile PrivateConfig config;
private final Map<String, AppenderControl> appenders = new ConcurrentHashMap();
private final Map<String, AppenderControl> appenders = new ConcurrentHashMap<>();
public Logger(String name) {
this(name, null, Level.INFO);
@@ -109,8 +109,8 @@ public class Logger extends AbstractLogger {
}
public Map<String, IAppender> getAppenders() {
Map map = new HashMap();
for (Map.Entry entry : this.appenders.entrySet())
Map<String, IAppender> map = new HashMap<>();
for (Map.Entry<String, AppenderControl> entry : this.appenders.entrySet())
map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender());
return map;
}

View File

@@ -1,137 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.logging.logger;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jackhuang.hellominecraft.util.logging.Level;
import org.jackhuang.hellominecraft.util.logging.message.IMessage;
import org.jackhuang.hellominecraft.util.logging.message.IMessageFactory;
public class SimpleLogger extends AbstractLogger {
private static final char SPACE = ' ';
private DateFormat dateFormatter;
private Level level;
private final boolean showDateTime;
private final boolean showContextMap;
private PrintStream stream;
private final String logName;
public SimpleLogger(String name, Level defaultLevel, boolean showLogName, boolean showShortLogName, boolean showDateTime, boolean showContextMap, String dateTimeFormat, IMessageFactory messageFactory, PrintStream stream) {
super(name, messageFactory);
this.level = defaultLevel;
if (showShortLogName) {
int index = name.lastIndexOf('.');
if ((index > 0) && (index < name.length()))
this.logName = name.substring(index + 1);
else
this.logName = name;
} else if (showLogName)
this.logName = name;
else
this.logName = null;
this.showDateTime = showDateTime;
this.showContextMap = showContextMap;
this.stream = stream;
if (showDateTime)
try {
this.dateFormatter = new SimpleDateFormat(dateTimeFormat);
} catch (IllegalArgumentException e) {
this.dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS zzz");
}
}
public void setStream(PrintStream stream) {
this.stream = stream;
}
public Level getLevel() {
return this.level;
}
public void setLevel(Level level) {
if (level != null)
this.level = level;
}
@Override
public void abstractLog(Level level, IMessage msg, Throwable throwable) {
StringBuilder sb = new StringBuilder();
if (this.showDateTime) {
Date now = new Date();
String dateText;
synchronized (this.dateFormatter) {
dateText = this.dateFormatter.format(now);
}
sb.append(dateText);
sb.append(SPACE);
}
sb.append(level.toString());
sb.append(SPACE);
if ((this.logName != null) && (this.logName.length() > 0)) {
sb.append(this.logName);
sb.append(SPACE);
}
sb.append(msg.getFormattedMessage());
Object[] params = msg.getParameters();
Throwable t;
if ((throwable == null) && (params != null) && ((params[(params.length - 1)] instanceof Throwable)))
t = (Throwable) params[(params.length - 1)];
else
t = throwable;
if (t != null) {
sb.append(SPACE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.printStackTrace(new PrintStream(baos));
sb.append(baos.toString());
}
this.stream.println(sb.toString());
}
@Override
protected boolean isEnabled(Level level, String msg) {
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, String msg, Throwable t) {
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, String msg, Object[] p1) {
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, Object msg, Throwable t) {
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, IMessage msg, Throwable t) {
return this.level.level >= level.level;
}
}

View File

@@ -22,7 +22,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@@ -230,7 +229,7 @@ public class ParameterizedMessage
if (o instanceof String)
return (String) o;
StringBuilder str = new StringBuilder();
Set dejaVu = new HashSet();
Set<String> dejaVu = new HashSet<>();
recursiveDeepToString(o, str, dejaVu);
return str.toString();
}
@@ -244,7 +243,7 @@ public class ParameterizedMessage
str.append(o);
return;
}
Class oClass = o.getClass();
Class<?> oClass = o.getClass();
if (oClass.isArray())
if (oClass == byte[].class)
str.append(Arrays.toString((byte[]) (byte[]) o));
@@ -265,7 +264,7 @@ public class ParameterizedMessage
else {
String id = identityToString(o);
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
str.append(RECURSION_PREFIX).append(id).append(RECURSION_SUFFIX);
else {
dejaVu.add(id);
Object[] oArray = (Object[]) (Object[]) o;
@@ -276,7 +275,7 @@ public class ParameterizedMessage
first = false;
else
str.append(", ");
recursiveDeepToString(current, str, new HashSet(dejaVu));
recursiveDeepToString(current, str, new HashSet<>(dejaVu));
}
str.append("]");
}
@@ -284,42 +283,40 @@ public class ParameterizedMessage
else if ((o instanceof Map)) {
String id = identityToString(o);
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
str.append(RECURSION_PREFIX).append(id).append(RECURSION_SUFFIX);
else {
dejaVu.add(id);
Map oMap = (Map) o;
Map<?, ?> oMap = (Map<?, ?>) o;
str.append("{");
boolean isFirst = true;
for (Object o1 : oMap.entrySet()) {
Map.Entry current = (Map.Entry) o1;
for (Map.Entry<?, ?> current : oMap.entrySet()) {
if (isFirst)
isFirst = false;
else
str.append(", ");
Object key = current.getKey();
Object value = current.getValue();
recursiveDeepToString(key, str, new HashSet(dejaVu));
recursiveDeepToString(key, str, new HashSet<>(dejaVu));
str.append("=");
recursiveDeepToString(value, str, new HashSet(dejaVu));
recursiveDeepToString(value, str, new HashSet<>(dejaVu));
}
str.append("}");
}
} else if ((o instanceof Collection)) {
String id = identityToString(o);
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
str.append(RECURSION_PREFIX).append(id).append(RECURSION_SUFFIX);
else {
dejaVu.add(id);
Collection oCol = (Collection) o;
Collection<?> oCol = (Collection<?>) o;
str.append("[");
boolean isFirst = true;
for (Iterator i$ = oCol.iterator(); i$.hasNext();) {
Object anOCol = i$.next();
for (Object anOCol : oCol) {
if (isFirst)
isFirst = false;
else
str.append(", ");
recursiveDeepToString(anOCol, str, new HashSet(dejaVu));
recursiveDeepToString(anOCol, str, new HashSet<>(dejaVu));
}
str.append("]");
}
@@ -332,17 +329,17 @@ public class ParameterizedMessage
try {
str.append(o.toString());
} catch (Throwable t) {
str.append("[!!!");
str.append(ERROR_PREFIX);
str.append(identityToString(o));
str.append("=>");
str.append(ERROR_SEPARATOR);
String msg = t.getMessage();
String className = t.getClass().getName();
str.append(className);
if (!className.equals(msg)) {
str.append(":");
str.append(ERROR_MSG_SEPARATOR);
str.append(msg);
}
str.append("!!!]");
str.append(ERROR_SUFFIX);
}
}

View File

@@ -23,8 +23,6 @@ package org.jackhuang.hellominecraft.util.logging.message;
*/
public final class ParameterizedMessageFactory extends AbstractMessageFactory {
public static final ParameterizedMessageFactory INSTANCE = new ParameterizedMessageFactory();
@Override
public IMessage newMessage(String message, Object[] params) {
return new ParameterizedMessage(message, params);

View File

@@ -17,10 +17,7 @@
*/
package org.jackhuang.hellominecraft.util.system;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -55,9 +52,7 @@ public final class CompressingUtils {
* @throws java.io.IOException 压缩失败或无法读取
*/
public static void zip(File sourceDir, File zipFile, BiFunction<String, Boolean, String> pathNameCallback) throws IOException {
FileOutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
try (ZipOutputStream zos = new ZipOutputStream(FileUtils.openOutputStream(zipFile))) {
String basePath;
if (sourceDir.isDirectory())
basePath = sourceDir.getPath();
@@ -68,30 +63,6 @@ public final class CompressingUtils {
}
}
/**
* 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件
*
* @param sourceDir 源文件夹
* @param zipFile 压缩生成的zip文件路径。
* @param pathNameCallback callback(pathName, isDirectory) returns your
* modified pathName
*
* @throws java.io.IOException 压缩失败或无法读取
*/
public static ZipOutputStream zipContinuing(File sourceDir, File zipFile, BiFunction<String, Boolean, String> pathNameCallback) throws IOException {
FileOutputStream os = new FileOutputStream(zipFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
String basePath;
if (sourceDir.isDirectory())
basePath = sourceDir.getPath();
else//直接压缩单个文件时,取父目录
basePath = sourceDir.getParent();
zipFile(sourceDir, basePath, zos, pathNameCallback);
return zos;
}
}
/**
* 将文件压缩成zip文件
*
@@ -128,18 +99,13 @@ public final class CompressingUtils {
pathName = pathNameCallback.apply(pathName, true);
if (pathName == null)
continue;
try (InputStream is = new FileInputStream(file)) {
BufferedInputStream bis = new BufferedInputStream(is);
try (InputStream is = FileUtils.openInputStream(file)) {
zos.putNextEntry(new ZipEntry(pathName));
IOUtils.copyStream(bis, zos, buf);
IOUtils.copyStream(is, zos, buf);
}
}
}
public static void unzip(String zipFileName, String extPlace) throws IOException {
unzip(new File(zipFileName), new File(extPlace));
}
public static void unzip(File zipFileName, File extPlace) throws IOException {
unzip(zipFileName, extPlace, null, true);
}
@@ -157,7 +123,7 @@ public final class CompressingUtils {
public static void unzip(File zipFileName, File extPlace, Predicate<String> callback, boolean ignoreExistsFile) throws IOException {
byte[] buf = new byte[1024];
extPlace.mkdirs();
try (ZipInputStream zipFile = new ZipInputStream(new FileInputStream(zipFileName))) {
try (ZipInputStream zipFile = new ZipInputStream(FileUtils.openInputStream(zipFileName))) {
if (zipFileName.exists()) {
String strPath, gbkPath, strtemp;
strPath = extPlace.getAbsolutePath();
@@ -186,7 +152,7 @@ public final class CompressingUtils {
}
if (ignoreExistsFile && new File(strtemp).exists())
continue;
try (FileOutputStream fos = new FileOutputStream(strtemp)) {
try (FileOutputStream fos = FileUtils.openOutputStream(new File(strtemp))) {
IOUtils.copyStream(zipFile, fos, buf);
}
}

View File

@@ -152,11 +152,11 @@ public final class FileUtils {
if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath()))
throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
List exclusionList = null;
List<String> exclusionList = null;
if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if ((srcFiles != null) && (srcFiles.length > 0)) {
exclusionList = new ArrayList(srcFiles.length);
exclusionList = new ArrayList<>(srcFiles.length);
for (File srcFile : srcFiles) {
File copiedFile = new File(destDir, srcFile.getName());
exclusionList.add(copiedFile.getCanonicalPath());
@@ -193,12 +193,12 @@ public final class FileUtils {
public static String read(File file)
throws IOException {
return IOUtils.toString(IOUtils.openInputStream(file));
return IOUtils.toString(openInputStream(file));
}
public static String readQuietly(File file) {
try {
return IOUtils.toString(IOUtils.openInputStream(file));
return IOUtils.toString(openInputStream(file));
} catch (IOException ex) {
HMCLog.err("Failed to read file: " + file, ex);
return null;
@@ -207,15 +207,7 @@ public final class FileUtils {
public static String read(File file, String charset)
throws IOException {
return IOUtils.toString(IOUtils.openInputStream(file), charset);
}
public static String readIgnoreFileNotFound(File file) throws IOException {
try {
return IOUtils.toString(IOUtils.openInputStream(file));
} catch (FileNotFoundException ex) {
return "";
}
return IOUtils.toString(openInputStream(file), charset);
}
public static void copyFileQuietly(File srcFile, File destFile) {
@@ -371,7 +363,7 @@ public final class FileUtils {
}
public static File[] searchSuffix(File dir, String suffix) {
ArrayList<File> al = new ArrayList();
ArrayList<File> al = new ArrayList<>();
File[] files = dir.listFiles();
if (files == null)
return new File[0];

View File

@@ -21,8 +21,6 @@ import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -81,16 +79,6 @@ public final class IOUtils {
return t;
}
public static String extractLastDirectory(String dir) {
String t = removeLastSeparator(dir);
int i = t.length() - 1;
while (i >= 0 && !isSeparator(dir.charAt(i)))
i--;
if (i < 0)
return t;
return t.substring(i + 1, (t.length() - i) + (i + 1) - 1);
}
public static void findAllFile(File f, Consumer<String> callback) {
if (f.isDirectory()) {
File[] f1 = f.listFiles();
@@ -110,7 +98,7 @@ public final class IOUtils {
callback.accept(f1[i].getName());
}
}
public static String getRealPath() {
String realPath = IOUtils.class.getClassLoader().getResource("").getFile();
java.io.File file = new java.io.File(realPath);
@@ -171,11 +159,6 @@ public final class IOUtils {
return mac;
}
public static String extractFileName(String fileName) {
File file = new File(fileName);
return file.getName();
}
public static String getJavaDir() {
return getJavaDir(System.getProperty("java.home"));
}
@@ -246,18 +229,6 @@ public final class IOUtils {
output.write(data.getBytes(encoding));
}
public static FileInputStream openInputStream(File file)
throws IOException {
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory");
if (!file.canRead())
throw new IOException("File '" + file + "' cannot be read");
} else
throw new FileNotFoundException("File '" + file + "' does not exist");
return new FileInputStream(file);
}
public static String tryGetCanonicalFolderPath(File file) {
try {
return IOUtils.addSeparator(file.getCanonicalPath());

View File

@@ -30,10 +30,12 @@ public class JavaProcess {
private final List<String> commands;
private final Process process;
private final ArrayList<String> stdOutLines = new ArrayList<>();
private final ProcessManager pm;
public JavaProcess(List<String> commands, Process process, ProcessManager pm) {
this.commands = commands;
this.process = process;
this.pm = pm;
if (pm != null)
pm.registerProcess(this);
}
@@ -53,6 +55,10 @@ public class JavaProcess {
public String getStartupCommand() {
return this.process.toString();
}
public ProcessManager getProcessManager() {
return pm;
}
public ArrayList<String> getStdOutLines() {
return this.stdOutLines;

View File

@@ -115,15 +115,6 @@ public final class JdkVersion implements Cloneable {
*/
public static final int JAVA_19 = 6;
private static final String JAVA_VER;
private static final int MAJOR_JAVA_VER;
static {
JAVA_VER = System.getProperty("java.version");
// version String should look like "1.4.2_10"
MAJOR_JAVA_VER = parseVersion(JAVA_VER);
}
private static int parseVersion(String javaVersion) {
if (StrUtils.isBlank(javaVersion))
return UNKOWN;
@@ -139,42 +130,6 @@ public final class JdkVersion implements Cloneable {
return a;
}
/**
* Return the full Java version string, as returned by
* <code>System.getProperty("java.version")</code>.
*
* @return the full Java version string
*
* @see System#getProperty(String)
*/
public static String getJavaVersion() {
return JAVA_VER;
}
/**
* Get the major version code. This means we can do things like
* <code>if (getMajorJavaVersion() < JAVA_14)</code>. @retu
*
*
* rn a code comparable to the JAVA_XX codes in this class
*
* @return
*
* @see #JAVA_13
* @see #JAVA_14
* @see #JAVA_15
* @see #JAVA_16
* @see #JAVA_17
*/
public static int getMajorJavaVersion() {
return MAJOR_JAVA_VER;
}
public static boolean isJava64Bit() {
String jdkBit = System.getProperty("sun.arch.data.model");
return jdkBit.contains("64");
}
private static final Pattern p = Pattern.compile("java version \"[1-9]*\\.[1-9]*\\.[0-9]*(.*?)\"");
public static JdkVersion getJavaVersionFromExecutable(String file) throws IOException {
@@ -197,11 +152,6 @@ public final class JdkVersion implements Cloneable {
return new JdkVersion(file, ver, platform);
}
public void write(File f) throws IOException {
if (ver != null && getPlatform() != Platform.UNKNOWN)
FileUtils.write(f, ver + "\n" + platform);
}
public boolean isEarlyAccess() {
return getVersion() != null && getVersion().endsWith("-ea");
}

View File

@@ -20,7 +20,6 @@ package org.jackhuang.hellominecraft.util.system;
import com.sun.management.OperatingSystemMXBean;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
@@ -92,7 +91,7 @@ public enum OS {
public static long[] memoryInfoForLinux() throws IOException {
File file = new File("/proc/meminfo");
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charsets.UTF_8))) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(FileUtils.openInputStream(file), Charsets.UTF_8))) {
long[] result = new long[4];
String str;
StringTokenizer token;

View File

@@ -25,7 +25,7 @@ import java.util.HashSet;
*/
public class ProcessManager {
private static final HashSet<JavaProcess> GAME_PROCESSES = new HashSet();
private static final HashSet<JavaProcess> GAME_PROCESSES = new HashSet<>();
public void registerProcess(JavaProcess jp) {
GAME_PROCESSES.add(jp);

View File

@@ -21,9 +21,9 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.EventHandler;
import org.jackhuang.hellominecraft.util.code.Charsets;
/**
*
@@ -50,15 +50,9 @@ public class ProcessThread extends Thread {
BufferedReader br = null;
try {
InputStream in = p.getRawProcess().getInputStream();
try {
br = new BufferedReader(new InputStreamReader(in, System.getProperty("sun.jnu.encoding", "UTF-8")));
} catch (UnsupportedEncodingException ex) {
HMCLog.warn("Unsupported encoding: " + System.getProperty("sun.jnu.encoding", "UTF-8"), ex);
br = new BufferedReader(new InputStreamReader(in));
}
br = new BufferedReader(new InputStreamReader(in, Charsets.toCharset()));
int ch;
String line = "";
String line;
while (p.isRunning())
while ((line = br.readLine()) != null) {
printlnEvent.execute(line);
@@ -70,6 +64,8 @@ public class ProcessThread extends Thread {
System.out.println("Minecraft: " + line);
p.getStdOutLines().add(line);
}
if (p.getProcessManager() != null)
p.getProcessManager().onProcessStopped(p);
stopEvent.execute(p);
} catch (IOException e) {
HMCLog.err("An error occured when reading process stdout/stderr.", e);

View File

@@ -1,47 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.system;
import org.jackhuang.hellominecraft.util.func.Consumer;
/**
*
* @author huangyuhui
*/
public class ThreadExecutor extends Thread {
public final Consumer<Throwable> c;
public final Runnable r;
public ThreadExecutor(Consumer<Throwable> c, Runnable r) {
super();
this.c = c;
this.r = r;
}
@Override
public void run() {
try {
r.run();
c.accept(null);
} catch (Throwable t) {
c.accept(t);
}
}
}

View File

@@ -22,7 +22,6 @@ import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
@@ -41,8 +40,7 @@ public class ZipEngine implements Closeable {
ZipOutputStream zos;
public ZipEngine(File f) throws IOException {
FileOutputStream os = new FileOutputStream(f);
zos = new ZipOutputStream(new BufferedOutputStream(os));
zos = new ZipOutputStream(new BufferedOutputStream(FileUtils.openOutputStream(f)));
}
@Override
@@ -51,10 +49,6 @@ public class ZipEngine implements Closeable {
zos.close();
}
public void putDirectory(String sourceDir) throws IOException {
putDirectory(new File(sourceDir), null);
}
public void putDirectory(File sourceDir) throws IOException {
putDirectory(sourceDir, null);
}
@@ -117,7 +111,7 @@ public class ZipEngine implements Closeable {
}
public void putFile(File file, String pathName) throws IOException {
try (FileInputStream fis = new FileInputStream(file)) {
try (FileInputStream fis = FileUtils.openInputStream(file)) {
putStream(fis, pathName);
}
}

View File

@@ -1,46 +0,0 @@
/*
* Hello Minecraft!.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.tasks;
import java.io.File;
import org.jackhuang.hellominecraft.util.system.CompressingUtils;
/**
*
* @author huangyuhui
*/
public class DecompressTask extends Task {
File src, dest;
public DecompressTask(File src, File dest) {
this.src = src;
this.dest = dest;
}
@Override
public void executeTask(boolean areDependTasksSucceeded) throws Throwable {
CompressingUtils.unzip(src, dest);
}
@Override
public String getInfo() {
return "Decompress: " + src.getAbsolutePath() + " to " + dest.getAbsolutePath();
}
}

View File

@@ -22,6 +22,7 @@ package org.jackhuang.hellominecraft.util.tasks;
* @author huangyuhui
*/
public class NoShownTaskException extends RuntimeException {
private static final long serialVersionUID = 4893571368018439312L;
public NoShownTaskException(String msg) {
super(msg);

View File

@@ -18,7 +18,6 @@
package org.jackhuang.hellominecraft.util.tasks;
import java.util.Collection;
import org.jackhuang.hellominecraft.util.logging.HMCLog;
/**
*
@@ -102,14 +101,10 @@ public abstract class Task {
return this;
}
public Task after(Task t) {
public Task with(Task t) {
return new DoubleTask(this, t);
}
public Task before(Task t) {
return new DoubleTask(t, this);
}
public void runWithException() throws Throwable {
Collection<Task> c = getDependTasks();
if (c != null)
@@ -121,14 +116,4 @@ public abstract class Task {
for (Task t : c)
t.runWithException();
}
public boolean run() {
try {
runWithException();
return true;
} catch (Throwable t) {
HMCLog.err("Failed to execute task", t);
return false;
}
}
}

View File

@@ -40,7 +40,7 @@ public class TaskList extends Thread {
List<Task> taskQueue = Collections.synchronizedList(new LinkedList<>());
public final EventHandler<Object> doneEvent = new EventHandler<>(this);
ArrayList<DoingDoneListener<Task>> taskListener = new ArrayList();
ArrayList<DoingDoneListener<Task>> taskListener = new ArrayList<>();
int totTask;
boolean shouldContinue = true;
@@ -49,11 +49,6 @@ public class TaskList extends Thread {
setDaemon(true);
}
public void clean() {
shouldContinue = true;
taskQueue.clear();
}
public void addTaskListener(DoingDoneListener<Task> l) {
taskListener.add(l);
}

View File

@@ -44,7 +44,7 @@ public class TaskWindow extends javax.swing.JDialog
boolean suc = false;
private transient TaskList taskList;
private final ArrayList<String> failReasons = new ArrayList();
private final ArrayList<String> failReasons = new ArrayList<>();
private String stackTrace = null, lastStackTrace = null;
/**
@@ -299,7 +299,6 @@ public class TaskWindow extends javax.swing.JDialog
public static class TaskWindowFactory {
LinkedList<Task> ll = new LinkedList<>();
boolean flag;
public TaskWindowFactory append(Task ts) {
if (ts != null)

View File

@@ -237,7 +237,7 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
return filePath;
}
ArrayList<PreviousResult<String>> al = new ArrayList();
ArrayList<PreviousResult<String>> al = new ArrayList<>();
@Override
public Task registerPreviousResult(PreviousResult<String> pr) {

View File

@@ -1,26 +0,0 @@
/*
* Hello Minecraft! Launcher.
* Copyright (C) 2013 huangyuhui <huanghongxun2008@126.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
package org.jackhuang.hellominecraft.util.ui;
/**
*
* @author huang
*/
public interface AlwaysDirty {
}

View File

@@ -37,10 +37,6 @@ public class DropShadowBorder extends AbstractBorder {
private Insets insets = null;
RenderingHints hints;
public DropShadowBorder(Color color) {
this(color, 3);
}
public DropShadowBorder(Color color, int thickness) {
this.thickness = thickness;
this.color = color;
@@ -95,10 +91,4 @@ public class DropShadowBorder extends AbstractBorder {
}
g.drawImage(list, 0, 0, width, height, null);
}
void copyFromArray(int[] from, int W, int H, int[] to, int x, int y, int w, int h) {
for (int i = 0; i < h; ++i)
for (int j = 0; j < w; ++j)
to[i * w + j] = from[(i + y) * W + j + x];
}
}

View File

@@ -17,6 +17,7 @@
*/
package org.jackhuang.hellominecraft.util.ui;
import java.io.PrintStream;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
@@ -26,7 +27,6 @@ import org.jackhuang.hellominecraft.util.logging.HMCLog;
import org.jackhuang.hellominecraft.util.logging.Level;
import org.jackhuang.hellominecraft.util.func.NonFunction;
import org.jackhuang.hellominecraft.util.DoubleOutputStream;
import org.jackhuang.hellominecraft.util.LauncherPrintStream;
import org.jackhuang.hellominecraft.util.Utils;
/**
@@ -48,9 +48,9 @@ public class LogWindow extends javax.swing.JFrame {
movingEnd = true;
DoubleOutputStream out = new DoubleOutputStream(new LogWindowOutputStream(this, Level.INFO), System.out);
System.setOut(new LauncherPrintStream(out));
System.setOut(new PrintStream(out));
DoubleOutputStream err = new DoubleOutputStream(new LogWindowOutputStream(this, Level.ERROR), System.err);
System.setErr(new LauncherPrintStream(err));
System.setErr(new PrintStream(err));
SwingUtilities.invokeLater(() -> {
setLocationRelativeTo(null);
@@ -206,7 +206,7 @@ public class LogWindow extends javax.swing.JFrame {
}//GEN-LAST:event_btnCloseActionPerformed
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
this.txtLog.setText("");
clean();
}//GEN-LAST:event_btnClearActionPerformed
private void btnCopyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCopyActionPerformed
@@ -240,14 +240,6 @@ public class LogWindow extends javax.swing.JFrame {
SwingUtils.exitIfNoWindow(this);
}//GEN-LAST:event_formWindowClosing
public void log(String status) {
log(status, Level.INFO);
}
public void warning(String status) {
log(status, Level.WARN);
}
public synchronized void log(String status, Level c) {
status = status.replace("\t", " ");
Document d = txtLog.getStyledDocument();

View File

@@ -19,7 +19,6 @@ package org.jackhuang.hellominecraft.util.ui;
import java.io.OutputStream;
import java.util.Objects;
import java.util.Timer;
import javax.swing.SwingUtilities;
import org.jackhuang.hellominecraft.util.code.Charsets;
import org.jackhuang.hellominecraft.util.logging.Level;
@@ -30,8 +29,6 @@ import org.jackhuang.hellominecraft.util.logging.Level;
*/
public class LogWindowOutputStream extends OutputStream {
private static final Timer TIMER = new Timer();
private final LogWindow txt;
private final Level sas;
@@ -60,8 +57,4 @@ public class LogWindowOutputStream extends OutputStream {
public final void write(int i) {
append(new String(new byte[] { (byte) i }, Charsets.UTF_8));
}
public static void dispose() {
TIMER.cancel();
}
}

View File

@@ -40,7 +40,6 @@ import javax.swing.JOptionPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import org.jackhuang.hellominecraft.util.C;
@@ -70,15 +69,13 @@ public final class SwingUtils {
*
* @return
*/
public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) {
return new DefaultTableModel(
new Object[][] {},
titleA) {
Class[] types = typesA;
public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class<?>[] typesA, final boolean[] canEditA) {
return new DefaultTableModel(new Object[][] {}, titleA) {
Class<?>[] types = typesA;
boolean[] canEdit = canEditA;
@Override
public Class getColumnClass(int columnIndex) {
public Class<?> getColumnClass(int columnIndex) {
return types[columnIndex];
}
@@ -132,16 +129,6 @@ public final class SwingUtils {
}
}
/**
* Move the cursor to the end of TextArea.
*
* @param tf the TextArea
*/
public static void moveEnd(JTextArea tf) {
int position = tf.getText().length();
tf.setCaretPosition(position);
}
/**
* Move the cursor to the end of ScrollPane.
*
@@ -159,27 +146,8 @@ public final class SwingUtils {
*
* @return Forcely Type casted to DefaultListModel
*/
public static DefaultListModel getDefaultListModel(JList list) {
return (DefaultListModel) list.getModel();
}
/**
* Append new element to JList
*
* @param list the JList
* @param element the Element
*/
public static void appendLast(JList list, Object element) {
getDefaultListModel(list).addElement(element);
}
public static void replaceLast(JList list, Object element) {
DefaultListModel model = getDefaultListModel(list);
model.set(model.getSize() - 1, element);
}
public static void clear(JList list) {
list.setModel(new DefaultListModel());
public static <T> DefaultListModel<T> getDefaultListModel(JList<T> list) {
return (DefaultListModel<T>) list.getModel();
}
/**
@@ -269,13 +237,14 @@ public final class SwingUtils {
}
public static int select(String[] selList, String msg) {
JComboBox<String> box = new JComboBox<>(selList);
Object msgs[] = new Object[2];
msgs[0] = msg;
msgs[1] = new JComboBox(selList);
msgs[1] = box;
int result = JOptionPane.showOptionDialog(null, msgs, msg, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if (result == JOptionPane.CANCEL_OPTION)
return -1;
return ((JComboBox) msgs[1]).getSelectedIndex();
return box.getSelectedIndex();
}
public static void setEnabled(JComponent component, boolean t) {

View File

@@ -27,7 +27,6 @@ import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.tree.TreeCellRenderer;
import org.jackhuang.hellominecraft.util.Pair;
public class CheckBoxTreeCellRenderer extends JPanel implements TreeCellRenderer {

View File

@@ -44,7 +44,7 @@ public class CheckBoxTreeNode extends DefaultMutableTreeNode {
@Override
public String toString() {
if (userObject instanceof Pair)
return "<html>" + ((Pair) userObject).key + "<font color=gray>&nbsp;-&nbsp;" + ((Pair) userObject).value + "</font></html>";
return "<html>" + ((Pair<?, ?>) userObject).key + "<font color=gray>&nbsp;-&nbsp;" + ((Pair<?, ?>) userObject).value + "</font></html>";
else
return userObject.toString();
}

View File

@@ -15,9 +15,9 @@ package org.jackhuang.hellominecraft.util.ui.wizard.api;
import java.awt.Container;
import java.awt.Rectangle;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import javax.swing.Action;
import org.jackhuang.hellominecraft.util.ArrayUtils;
import org.jackhuang.hellominecraft.util.ui.wizard.api.displayer.WizardDisplayerImpl;
import org.jackhuang.hellominecraft.util.ui.wizard.spi.Wizard;
@@ -88,7 +88,6 @@ public abstract class WizardDisplayer {
protected WizardDisplayer() {
}
private static final String SYSPROP_KEY = "WizardDisplayer.default";
/**
* Display a wizard in a dialog, using the default implementation of
@@ -103,7 +102,7 @@ public abstract class WizardDisplayer {
* shown
* and entered in the wizard. May be null.
*/
public static Object showWizard(Wizard wizard, Rectangle rect, Action help, Map initialProperties) {
public static Object showWizard(Wizard wizard, Rectangle rect, Action help, Map<?, ?> initialProperties) {
// assert nonBuggyWizard (wizard);
// validate it
nonBuggyWizard(wizard);
@@ -124,31 +123,6 @@ public abstract class WizardDisplayer {
return showWizard(wizard, null, null, null);
}
/**
* Show a wizard with default window placement, showing the help button,
* which will invoke the passed action.
*
* @param wizard The wizard to show
* @param help An action to invoke if the user presses the help button
*
* @return The result of Wizard.finish()
*/
public static Object showWizard(Wizard wizard, Action help) {
return showWizard(wizard, null, help, null);
}
/**
* Show a wizard in the passed location on screen with no help button
*
* @param wizard The wizard to show
* @param r The rectangle on screen for the wizard
*
* @return The result of Wizard.finish()
*/
public static Object showWizard(Wizard wizard, Rectangle r) {
return showWizard(wizard, r, null, null);
}
/**
* Show a wizard.
*
@@ -165,46 +139,19 @@ public abstract class WizardDisplayer {
* @return Whatever object the wizard returns from its <code>finish()</code>
* method, if the Wizard was completed by the user.
*/
protected abstract Object show(Wizard wizard, Rectangle r, Action help, Map initialProperties);
/**
* Install a panel representing a Wizard in a user-supplied container
* with a user-supplied layout constraint.
*
* @param c The container the wizard panel should be added
* to. May not
* be null.
* @param layoutConstraint The argument to use when adding the wizard's
* ui component to the container. May be null.
* @param helpAction An action that should be invoked when the help
* button
* is clicked (if null, no help button will be displayed)
* @param initialProperties A set of properties that should be pre-set upon
* entering the wizard. May be null.
* @param receiver An object which will be called when the Finish
* or
* Cancel buttons are pressed. May not be null.
*/
public static void installInContainer(Container c, Object layoutConstraint,
Wizard awizard,
Action helpAction, Map initialProperties,
WizardResultReceiver receiver) {
getDefault().install(c, layoutConstraint, awizard, helpAction,
initialProperties, receiver);
}
protected abstract Object show(Wizard wizard, Rectangle r, Action help, Map<?, ?> initialProperties);
/**
* Instance implementation of installInContainer().
*/
protected abstract void install(Container c, Object layoutConstraint,
Wizard awizard, Action helpAction, Map initialProperties,
Wizard awizard, Action helpAction, Map<?, ?> initialProperties,
WizardResultReceiver receiver);
private static boolean nonBuggyWizard(Wizard wizard) {
String[] s = wizard.getAllSteps();
// assert new HashSet(Arrays.asList(s)).size() == s.length;
// for JDK 1.4.2: replace assert with runtime exception
if (new HashSet(Arrays.asList(s)).size() != s.length)
if (ArrayUtils.hasDuplicateElements(s))
throw new RuntimeException("steps are duplicated: " + Arrays.asList(s));
if (s.length == 1 && Wizard.UNDETERMINED_STEP.equals(s[0]))
// assert false : "Only ID may not be UNDETERMINED_ID";

View File

@@ -164,7 +164,7 @@ public class WizardDisplayerImpl extends WizardDisplayer {
* java.awt.Rectangle, javax.swing.Action, java.util.Map)
*/
private JPanel createOuterPanel(final Wizard awizard, Rectangle bounds, Action helpAction,
Map initialProperties) {
Map<?, ?> initialProperties) {
this.wizard = awizard;

View File

@@ -50,10 +50,10 @@ import java.util.Stack;
*
* @author Tim Boudreau
*/
public class MergeMap implements Map {
public class MergeMap<K, V> implements Map<K, V> {
private final Stack order = new Stack();
private final Map id2map = new HashMap();
private final Stack<String> order = new Stack<>();
private final Map<String, Map<K, V>> id2map = new HashMap<>();
/**
* Creates a new instance of MergeMap
@@ -71,7 +71,7 @@ public class MergeMap implements Map {
* have a first panel that gathered some settings using the old APIs
* framework, and we need to inject them here.
*/
public MergeMap(String currId, Map everpresent) {
public MergeMap(String currId, Map<K, V> everpresent) {
order.push(BASE);
id2map.put(BASE, everpresent);
push(currId);
@@ -81,16 +81,16 @@ public class MergeMap implements Map {
* Move to a different ID (meaning add a new named map to proxy which can be
* calved off if necessary).
*/
public Map push(String id) {
public Map<K, V> push(String id) {
// assert !order.contains(id) : id + " already present";
if (order.contains(id))
throw new RuntimeException(id + " already present");
// assert !order.contains(id) : id + " already present";
if (!order.isEmpty() && id.equals(order.peek()))
return (Map) id2map.get(id);
Map result = (Map) id2map.get(id);
return (Map<K, V>) id2map.get(id);
Map<K, V> result = (Map<K, V>) id2map.get(id);
if (result == null) {
result = new HashMap();
result = new HashMap<>();
id2map.put(id, result);
}
order.push(id);
@@ -115,7 +115,7 @@ public class MergeMap implements Map {
+ "entry");
//Get the current map
String result = (String) order.peek();
Map curr = (Map) id2map.get(result);
Map<K, V> curr = (Map<K, V>) id2map.get(result);
order.pop();
//Though unlikely, it is possible that a later step in a wizard
@@ -124,13 +124,11 @@ public class MergeMap implements Map {
//we're removing, and if any of them are in steps lower on the
//stack, change those lower steps values to whatever was written
//into the map we're calving off
for (Iterator i = orderIterator(); i.hasNext();) {
Map other = (Map) id2map.get(i.next());
for (Iterator j = curr.keySet().iterator(); j.hasNext();) {
Object key = j.next();
for (Iterator<String> i = orderIterator(); i.hasNext();) {
Map<K, V> other = (Map<K, V>) id2map.get(i.next());
for (K key : curr.keySet())
if (other.containsKey(key))
other.put(key, curr.get(key));
}
}
return result;
}
@@ -142,8 +140,8 @@ public class MergeMap implements Map {
@Override
public boolean containsKey(Object obj) {
for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next());
for (Iterator<String> i = orderIterator(); i.hasNext();) {
Map<K, V> curr = (Map<K, V>) id2map.get(i.next());
if (curr.containsKey(obj))
return true;
}
@@ -152,8 +150,8 @@ public class MergeMap implements Map {
@Override
public boolean containsValue(Object obj) {
for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next());
for (Iterator<String> i = orderIterator(); i.hasNext();) {
Map<K, V> curr = (Map<K, V>) id2map.get(i.next());
if (curr.containsValue(obj))
return true;
}
@@ -161,21 +159,21 @@ public class MergeMap implements Map {
}
@Override
public java.util.Set entrySet() {
HashSet result = new HashSet();
for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next());
public java.util.Set<Entry<K, V>> entrySet() {
HashSet<Entry<K, V>> result = new HashSet<>();
for (Iterator<String> i = orderIterator(); i.hasNext();) {
Map<K, V> curr = (Map<K, V>) id2map.get(i.next());
result.addAll(curr.entrySet());
}
return result;
}
@Override
public Object get(Object obj) {
for (Iterator i = orderIterator(); i.hasNext();) {
public V get(Object obj) {
for (Iterator<String> i = orderIterator(); i.hasNext();) {
String id = (String) i.next();
Map curr = (Map) id2map.get(id);
Object result = curr.get(obj);
Map<K, V> curr = (Map<K, V>) id2map.get(id);
V result = curr.get(obj);
if (result != null)
return result;
}
@@ -188,33 +186,33 @@ public class MergeMap implements Map {
}
@Override
public Set keySet() {
HashSet result = new HashSet();
for (Iterator i = orderIterator(); i.hasNext();) {
Map curr = (Map) id2map.get(i.next());
public Set<K> keySet() {
HashSet<K> result = new HashSet<>();
for (Iterator<String> i = orderIterator(); i.hasNext();) {
Map<K, V> curr = (Map<K, V>) id2map.get(i.next());
result.addAll(curr.keySet());
}
return result;
}
@Override
public Object put(Object obj, Object obj1) {
Map curr = (Map) id2map.get(order.peek());
public V put(K obj, V obj1) {
Map<K, V> curr = (Map<K, V>) id2map.get(order.peek());
return curr.put(obj, obj1);
}
@Override
public void putAll(Map map) {
Map curr = (Map) id2map.get(order.peek());
public void putAll(Map<? extends K, ? extends V> map) {
Map<K, V> curr = (Map<K, V>) id2map.get(order.peek());
curr.putAll(map);
}
private Object doRemove(Object obj) {
Map curr = (Map) id2map.get(order.peek());
Object result = curr.remove(obj);
private V doRemove(Object obj) {
Map<K, V> curr = (Map<K, V>) id2map.get(order.peek());
V result = curr.remove(obj);
if (result == null)
for (Iterator i = orderIterator(); i.hasNext();) {
curr = (Map) id2map.get(i.next());
for (Iterator<String> i = orderIterator(); i.hasNext();) {
curr = (Map<K, V>) id2map.get(i.next());
result = curr.remove(obj);
if (result != null)
break;
@@ -223,9 +221,9 @@ public class MergeMap implements Map {
}
@Override
public Object remove(Object obj) {
public V remove(Object obj) {
//Ensure we remove any duplicates in upper arrays
Object result = get(obj);
V result = get(obj);
while (get(obj) != null)
doRemove(obj);
return result;
@@ -238,40 +236,43 @@ public class MergeMap implements Map {
}
@Override
public Collection values() {
HashSet result = new HashSet();
Set keys = keySet();
for (Iterator i = keys.iterator(); i.hasNext();)
public Collection<V> values() {
HashSet<V> result = new HashSet<>();
Set<K> keys = keySet();
for (Iterator<K> i = keys.iterator(); i.hasNext();)
result.add(get(i.next()));
return result;
}
private Iterator orderIterator() {
private Iterator<String> orderIterator() {
return new ReverseIterator(order);
}
private static final class ReverseIterator implements Iterator {
private static final class ReverseIterator implements Iterator<String> {
private int pos;
private final List l;
private final List<String> l;
public ReverseIterator(Stack s) {
public ReverseIterator(Stack<String> s) {
pos = s.size() - 1;
l = new ArrayList(s);
l = new ArrayList<>(s);
}
@Override
public boolean hasNext() {
return pos != -1;
}
public Object next() {
@Override
public String next() {
if (pos < 0)
throw new NoSuchElementException();
Object result = l.get(pos);
String result = l.get(pos);
pos--;
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}

View File

@@ -28,10 +28,10 @@ import org.jackhuang.hellominecraft.util.func.Consumer;
*/
public abstract class AbstractWizard implements WizardImplementation {
protected final List listenerList = Collections.synchronizedList(new LinkedList());
protected final List<WizardObserver> listenerList = Collections.synchronizedList(new LinkedList<>());
protected void fireChanged(Consumer<WizardObserver> r) {
WizardObserver[] listeners = (WizardObserver[]) listenerList.toArray(new WizardObserver[listenerList.size()]);
WizardObserver[] listeners = listenerList.toArray(new WizardObserver[listenerList.size()]);
for (int i = listeners.length - 1; i >= 0; i--) {
WizardObserver l = (WizardObserver) listeners[i];

View File

@@ -27,7 +27,6 @@ import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.EventObject;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.*;
import javax.swing.table.*;
@@ -71,7 +70,7 @@ final class GenericListener
* Set of components that we're listening to models of, so we can look
* up the component from the model as needed
*/
private final Set listenedTo = new HashSet();
private final Set<Component> listenedTo = new HashSet<>();
private final WizardPage.CustomComponentListener extListener;
private final WizardPage.CustomComponentNotifier extNotifier;
@@ -150,9 +149,9 @@ final class GenericListener
attachToHierarchyOf((Container) jc);
else if (jc instanceof JList) {
listenedTo.add(jc);
((JList) jc).addListSelectionListener(this);
((JList<?>) jc).addListSelectionListener(this);
} else if (jc instanceof JComboBox)
((JComboBox) jc).addActionListener(this);
((JComboBox<?>) jc).addActionListener(this);
else if (jc instanceof JTree) {
listenedTo.add(jc);
((JTree) jc).getSelectionModel().addTreeSelectionListener(this);
@@ -189,9 +188,9 @@ final class GenericListener
if (isProbablyAContainer(jc))
detachFromHierarchyOf((Container) jc);
else if (jc instanceof JList)
((JList) jc).removeListSelectionListener(this);
((JList<?>) jc).removeListSelectionListener(this);
else if (jc instanceof JComboBox)
((JComboBox) jc).removeActionListener(this);
((JComboBox<?>) jc).removeActionListener(this);
else if (jc instanceof JTree)
((JTree) jc).getSelectionModel().removeTreeSelectionListener(this);
else if (jc instanceof JToggleButton)
@@ -271,34 +270,28 @@ final class GenericListener
wizardPage.userInputReceived((Component) ((EventObject) e).getSource(), e);
else if (e instanceof TreeSelectionEvent) {
TreeSelectionModel mdl = (TreeSelectionModel) ((TreeSelectionEvent) e).getSource();
for (Iterator i = listenedTo.iterator(); i.hasNext();) {
Object o = i.next();
for (Object o : listenedTo)
if (o instanceof JTree && ((JTree) o).getSelectionModel() == mdl) {
wizardPage.userInputReceived((Component) o, e);
break;
}
}
} else if (e instanceof DocumentEvent) {
Document document = ((DocumentEvent) e).getDocument();
for (Iterator i = listenedTo.iterator(); i.hasNext();) {
Object o = i.next();
for (Component o : listenedTo)
if (o instanceof JTextComponent && ((JTextComponent) o).getDocument() == document) {
wizardPage.userInputReceived((Component) o, e);
break;
}
}
} else if (e instanceof ListSelectionEvent) {
ListSelectionModel model = (ListSelectionModel) ((ListSelectionEvent) e).getSource();
for (Iterator i = listenedTo.iterator(); i.hasNext();) {
Object o = i.next();
if (o instanceof JList && ((JList) o).getSelectionModel() == model) {
for (Object o : listenedTo)
if (o instanceof JList && ((JList<?>) o).getSelectionModel() == model) {
wizardPage.userInputReceived((Component) o, e);
break;
} else if (o instanceof JTable && ((JTable) o).getSelectionModel() == model) {
wizardPage.userInputReceived((Component) o, e);
break;
}
}
} else
wizardPage.userInputReceived(null, e);
} finally {
@@ -307,10 +300,12 @@ final class GenericListener
}
}
@Override
public void actionPerformed(ActionEvent e) {
fire(e);
}
@Override
public void propertyChange(PropertyChangeEvent e) {
if (e.getSource() instanceof JComponent && "name".equals(e.getPropertyName())) {
// Note - most components do NOT fire a property change on
@@ -324,10 +319,12 @@ final class GenericListener
}
}
@Override
public void itemStateChanged(ItemEvent e) {
fire(e);
}
@Override
public void componentAdded(ContainerEvent e) {
// if (extListener != null && extListener.accept(e.getChild())) {
// extListener.startListeningTo(e.getChild(), extNotifier);
@@ -337,6 +334,7 @@ final class GenericListener
attachTo(e.getChild());
}
@Override
public void componentRemoved(ContainerEvent e) {
if (extListener != null && extListener.accept(e.getChild())) {
extListener.stopListeningTo(e.getChild());
@@ -345,30 +343,37 @@ final class GenericListener
detachFrom(e.getChild());
}
@Override
public void insertUpdate(DocumentEvent e) {
fire(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
fire(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
fire(e);
}
@Override
public void stateChanged(ChangeEvent e) {
fire(e);
}
@Override
public void valueChanged(ListSelectionEvent e) {
fire(e);
}
@Override
public void valueChanged(TreeSelectionEvent e) {
fire(e);
}
@Override
public void tableChanged(TableModelEvent e) {
fire(e);
}

View File

@@ -32,7 +32,7 @@ import javax.swing.JComponent;
*/
final class SimpleWizard extends AbstractWizard {
private final Map ids2panels = new HashMap();
private final Map ids2panels = new HashMap<>();
final SimpleWizardInfo info;

View File

@@ -23,13 +23,13 @@ import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.jackhuang.hellominecraft.util.ArrayUtils;
import org.jackhuang.hellominecraft.util.code.Charsets;
import org.jackhuang.hellominecraft.util.system.IOUtils;
@@ -62,7 +62,7 @@ public final class SimpleWizardInfo implements WizardControllerImplementation {
protected SimpleWizardInfo(String title, String[] steps, String[] descriptions, WizardPanelProvider provider) {
this.steps = Objects.requireNonNull(steps, "Null steps");
this.descriptions = Objects.requireNonNull(descriptions, "Null descriptions");
if (new HashSet(Arrays.asList(steps)).size() < steps.length)
if (ArrayUtils.hasDuplicateElements(steps))
throw new IllegalArgumentException("Duplicate ID: " + Arrays.asList(steps));
if (descriptions.length != steps.length)
if (steps.length != descriptions.length + 1 && !WizardImplementation.UNDETERMINED_STEP.equals(steps[steps.length - 1]))
@@ -76,17 +76,13 @@ public final class SimpleWizardInfo implements WizardControllerImplementation {
}
final void setWizard(SimpleWizard wizard) {
this.wizard = new WeakReference(wizard);
this.wizard = new WeakReference<>(wizard);
}
final SimpleWizard getWizard() {
return wizard != null ? (SimpleWizard) wizard.get() : null;
}
final SimpleWizard createWizard() {
return new SimpleWizard(this);
}
//pkg private for unit tests
final WizardController controller = new WizardController(this);

View File

@@ -89,7 +89,7 @@ public class Summary {
if (ArrayUtils.isEmpty(items))
throw new IllegalArgumentException("Items array empty");
this.result = result;
JList list = new JList(items);
JList<String> list = new JList<>(items);
comp = new JScrollPane(list);
}

View File

@@ -28,7 +28,7 @@ final class Util {
static String[] getSteps(WizardPage[] pages) {
String[] result = new String[pages.length];
Set uniqueNames = new HashSet(pages.length);
Set<String> uniqueNames = new HashSet<>(pages.length);
for (int i = 0; i < pages.length; i++) {
result[i] = pages[i].id();
if (result[i] == null || uniqueNames.contains(result[i])) {
@@ -41,7 +41,7 @@ final class Util {
return result;
}
static String uniquify(String s, Set /* <String> */ used) {
static String uniquify(String s, Set<String> used) {
String test = s;
if (test != null) {
int ix = 0;
@@ -66,11 +66,11 @@ final class Util {
return result;
}
static String getIDFromStaticMethod(Class clazz) {
static String getIDFromStaticMethod(Class<?> clazz) {
// System.err.println("GetID by method for " + clazz);
String result = null;
try {
Method m = clazz.getDeclaredMethod("getStep", new Class[]{});
Method m = clazz.getDeclaredMethod("getStep", new Class<?>[]{});
// assert m.getReturnType() == String.class;
result = Objects.requireNonNull((String) m.invoke(clazz, (Object[]) null), "getStep may not return null");
} catch (Exception ex) {
@@ -83,12 +83,12 @@ final class Util {
* Get an array of steps by looking for a static method getID() on each
* class object passed
*/
static String[] getSteps(Class[] pages) {
static String[] getSteps(Class<?>[] pages) {
Objects.requireNonNull(pages, "Null array of classes");
String[] result = new String[pages.length];
Set used = new HashSet(pages.length);
Set<String> used = new HashSet<>(pages.length);
for (int i = 0; i < pages.length; i++) {
Objects.requireNonNull(pages[i], "Null at " + i + " in array of panel classes");
@@ -116,7 +116,7 @@ final class Util {
* Get an array of descriptions by looking for the static method
* getDescription() on each passed class object
*/
static String[] getDescriptions(Class[] pages) {
static String[] getDescriptions(Class<?>[] pages) {
String[] result = new String[pages.length];
for (int i = 0; i < pages.length; i++)
@@ -125,7 +125,7 @@ final class Util {
return result;
}
static String getDescriptionFromStaticMethod(Class clazz) {
static String getDescriptionFromStaticMethod(Class<?> clazz) {
Method m;
try {
m = clazz.getDeclaredMethod("getDescription", (Class[]) null);

View File

@@ -10,15 +10,12 @@ enclosed by brackets [] replaced by your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]" */
package org.jackhuang.hellominecraft.util.ui.wizard.spi;
import java.awt.Rectangle;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.swing.Action;
import javax.swing.JComponent;
import org.jackhuang.hellominecraft.util.ui.wizard.api.WizardDisplayer;
/**
* Encapsulates the logic and state of a Wizard. A Wizard gathers information
@@ -284,8 +281,8 @@ public final class Wizard {
}
private volatile boolean listeningToImpl = false;
private final List listeners = Collections.synchronizedList(
new LinkedList());
private final List<WizardObserver> listeners = Collections.synchronizedList(
new LinkedList<>());
private WizardObserver l = null;
@@ -360,31 +357,4 @@ public final class Wizard {
return false;
}
/**
* Delegates to WizardDisplayer.showWizard()
*/
public void show() {
WizardDisplayer.showWizard(this);
}
/**
* Delegates to WizardDisplayer.showWizard()
*/
public Object show(Wizard wizard, Action help) {
return WizardDisplayer.showWizard(wizard, help);
}
/**
* Delegates to WizardDisplayer.showWizard()
*/
public Object show(Wizard wizard, Rectangle r) {
return WizardDisplayer.showWizard(wizard, r);
}
/**
* Delegates to WizardDisplayer.showWizard()
*/
public Object show(Wizard wizard, Rectangle r, Action help) {
return WizardDisplayer.showWizard(wizard, r, help, null);
}
}

View File

@@ -23,9 +23,10 @@ import java.awt.Color;
import java.awt.Component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.jackhuang.hellominecraft.util.ArrayUtils;
/**
* A convenience JPanel subclass that makes it easy to create wizard panels.
@@ -191,7 +192,7 @@ public class WizardPage extends JPanel implements WizardPanel {
/**
* Use this constructor or the default constructor if you intend to pass an
* array of Class objects to lazily create WizardPanels.
* array of Class<?> objects to lazily create WizardPanels.
*/
protected WizardPage(boolean autoListen) {
this(null, null, autoListen);
@@ -428,7 +429,7 @@ public class WizardPage extends JPanel implements WizardPanel {
* Create simple Wizard from an array of classes, each of which is a unique
* subclass of WizardPage.
*/
public static Wizard createWizard(Class[] wizardPageClasses, WizardResultProducer finisher) {
public static Wizard createWizard(Class<?>[] wizardPageClasses, WizardResultProducer finisher) {
return new CWPP(wizardPageClasses, finisher).createWizard();
}
@@ -436,7 +437,7 @@ public class WizardPage extends JPanel implements WizardPanel {
* Create simple Wizard from an array of classes, each of which is a unique
* subclass of WizardPage.
*/
public static Wizard createWizard(String title, Class[] wizardPageClasses, WizardResultProducer finisher) {
public static Wizard createWizard(String title, Class<?>[] wizardPageClasses, WizardResultProducer finisher) {
return new CWPP(title, wizardPageClasses, finisher).createWizard();
}
@@ -444,7 +445,7 @@ public class WizardPage extends JPanel implements WizardPanel {
* Create simple Wizard from an array of classes, each of which is a unique
* subclass of WizardPage.
*/
public static Wizard createWizard(String title, Class[] wizardPageClasses) {
public static Wizard createWizard(String title, Class<?>[] wizardPageClasses) {
return new CWPP(title, wizardPageClasses,
WizardResultProducer.NO_OP).createWizard();
}
@@ -453,7 +454,7 @@ public class WizardPage extends JPanel implements WizardPanel {
* Create a simple Wizard from an array of classes, each of which is a
* unique subclass of WizardPage, with a no-op WizardResultProducer.
*/
public static Wizard createWizard(Class[] wizardPageClasses) {
public static Wizard createWizard(Class<?>[] wizardPageClasses) {
return createWizard(wizardPageClasses, WizardResultProducer.NO_OP);
}
@@ -469,14 +470,13 @@ public class WizardPage extends JPanel implements WizardPanel {
*/
void setWizardDataMap(Map m) {
if (m == null)
wizardData = new HashMap();
wizardData = new HashMap<>();
else {
if (wizardData instanceof HashMap)
// our initial map has keys for all of our components
// but with dummy empty values
// So make sure we don't override data that was put in as part of the initialProperties
for (Iterator iter = wizardData.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
for (Map.Entry entry : (Set<Map.Entry>) wizardData.entrySet()) {
Object key = entry.getKey();
if (!m.containsKey(key))
m.put(key, entry.getValue());
@@ -660,7 +660,7 @@ public class WizardPage extends JPanel implements WizardPanel {
} else if (comp instanceof JFormattedTextField)
return ((JFormattedTextField) comp).getValue();
else if (comp instanceof JList) {
Object[] o = ((JList) comp).getSelectedValues();
Object[] o = ((JList<?>) comp).getSelectedValues();
if (o.length > 1)
return o;
else if (o.length == 1)
@@ -668,7 +668,7 @@ public class WizardPage extends JPanel implements WizardPanel {
} else if (comp instanceof JTextComponent)
return ((JTextComponent) comp).getText();
else if (comp instanceof JComboBox)
return ((JComboBox) comp).getSelectedItem();
return ((JComboBox<?>) comp).getSelectedItem();
else if (comp instanceof JColorChooser)
return ((JColorChooser) comp).getSelectionModel().getSelectedColor();
else if (comp instanceof JSpinner)
@@ -702,7 +702,7 @@ public class WizardPage extends JPanel implements WizardPanel {
else if (comp instanceof JList) {
if (value instanceof Object[])
throw new IllegalArgumentException("can't handle multi-select lists");
((JList) comp).setSelectedValue(value, true);
((JList<?>) comp).setSelectedValue(value, true);
} else if (comp instanceof JTextComponent)
((JTextComponent) comp).setText((String) value);
else if (comp instanceof JComboBox)
@@ -898,7 +898,7 @@ public class WizardPage extends JPanel implements WizardPanel {
* Make sure we haven't been passed bogus data
*/
private String valid(WizardPage[] pages) {
if (new HashSet(Arrays.asList(pages)).size() != pages.length)
if (ArrayUtils.hasDuplicateElements(pages))
return "Duplicate entry in array: "
+ Arrays.asList(pages);
@@ -934,44 +934,27 @@ public class WizardPage extends JPanel implements WizardPanel {
*/
private static final class CWPP extends WizardPanelProvider {
private final Class[] classes;
private final Class<?>[] classes;
private final WizardResultProducer finish;
private final String[] longDescriptions;
CWPP(String title, Class[] classes, WizardResultProducer finish) {
CWPP(String title, Class<?>[] classes, WizardResultProducer finish) {
super(title, Util.getSteps(classes), Util.getDescriptions(classes));
// assert classes != null : "Class array may not be null";
// assert new HashSet(Arrays.asList(classes)).size() == classes.length :
// "Duplicate entries in class array";
// assert finish != null : "WizardResultProducer may not be null";
_validateArgs(classes, finish);
this.finish = finish;
this.classes = classes;
longDescriptions = new String[classes.length];
}
private void _validateArgs(Class[] classes, WizardResultProducer finish) {
// assert classes != null : "Class array may not be null";
// assert new HashSet(Arrays.asList(classes)).size() == classes.length :
// "Duplicate entries in class array";
// assert finish != null : "WizardResultProducer may not be null";
if (classes == null)
throw new RuntimeException("Class array may not be null");
if (new HashSet(Arrays.asList(classes)).size() != classes.length)
private void _validateArgs(Class<?>[] classes, WizardResultProducer finish) {
Objects.requireNonNull(classes, "Class<?> array may not be null");
Objects.requireNonNull(finish, "WizardResultProducer may not be null");
if (ArrayUtils.hasDuplicateElements(classes))
throw new RuntimeException("Duplicate entries in class array");
if (finish == null)
throw new RuntimeException("WizardResultProducer may not be null");
}
CWPP(Class[] classes, WizardResultProducer finish) {
CWPP(Class<?>[] classes, WizardResultProducer finish) {
super(Util.getSteps(classes), Util.getDescriptions(classes));
// assert classes != null : "Class array may not be null";
// assert new HashSet(Arrays.asList(classes)).size() == classes.length :
// "Duplicate entries in class array";
// assert finish != null : "WizardResultProducer may not be null";
longDescriptions = new String[classes.length];
_validateArgs(classes, finish);

View File

@@ -16,10 +16,10 @@ enclosed by brackets [] replaced by your own identifying information:
package org.jackhuang.hellominecraft.util.ui.wizard.spi;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import javax.swing.JComponent;
import org.jackhuang.hellominecraft.util.ArrayUtils;
/**
* (Note: <code>WizardPage</code> offers somewhat simpler functionality for
@@ -142,7 +142,7 @@ public abstract class WizardPanelProvider {
Objects.requireNonNull(steps[i], "Step id " + i + " is null");
Objects.requireNonNull(descriptions[i], "Description " + i + " is null");
}
if (new HashSet(Arrays.asList(steps)).size() != steps.length)
if (ArrayUtils.hasDuplicateElements(steps))
return "Duplicate step ids: " + Arrays.asList(steps);
return null;
}