This commit is contained in:
huanghongxun
2015-11-17 12:51:04 +08:00
parent 39b6d68006
commit 159a992081
243 changed files with 2990 additions and 2836 deletions

View File

@@ -21,7 +21,7 @@ if (!hasProperty('mainClass')) {
}
if (System.getenv("BUILD_NUMBER") != null)
version = System.getenv("BUILD_NUMBER")
version = System.getenv("BUILD_NUMBER")
buildscript {
repositories {

View File

@@ -30,12 +30,12 @@ public final class C {
public static final Gson gson = new Gson();
public static final ResourceBundle I18N;
static {
ResourceBundle rb = null;
try {
rb = ResourceBundle.getBundle("org/jackhuang/hellominecraft/launcher/I18N");
} catch(Throwable t) {
} catch (Throwable t) {
rb = null;
System.out.println("Did you delete I18N.properties?");
t.printStackTrace();

View File

@@ -26,45 +26,42 @@ public class AppenderControl {
private final int intLevel;
public AppenderControl(IAppender appender, Level level) {
this.appender = appender;
this.level = level;
this.intLevel = (level == null ? Level.ALL.level : level.level);
this.appender = appender;
this.level = level;
this.intLevel = (level == null ? Level.ALL.level : level.level);
}
public IAppender getAppender() {
return this.appender;
return this.appender;
}
public void callAppender(LogEvent event) {
if ((this.level != null)
&& (this.intLevel < event.level.level)) {
return;
}
if ((this.level != null)
&& (this.intLevel < event.level.level))
return;
if (this.recursive.get() != null) {
System.err.println("Recursive call to appender " + this.appender.getName());
return;
}
try {
this.recursive.set(this);
if (this.recursive.get() != null) {
System.err.println("Recursive call to appender " + this.appender.getName());
return;
}
try {
this.recursive.set(this);
try {
this.appender.append(event);
} catch (RuntimeException ex) {
System.err.println("An exception occurred processing Appender " + this.appender.getName());
ex.printStackTrace();
if (!this.appender.ignoreExceptions()) {
throw ex;
}
} catch (Exception ex) {
System.err.println("An exception occurred processing Appender " + this.appender.getName());
ex.printStackTrace();
if (!this.appender.ignoreExceptions()) {
throw new LoggingException(ex);
}
}
} finally {
this.recursive.set(null);
}
try {
this.appender.append(event);
} catch (RuntimeException ex) {
System.err.println("An exception occurred processing Appender " + this.appender.getName());
ex.printStackTrace();
if (!this.appender.ignoreExceptions())
throw ex;
} catch (Exception ex) {
System.err.println("An exception occurred processing Appender " + this.appender.getName());
ex.printStackTrace();
if (!this.appender.ignoreExceptions())
throw new LoggingException(ex);
}
} finally {
this.recursive.set(null);
}
}
}

View File

@@ -25,16 +25,15 @@ import org.jackhuang.hellominecraft.logging.layout.DefaultLayout;
*
* @author huangyuhui
*/
public class Configuration {
public ArrayList<IAppender> appenders = new ArrayList<IAppender>();
public static Configuration DEFAULT;
static {
DEFAULT = new Configuration();
DEFAULT.appenders.add(new ConsoleAppender("Console", new DefaultLayout(), true, new ConsoleAppender.SystemOutStream(), true));
DEFAULT = new Configuration();
DEFAULT.appenders.add(new ConsoleAppender("Console", new DefaultLayout(), true, new ConsoleAppender.SystemOutStream(), true));
}
}

View File

@@ -73,7 +73,7 @@ public enum Level {
level = DEBUG;
} else {
if (line.contains("[INFO]") || line.contains("[CONFIG]") || line.contains("[FINE]")
|| line.contains("[FINER]") || line.contains("[FINEST]"))
|| line.contains("[FINER]") || line.contains("[FINEST]"))
level = INFO;
if (line.contains("[SEVERE]") || line.contains("[STDERR]"))
level = ERROR;
@@ -84,12 +84,12 @@ public enum Level {
}
if (line.contains("overwriting existing"))
return FATAL;
if (line.contains("Exception in thread")
|| line.matches("\\s+at " + JAVA_SYMBOL)
|| line.matches("Caused by: " + JAVA_SYMBOL)
|| line.matches("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$]?[a-zA-Z\\d_$]*(Exception|Error|Throwable)")
|| line.matches("... \\d+ more$"))
|| line.matches("\\s+at " + JAVA_SYMBOL)
|| line.matches("Caused by: " + JAVA_SYMBOL)
|| line.matches("([a-zA-Z_$][a-zA-Z\\d_$]*\\.)+[a-zA-Z_$]?[a-zA-Z\\d_$]*(Exception|Error|Throwable)")
|| line.matches("... \\d+ more$"))
return ERROR;
return level;
}

View File

@@ -23,10 +23,10 @@ import org.jackhuang.hellominecraft.logging.message.IMessage;
* @author huangyuhui
*/
public class LogEvent {
public Level level;
public String threadName;
public Throwable thrown;
public IMessage message;
}

View File

@@ -23,7 +23,7 @@ package org.jackhuang.hellominecraft.logging;
public class LoggingException extends RuntimeException {
public LoggingException(Exception e) {
super(e);
super(e);
}
}

View File

@@ -30,27 +30,27 @@ public abstract class AbstractAppender implements IAppender {
private final boolean ignoreExceptions;
public AbstractAppender(String name, ILayout<? extends Serializable> layout) {
this(name, layout, true);
this(name, layout, true);
}
public AbstractAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions) {
this.name = name;
this.layout = layout;
this.ignoreExceptions = ignoreExceptions;
this.name = name;
this.layout = layout;
this.ignoreExceptions = ignoreExceptions;
}
@Override
public String getName() {
return name;
return name;
}
@Override
public boolean ignoreExceptions() {
return ignoreExceptions;
return ignoreExceptions;
}
@Override
public ILayout<? extends Serializable> getLayout() {
return this.layout;
return this.layout;
}
}

View File

@@ -28,62 +28,62 @@ import org.jackhuang.hellominecraft.logging.layout.ILayout;
public class ConsoleAppender extends OutputStreamAppender {
public ConsoleAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions, OutputStream stream, boolean immediateFlush) {
super(name, layout, ignoreExceptions, stream, true);
super(name, layout, ignoreExceptions, stream, true);
}
public static class SystemOutStream extends OutputStream {
@Override
public void close() {
}
@Override
public void close() {
}
@Override
public void flush() {
System.out.flush();
}
@Override
public void flush() {
System.out.flush();
}
@Override
public void write(byte[] b) throws IOException {
System.out.write(b);
}
@Override
public void write(byte[] b) throws IOException {
System.out.write(b);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.out.write(b, off, len);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.out.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
System.out.write(b);
}
@Override
public void write(int b) throws IOException {
System.out.write(b);
}
}
public static class SystemErrStream extends OutputStream {
@Override
public void close() {
}
@Override
public void close() {
}
@Override
public void flush() {
System.err.flush();
}
@Override
public void flush() {
System.err.flush();
}
@Override
public void write(byte[] b) throws IOException {
System.err.write(b);
}
@Override
public void write(byte[] b) throws IOException {
System.err.write(b);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.err.write(b, off, len);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.err.write(b, off, len);
}
@Override
public void write(int b) {
System.err.write(b);
}
@Override
public void write(int b) {
System.err.write(b);
}
}
}

View File

@@ -25,10 +25,13 @@ import org.jackhuang.hellominecraft.logging.layout.ILayout;
* @author huangyuhui
*/
public interface IAppender {
void append(LogEvent event);
String getName();
boolean ignoreExceptions();
ILayout<? extends Serializable> getLayout();
}

View File

@@ -37,27 +37,26 @@ public abstract class OutputStreamAppender extends AbstractAppender {
private final Lock readLock = new ReentrantReadWriteLock().readLock();
public OutputStreamAppender(String name, ILayout<? extends Serializable> layout, boolean ignoreExceptions, OutputStream stream, boolean immediateFlush) {
super(name, layout, ignoreExceptions);
super(name, layout, ignoreExceptions);
this.immediateFlush = immediateFlush;
this.stream = stream;
this.immediateFlush = immediateFlush;
this.stream = stream;
}
@Override
public void append(LogEvent event) {
this.readLock.lock();
try {
byte[] bytes = getLayout().toByteArray(event);
if (bytes.length > 0) {
stream.write(bytes);
}
if(event.thrown != null)
event.thrown.printStackTrace(new PrintStream(stream));
} catch (IOException ex) {
System.err.println("Unable to write to stream for appender: " + getName());
throw new LoggingException(ex);
} finally {
this.readLock.unlock();
}
this.readLock.lock();
try {
byte[] bytes = getLayout().toByteArray(event);
if (bytes.length > 0)
stream.write(bytes);
if (event.thrown != null)
event.thrown.printStackTrace(new PrintStream(stream));
} catch (IOException ex) {
System.err.println("Unable to write to stream for appender: " + getName());
throw new LoggingException(ex);
} finally {
this.readLock.unlock();
}
}
}

View File

@@ -26,7 +26,7 @@ public abstract class AbstractStringLayout implements ILayout<String> {
@Override
public byte[] toByteArray(LogEvent event) {
return toSerializable(event).getBytes();
return toSerializable(event).getBytes();
}
}

View File

@@ -25,11 +25,12 @@ import org.jackhuang.hellominecraft.logging.LogEvent;
* @author huangyuhui
*/
public class DefaultLayout extends AbstractStringLayout {
private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
@Override
public String toSerializable(LogEvent event) {
return "[" + sdf.format(new Date()) + "] [" + event.threadName + "/" + event.level.name() + "] " + event.message.getFormattedMessage() + "\n";
return "[" + sdf.format(new Date()) + "] [" + event.threadName + "/" + event.level.name() + "] " + event.message.getFormattedMessage() + "\n";
}
}

View File

@@ -25,8 +25,9 @@ import org.jackhuang.hellominecraft.logging.LogEvent;
* @param <T>
*/
public interface ILayout<T extends Serializable> {
byte[] toByteArray(LogEvent event);
T toSerializable(LogEvent event);
}

View File

@@ -23,7 +23,7 @@ import org.jackhuang.hellominecraft.logging.message.ParameterizedMessageFactory;
import org.jackhuang.hellominecraft.logging.message.StringFormattedMessage;
public abstract class AbstractLogger
implements ILogger {
implements ILogger {
public static final Class<? extends IMessageFactory> DEFAULT_MESSAGE_FACTORY_CLASS = ParameterizedMessageFactory.class;
@@ -34,278 +34,249 @@ public abstract class AbstractLogger
private final IMessageFactory messageFactory;
public AbstractLogger() {
this.name = getClass().getName();
this.messageFactory = createDefaultMessageFactory();
this.name = getClass().getName();
this.messageFactory = createDefaultMessageFactory();
}
public AbstractLogger(String name) {
this.name = name;
this.messageFactory = createDefaultMessageFactory();
this.name = name;
this.messageFactory = createDefaultMessageFactory();
}
public AbstractLogger(String name, IMessageFactory messageFactory) {
this.name = name;
this.messageFactory = (messageFactory == null ? createDefaultMessageFactory() : messageFactory);
this.name = name;
this.messageFactory = (messageFactory == null ? createDefaultMessageFactory() : messageFactory);
}
private IMessageFactory createDefaultMessageFactory() {
try {
return (IMessageFactory) DEFAULT_MESSAGE_FACTORY_CLASS.newInstance();
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
try {
return (IMessageFactory) DEFAULT_MESSAGE_FACTORY_CLASS.newInstance();
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
@Override
public void catching(Level level, Throwable t) {
if (isEnabled(level, (Object) null, null)) {
log(level, this.messageFactory.newMessage(CATCHING), t);
}
if (isEnabled(level, (Object) null, null))
log(level, this.messageFactory.newMessage(CATCHING), t);
}
@Override
public void catching(Throwable t) {
catching(Level.ERROR, t);
catching(Level.ERROR, t);
}
@Override
public void debug(IMessage msg) {
if (isEnabled(Level.DEBUG, msg, null)) {
log(Level.DEBUG, msg, null);
}
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);
}
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);
}
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);
}
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);
}
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());
}
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);
}
if (isEnabled(Level.DEBUG, message, t))
log(Level.DEBUG, this.messageFactory.newMessage(message), t);
}
@Override
public void entry() {
entry(new Object[0]);
entry(new Object[0]);
}
@Override
public void entry(Object[] params) {
if (isEnabled(Level.TRACE, (Object) null, null)) {
log(Level.TRACE, entryMsg(params.length, params), null);
}
if (isEnabled(Level.TRACE, (Object) null, null))
log(Level.TRACE, entryMsg(params.length, params), null);
}
private IMessage entryMsg(int count, Object[] params) {
if (count == 0) {
return this.messageFactory.newMessage("entry");
}
StringBuilder sb = new StringBuilder("entry params(");
int i = 0;
for (Object parm : params) {
if (parm != null) {
sb.append(parm.toString());
} else {
sb.append("null");
}
i++;
if (i < params.length) {
sb.append(", ");
}
}
sb.append(")");
return this.messageFactory.newMessage(sb.toString());
if (count == 0)
return this.messageFactory.newMessage("entry");
StringBuilder sb = new StringBuilder("entry params(");
int i = 0;
for (Object parm : params) {
if (parm != null)
sb.append(parm.toString());
else
sb.append("null");
i++;
if (i < params.length)
sb.append(", ");
}
sb.append(")");
return this.messageFactory.newMessage(sb.toString());
}
@Override
public void error(IMessage msg) {
if (isEnabled(Level.ERROR, msg, null)) {
log(Level.ERROR, msg, null);
}
if (isEnabled(Level.ERROR, msg, null))
log(Level.ERROR, msg, null);
}
@Override
public void error(IMessage msg, Throwable t) {
if (isEnabled(Level.ERROR, msg, t)) {
log(Level.ERROR, msg, t);
}
if (isEnabled(Level.ERROR, msg, t))
log(Level.ERROR, msg, t);
}
@Override
public void error(Object message) {
if (isEnabled(Level.ERROR, message, null)) {
log(Level.ERROR, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.ERROR, message, null))
log(Level.ERROR, this.messageFactory.newMessage(message), null);
}
@Override
public void error(Object message, Throwable t) {
if (isEnabled(Level.ERROR, message, t)) {
log(Level.ERROR, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.ERROR, message, t))
log(Level.ERROR, this.messageFactory.newMessage(message), t);
}
@Override
public void error(String message) {
if (isEnabled(Level.ERROR, message)) {
log(Level.ERROR, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.ERROR, message))
log(Level.ERROR, this.messageFactory.newMessage(message), null);
}
@Override
public void error(String message, Object[] params) {
if (isEnabled(Level.ERROR, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.ERROR, msg, msg.getThrowable());
}
if (isEnabled(Level.ERROR, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.ERROR, msg, msg.getThrowable());
}
}
@Override
public void error(String message, Throwable t) {
if (isEnabled(Level.ERROR, message, t)) {
log(Level.ERROR, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.ERROR, message, t))
log(Level.ERROR, this.messageFactory.newMessage(message), t);
}
@Override
public void fatal(IMessage msg) {
if (isEnabled(Level.FATAL, msg, null)) {
log(Level.FATAL, msg, null);
}
if (isEnabled(Level.FATAL, msg, null))
log(Level.FATAL, msg, null);
}
@Override
public void fatal(IMessage msg, Throwable t) {
if (isEnabled(Level.FATAL, msg, t)) {
log(Level.FATAL, msg, t);
}
if (isEnabled(Level.FATAL, msg, t))
log(Level.FATAL, msg, t);
}
@Override
public void fatal(Object message) {
if (isEnabled(Level.FATAL, message, null)) {
log(Level.FATAL, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.FATAL, message, null))
log(Level.FATAL, this.messageFactory.newMessage(message), null);
}
@Override
public void fatal(Object message, Throwable t) {
if (isEnabled(Level.FATAL, message, t)) {
log(Level.FATAL, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.FATAL, message, t))
log(Level.FATAL, this.messageFactory.newMessage(message), t);
}
@Override
public void fatal(String message) {
if (isEnabled(Level.FATAL, message)) {
log(Level.FATAL, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.FATAL, message))
log(Level.FATAL, this.messageFactory.newMessage(message), null);
}
@Override
public void fatal(String message, Object[] params) {
if (isEnabled(Level.FATAL, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.FATAL, msg, msg.getThrowable());
}
if (isEnabled(Level.FATAL, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.FATAL, msg, msg.getThrowable());
}
}
@Override
public void fatal(String message, Throwable t) {
if (isEnabled(Level.FATAL, message, t)) {
log(Level.FATAL, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.FATAL, message, t))
log(Level.FATAL, this.messageFactory.newMessage(message), t);
}
@Override
public String getName() {
return this.name;
return this.name;
}
@Override
public void info(IMessage msg) {
if (isEnabled(Level.INFO, msg, null)) {
log(Level.INFO, msg, null);
}
if (isEnabled(Level.INFO, msg, null))
log(Level.INFO, msg, null);
}
@Override
public void info(IMessage msg, Throwable t) {
if (isEnabled(Level.INFO, msg, t)) {
log(Level.INFO, msg, t);
}
if (isEnabled(Level.INFO, msg, t))
log(Level.INFO, msg, t);
}
@Override
public void info(Object message) {
if (isEnabled(Level.INFO, message, null)) {
log(Level.INFO, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.INFO, message, null))
log(Level.INFO, this.messageFactory.newMessage(message), null);
}
@Override
public void info(Object message, Throwable t) {
if (isEnabled(Level.INFO, message, t)) {
log(Level.INFO, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.INFO, message, t))
log(Level.INFO, this.messageFactory.newMessage(message), t);
}
@Override
public void info(String message) {
if (isEnabled(Level.INFO, message)) {
log(Level.INFO, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.INFO, message))
log(Level.INFO, this.messageFactory.newMessage(message), null);
}
@Override
public void info(String message, Object[] params) {
if (isEnabled(Level.INFO, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.INFO, msg, msg.getThrowable());
}
if (isEnabled(Level.INFO, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.INFO, msg, msg.getThrowable());
}
}
@Override
public void info(String message, Throwable t) {
if (isEnabled(Level.INFO, message, t)) {
log(Level.INFO, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.INFO, message, t))
log(Level.INFO, this.messageFactory.newMessage(message), t);
}
protected abstract boolean isEnabled(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable);
@@ -322,213 +293,194 @@ public abstract class AbstractLogger
@Override
public boolean isErrorEnabled() {
return isEnabled(Level.ERROR);
return isEnabled(Level.ERROR);
}
@Override
public boolean isFatalEnabled() {
return isEnabled(Level.FATAL);
return isEnabled(Level.FATAL);
}
@Override
public boolean isInfoEnabled() {
return isEnabled(Level.INFO);
return isEnabled(Level.INFO);
}
@Override
public boolean isTraceEnabled() {
return isEnabled(Level.TRACE);
return isEnabled(Level.TRACE);
}
@Override
public boolean isWarnEnabled() {
return isEnabled(Level.WARN);
return isEnabled(Level.WARN);
}
@Override
public boolean isDebugEnabled() {
return isEnabled(Level.DEBUG);
return isEnabled(Level.DEBUG);
}
@Override
public boolean isEnabled(Level level) {
return isEnabled(level, (Object) null, null);
return isEnabled(level, (Object) null, null);
}
@Override
public void log(Level level, IMessage msg) {
if (isEnabled(level, msg, null)) {
log(level, msg, null);
}
if (isEnabled(level, msg, null))
log(level, msg, null);
}
@Override
public void log(Level level, IMessage msg, Throwable t) {
if (isEnabled(level, msg, t)) {
abstractLog(level, msg, t);
}
if (isEnabled(level, msg, t))
abstractLog(level, msg, t);
}
@Override
public void log(Level level, Object message) {
if (isEnabled(level, message, null)) {
log(level, this.messageFactory.newMessage(message), null);
}
if (isEnabled(level, message, null))
log(level, this.messageFactory.newMessage(message), null);
}
@Override
public void log(Level level, Object message, Throwable t) {
if (isEnabled(level, message, t)) {
log(level, this.messageFactory.newMessage(message), t);
}
if (isEnabled(level, message, t))
log(level, this.messageFactory.newMessage(message), t);
}
@Override
public void log(Level level, String message) {
if (isEnabled(level, message)) {
log(level, this.messageFactory.newMessage(message), null);
}
if (isEnabled(level, message))
log(level, this.messageFactory.newMessage(message), null);
}
@Override
public void log(Level level, String message, Object[] params) {
if (isEnabled(level, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(level, msg, msg.getThrowable());
}
if (isEnabled(level, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(level, msg, msg.getThrowable());
}
}
@Override
public void log(Level level, String message, Throwable t) {
if (isEnabled(level, message, t)) {
log(level, this.messageFactory.newMessage(message), t);
}
if (isEnabled(level, message, t))
log(level, this.messageFactory.newMessage(message), t);
}
@Override
public void printf(Level level, String format, Object[] params) {
if (isEnabled(level, format, params)) {
IMessage msg = new StringFormattedMessage(format, params);
log(level, msg, msg.getThrowable());
}
if (isEnabled(level, format, params)) {
IMessage msg = new StringFormattedMessage(format, params);
log(level, msg, msg.getThrowable());
}
}
@Override
public <T extends Throwable> T throwing(T t) {
return throwing(Level.ERROR, t);
return throwing(Level.ERROR, t);
}
@Override
public <T extends Throwable> T throwing(Level level, T t) {
if (isEnabled(level, (Object) null, null)) {
log(level, this.messageFactory.newMessage(THROWING), t);
}
return t;
if (isEnabled(level, (Object) null, null))
log(level, this.messageFactory.newMessage(THROWING), t);
return t;
}
@Override
public String toString() {
return this.name;
return this.name;
}
@Override
public void trace(IMessage msg) {
if (isEnabled(Level.TRACE, msg, null)) {
log(Level.TRACE, msg, null);
}
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);
}
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);
}
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);
}
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);
}
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());
}
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);
}
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)) {
log(Level.WARN, msg, null);
}
if (isEnabled(Level.WARN, msg, null))
log(Level.WARN, msg, null);
}
@Override
public void warn(IMessage msg, Throwable t) {
if (isEnabled(Level.WARN, msg, t)) {
log(Level.WARN, msg, t);
}
if (isEnabled(Level.WARN, msg, t))
log(Level.WARN, msg, t);
}
@Override
public void warn(Object message) {
if (isEnabled(Level.WARN, message, null)) {
log(Level.WARN, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.WARN, message, null))
log(Level.WARN, this.messageFactory.newMessage(message), null);
}
@Override
public void warn(Object message, Throwable t) {
if (isEnabled(Level.WARN, message, t)) {
log(Level.WARN, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.WARN, message, t))
log(Level.WARN, this.messageFactory.newMessage(message), t);
}
@Override
public void warn(String message) {
if (isEnabled(Level.WARN, message)) {
log(Level.WARN, this.messageFactory.newMessage(message), null);
}
if (isEnabled(Level.WARN, message))
log(Level.WARN, this.messageFactory.newMessage(message), null);
}
@Override
public void warn(String message, Object[] params) {
if (isEnabled(Level.WARN, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.WARN, msg, msg.getThrowable());
}
if (isEnabled(Level.WARN, message, params)) {
IMessage msg = this.messageFactory.newMessage(message, params);
log(Level.WARN, msg, msg.getThrowable());
}
}
@Override
public void warn(String message, Throwable t) {
if (isEnabled(Level.WARN, message, t)) {
log(Level.WARN, this.messageFactory.newMessage(message), t);
}
if (isEnabled(Level.WARN, message, t))
log(Level.WARN, this.messageFactory.newMessage(message), t);
}
}

View File

@@ -24,133 +24,133 @@ import org.jackhuang.hellominecraft.logging.message.IMessage;
* @author huangyuhui
*/
public interface ILogger {
void catching(Level paramLevel, Throwable paramThrowable);
void catching(Throwable paramThrowable);
void catching(Level paramLevel, Throwable paramThrowable);
void debug(IMessage paramIMessage);
void catching(Throwable paramThrowable);
void debug(IMessage paramIMessage, Throwable paramThrowable);
void debug(IMessage paramIMessage);
void debug(Object paramObject);
void debug(IMessage paramIMessage, Throwable paramThrowable);
void debug(Object paramObject, Throwable paramThrowable);
void debug(Object paramObject);
void debug(String paramString);
void debug(Object paramObject, Throwable paramThrowable);
void debug(String paramString, Object[] paramArrayOfObject);
void debug(String paramString);
void debug(String paramString, Throwable paramThrowable);
void debug(String paramString, Object[] paramArrayOfObject);
void entry();
void debug(String paramString, Throwable paramThrowable);
void entry(Object[] paramArrayOfObject);
void entry();
void error(IMessage paramIMessage);
void entry(Object[] paramArrayOfObject);
void error(IMessage paramIMessage, Throwable paramThrowable);
void error(IMessage paramIMessage);
void error(Object paramObject);
void error(IMessage paramIMessage, Throwable paramThrowable);
void error(Object paramObject, Throwable paramThrowable);
void error(Object paramObject);
void error(String paramString);
void error(Object paramObject, Throwable paramThrowable);
void error(String paramString, Object[] paramArrayOfObject);
void error(String paramString);
void error(String paramString, Throwable paramThrowable);
void error(String paramString, Object[] paramArrayOfObject);
void fatal(IMessage paramIMessage);
void error(String paramString, Throwable paramThrowable);
void fatal(IMessage paramIMessage, Throwable paramThrowable);
void fatal(IMessage paramIMessage);
void fatal(Object paramObject);
void fatal(IMessage paramIMessage, Throwable paramThrowable);
void fatal(Object paramObject, Throwable paramThrowable);
void fatal(Object paramObject);
void fatal(String paramString);
void fatal(Object paramObject, Throwable paramThrowable);
void fatal(String paramString, Object[] paramArrayOfObject);
void fatal(String paramString);
void fatal(String paramString, Throwable paramThrowable);
void fatal(String paramString, Object[] paramArrayOfObject);
String getName();
void fatal(String paramString, Throwable paramThrowable);
void info(IMessage paramIMessage);
String getName();
void info(IMessage paramIMessage, Throwable paramThrowable);
void info(IMessage paramIMessage);
void info(Object paramObject);
void info(IMessage paramIMessage, Throwable paramThrowable);
void info(Object paramObject, Throwable paramThrowable);
void info(Object paramObject);
void info(String paramString);
void info(Object paramObject, Throwable paramThrowable);
void info(String paramString, Object[] paramArrayOfObject);
void info(String paramString);
void info(String paramString, Throwable paramThrowable);
void info(String paramString, Object[] paramArrayOfObject);
boolean isDebugEnabled();
void info(String paramString, Throwable paramThrowable);
boolean isEnabled(Level paramLevel);
boolean isDebugEnabled();
boolean isErrorEnabled();
boolean isEnabled(Level paramLevel);
boolean isFatalEnabled();
boolean isErrorEnabled();
boolean isInfoEnabled();
boolean isFatalEnabled();
boolean isTraceEnabled();
boolean isInfoEnabled();
boolean isWarnEnabled();
boolean isTraceEnabled();
void log(Level paramLevel, IMessage paramIMessage);
boolean isWarnEnabled();
void log(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable);
void log(Level paramLevel, IMessage paramIMessage);
void log(Level paramLevel, Object paramObject);
void log(Level paramLevel, IMessage paramIMessage, Throwable paramThrowable);
void log(Level paramLevel, Object paramObject, Throwable paramThrowable);
void log(Level paramLevel, Object paramObject);
void log(Level paramLevel, String paramString);
void log(Level paramLevel, Object paramObject, Throwable paramThrowable);
void log(Level paramLevel, String paramString, Object[] paramArrayOfObject);
void log(Level paramLevel, String paramString);
void log(Level paramLevel, String paramString, Throwable paramThrowable);
void log(Level paramLevel, String paramString, Object[] paramArrayOfObject);
void printf(Level paramLevel, String paramString, Object[] paramArrayOfObject);
void log(Level paramLevel, String paramString, Throwable paramThrowable);
<T extends Throwable> T throwing(Level paramLevel, T paramT);
void printf(Level paramLevel, String paramString, Object[] paramArrayOfObject);
<T extends Throwable> T throwing(T paramT);
<T extends Throwable> T throwing(Level paramLevel, T paramT);
void trace(IMessage paramIMessage);
<T extends Throwable> T throwing(T paramT);
void trace(IMessage paramIMessage, Throwable paramThrowable);
void trace(IMessage paramIMessage);
void trace(Object paramObject);
void trace(IMessage paramIMessage, Throwable paramThrowable);
void trace(Object paramObject, Throwable paramThrowable);
void trace(Object paramObject);
void trace(String paramString);
void trace(Object paramObject, Throwable paramThrowable);
void trace(String paramString, Object[] paramArrayOfObject);
void trace(String paramString);
void trace(String paramString, Throwable paramThrowable);
void trace(String paramString, Object[] paramArrayOfObject);
void warn(IMessage paramIMessage);
void trace(String paramString, Throwable paramThrowable);
void warn(IMessage paramIMessage, Throwable paramThrowable);
void warn(IMessage paramIMessage);
void warn(Object paramObject);
void warn(IMessage paramIMessage, Throwable paramThrowable);
void warn(Object paramObject, Throwable paramThrowable);
void warn(Object paramObject);
void warn(String paramString);
void warn(Object paramObject, Throwable paramThrowable);
void warn(String paramString, Object[] paramArrayOfObject);
void warn(String paramString);
void warn(String paramString, Throwable paramThrowable);
void warn(String paramString, Object[] paramArrayOfObject);
void warn(String paramString, Throwable paramThrowable);
}

View File

@@ -31,138 +31,135 @@ public class Logger extends AbstractLogger {
protected volatile PrivateConfig config;
private final Map<String, AppenderControl> appenders = new ConcurrentHashMap();
public Logger(String name) {
this(name, null, Level.INFO);
this(name, null, Level.INFO);
}
public Logger(String name, IMessageFactory messageFactory, Level defaultLevel) {
super(name, messageFactory);
this.config = new PrivateConfig(Configuration.DEFAULT, this, defaultLevel);
super(name, messageFactory);
this.config = new PrivateConfig(Configuration.DEFAULT, this, defaultLevel);
}
public synchronized void setLevel(Level level) {
if (level != null) {
this.config = new PrivateConfig(this.config, level);
}
if (level != null)
this.config = new PrivateConfig(this.config, level);
}
public Level getLevel() {
return this.config.level;
return this.config.level;
}
@Override
public void abstractLog(Level level, IMessage data, Throwable t) {
LogEvent event = new LogEvent();
event.level = level;
event.message = data;
event.thrown = t;
event.threadName = Thread.currentThread().getName();
LogEvent event = new LogEvent();
event.level = level;
event.message = data;
event.thrown = t;
event.threadName = Thread.currentThread().getName();
log(event);
log(event);
}
public void log(LogEvent event) {
callAppenders(event);
callAppenders(event);
}
protected void callAppenders(LogEvent event) {
for (AppenderControl control : this.appenders.values()) {
control.callAppender(event);
}
for (AppenderControl control : this.appenders.values())
control.callAppender(event);
}
@Override
public boolean isEnabled(Level level, String msg) {
return this.config.filter(level, msg);
return this.config.filter(level, msg);
}
@Override
public boolean isEnabled(Level level, String msg, Throwable t) {
return this.config.filter(level, msg, t);
return this.config.filter(level, msg, t);
}
@Override
public boolean isEnabled(Level level, String msg, Object[] p1) {
return this.config.filter(level, msg, p1);
return this.config.filter(level, msg, p1);
}
@Override
public boolean isEnabled(Level level, Object msg, Throwable t) {
return this.config.filter(level, msg, t);
return this.config.filter(level, msg, t);
}
@Override
public boolean isEnabled(Level level, IMessage msg, Throwable t) {
return this.config.filter(level, msg, t);
return this.config.filter(level, msg, t);
}
public void addAppender(IAppender appender) {
this.appenders.put(appender.getName(), new AppenderControl(appender, null));
this.appenders.put(appender.getName(), new AppenderControl(appender, null));
}
public void removeAppender(IAppender appender) {
this.appenders.remove(appender.getName());
this.appenders.remove(appender.getName());
}
public Map<String, IAppender> getAppenders() {
Map map = new HashMap();
for (Map.Entry entry : this.appenders.entrySet()) {
map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender());
}
return map;
Map map = new HashMap();
for (Map.Entry entry : this.appenders.entrySet())
map.put(entry.getKey(), ((AppenderControl) entry.getValue()).getAppender());
return map;
}
@Override
public String toString() {
String nameLevel = "" + getName() + ":" + getLevel();
return nameLevel;
String nameLevel = "" + getName() + ":" + getLevel();
return nameLevel;
}
protected class PrivateConfig {
public final Configuration config;
private final Level level;
private final int intLevel;
private final Logger logger;
public final Configuration config;
private final Level level;
private final int intLevel;
private final Logger logger;
public PrivateConfig(Configuration c, Logger logger, Level level) {
this.level = level;
this.intLevel = this.level.level;
this.logger = logger;
this.config = c;
for(IAppender appender : config.appenders)
addAppender(appender);
}
public PrivateConfig(Configuration c, Logger logger, Level level) {
this.level = level;
this.intLevel = this.level.level;
this.logger = logger;
public PrivateConfig(PrivateConfig pc, Level level) {
this(pc.config, pc.logger, level);
}
this.config = c;
for (IAppender appender : config.appenders)
addAppender(appender);
}
boolean filter(Level level, String msg) {
public PrivateConfig(PrivateConfig pc, Level level) {
this(pc.config, pc.logger, level);
}
return this.intLevel >= level.level;
}
boolean filter(Level level, String msg) {
boolean filter(Level level, String msg, Throwable t) {
return this.intLevel >= level.level;
}
return this.intLevel >= level.level;
}
boolean filter(Level level, String msg, Throwable t) {
boolean filter(Level level, String msg, Object[] p1) {
return this.intLevel >= level.level;
}
return this.intLevel >= level.level;
}
boolean filter(Level level, String msg, Object[] p1) {
boolean filter(Level level, Object msg, Throwable t) {
return this.intLevel >= level.level;
}
return this.intLevel >= level.level;
}
boolean filter(Level level, Object msg, Throwable t) {
boolean filter(Level level, IMessage msg, Throwable t) {
return this.intLevel >= level.level;
}
return this.intLevel >= level.level;
}
boolean filter(Level level, IMessage msg, Throwable t) {
return this.intLevel >= level.level;
}
}
}

View File

@@ -36,106 +36,101 @@ public class SimpleLogger extends AbstractLogger {
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;
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");
}
}
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;
this.stream = stream;
}
public Level getLevel() {
return this.level;
return this.level;
}
public void setLevel(Level level) {
if (level != null) {
this.level = level;
}
if (level != null)
this.level = level;
}
@Override
public void abstractLog(Level level, IMessage msg, Throwable throwable) {
StringBuilder sb = new StringBuilder();
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(' ');
}
if (this.showDateTime) {
Date now = new Date();
String dateText;
synchronized (this.dateFormatter) {
dateText = this.dateFormatter.format(now);
}
sb.append(dateText);
sb.append(' ');
}
sb.append(level.toString());
sb.append(' ');
if ((this.logName != null) && (this.logName.length() > 0)) {
sb.append(this.logName);
sb.append(' ');
}
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(' ');
ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.printStackTrace(new PrintStream(baos));
sb.append(baos.toString());
}
this.stream.println(sb.toString());
sb.append(level.toString());
sb.append(' ');
if ((this.logName != null) && (this.logName.length() > 0)) {
sb.append(this.logName);
sb.append(' ');
}
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(' ');
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;
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, String msg, Throwable t) {
return this.level.level >= level.level;
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, String msg, Object[] p1) {
return this.level.level >= level.level;
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, Object msg, Throwable t) {
return this.level.level >= level.level;
return this.level.level >= level.level;
}
@Override
protected boolean isEnabled(Level level, IMessage msg, Throwable t) {
return this.level.level >= level.level;
return this.level.level >= level.level;
}
}

View File

@@ -21,15 +21,15 @@ package org.jackhuang.hellominecraft.logging.message;
* @author huangyuhui
*/
public abstract class AbstractMessageFactory
implements IMessageFactory {
implements IMessageFactory {
@Override
public IMessage newMessage(Object message) {
return new ObjectMessage(message);
return new ObjectMessage(message);
}
@Override
public IMessage newMessage(String message) {
return new SimpleMessage(message);
return new SimpleMessage(message);
}
}

View File

@@ -23,8 +23,12 @@ import java.io.Serializable;
* @author huangyuhui
*/
public interface IMessage extends Serializable {
String getFormattedMessage();
String getFormat();
Object[] getParameters();
Throwable getThrowable();
}

View File

@@ -17,15 +17,14 @@
package org.jackhuang.hellominecraft.logging.message;
public class ObjectMessage
implements IMessage {
implements IMessage {
private static final long serialVersionUID = -5903272448334166185L;
private final transient Object obj;
public ObjectMessage(Object obj) {
if (obj == null) {
if (obj == null)
obj = "null";
}
this.obj = obj;
}
@@ -41,17 +40,15 @@ public class ObjectMessage
@Override
public Object[] getParameters() {
return new Object[]{this.obj};
return new Object[] {this.obj};
}
@Override
public boolean equals(Object o) {
if (this == o) {
if (this == o)
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
if ((o == null) || (getClass() != o.getClass()))
return false;
}
ObjectMessage that = (ObjectMessage) o;

View File

@@ -30,7 +30,7 @@ import java.util.Set;
* @author huangyuhui
*/
public class ParameterizedMessage
implements IMessage {
implements IMessage {
public static final String RECURSION_PREFIX = "[...";
public static final String RECURSION_SUFFIX = "...]";
@@ -67,21 +67,20 @@ public class ParameterizedMessage
}
public ParameterizedMessage(String messagePattern, Object arg) {
this(messagePattern, new Object[]{arg});
this(messagePattern, new Object[] {arg});
}
public ParameterizedMessage(String messagePattern, Object arg1, Object arg2) {
this(messagePattern, new Object[]{arg1, arg2});
this(messagePattern, new Object[] {arg1, arg2});
}
private String[] parseArguments(Object[] arguments) {
if (arguments == null) {
if (arguments == null)
return null;
}
int argsCount = countArgumentPlaceholders(this.messagePattern);
int resultArgCount = arguments.length;
if ((argsCount < arguments.length)
&& (this.throwable == null) && ((arguments[(arguments.length - 1)] instanceof Throwable))) {
&& (this.throwable == null) && ((arguments[(arguments.length - 1)] instanceof Throwable))) {
this.throwable = ((Throwable) arguments[(arguments.length - 1)]);
resultArgCount--;
}
@@ -94,18 +93,16 @@ public class ParameterizedMessage
strArgs[0] = deepToString(arguments);
} else {
strArgs = new String[resultArgCount];
for (int i = 0; i < strArgs.length; i++) {
for (int i = 0; i < strArgs.length; i++)
strArgs[i] = deepToString(arguments[i]);
}
}
return strArgs;
}
@Override
public String getFormattedMessage() {
if (this.formattedMessage == null) {
if (this.formattedMessage == null)
this.formattedMessage = formatMessage(this.messagePattern, this.stringArgs);
}
return this.formattedMessage;
}
@@ -116,9 +113,8 @@ public class ParameterizedMessage
@Override
public Object[] getParameters() {
if (this.argArray != null) {
if (this.argArray != null)
return this.argArray;
}
return this.stringArgs;
}
@@ -133,8 +129,10 @@ public class ParameterizedMessage
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ParameterizedMessage that = (ParameterizedMessage) o;
if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null)
@@ -159,11 +157,11 @@ public class ParameterizedMessage
int currentArgument = 0;
for (int i = 0; i < messagePattern.length(); i++) {
char curChar = messagePattern.charAt(i);
if (curChar == ESCAPE_CHAR) {
if (curChar == ESCAPE_CHAR)
escapeCounter++;
} else if ((curChar == DELIM_START)
&& (i < messagePattern.length() - 1)
&& (messagePattern.charAt(i + 1) == DELIM_STOP)) {
else if ((curChar == DELIM_START)
&& (i < messagePattern.length() - 1)
&& (messagePattern.charAt(i + 1) == DELIM_STOP)) {
int escapedEscapes = escapeCounter / 2;
for (int j = 0; j < escapedEscapes; j++)
result.append(ESCAPE_CHAR);
@@ -193,36 +191,39 @@ public class ParameterizedMessage
}
public static int countArgumentPlaceholders(String messagePattern) {
if (messagePattern == null) return 0;
if (messagePattern == null)
return 0;
int delim = messagePattern.indexOf(123);
if (delim == -1) return 0;
if (delim == -1)
return 0;
int result = 0;
boolean isEscaped = false;
for (int i = 0; i < messagePattern.length(); i++) {
char curChar = messagePattern.charAt(i);
if (curChar == ESCAPE_CHAR) {
if (curChar == ESCAPE_CHAR)
isEscaped = !isEscaped;
} else if (curChar == DELIM_START) {
else if (curChar == DELIM_START) {
if ((!isEscaped)
&& (i < messagePattern.length() - 1)
&& (messagePattern.charAt(i + 1) == DELIM_STOP)) {
&& (i < messagePattern.length() - 1)
&& (messagePattern.charAt(i + 1) == DELIM_STOP)) {
result++;
i++;
}
isEscaped = false;
} else {
} else
isEscaped = false;
}
}
return result;
}
public static String deepToString(Object o) {
if (o == null) return null;
if (o instanceof String) return (String) o;
if (o == null)
return null;
if (o instanceof String)
return (String) o;
StringBuilder str = new StringBuilder();
Set dejaVu = new HashSet();
recursiveDeepToString(o, str, dejaVu);
@@ -239,53 +240,57 @@ public class ParameterizedMessage
return;
}
Class oClass = o.getClass();
if (oClass.isArray()) {
if (oClass == byte[].class) {
if (oClass.isArray())
if (oClass == byte[].class)
str.append(Arrays.toString((byte[]) (byte[]) o));
} else if (oClass == short[].class) {
else if (oClass == short[].class)
str.append(Arrays.toString((short[]) (short[]) o));
} else if (oClass == int[].class) {
else if (oClass == int[].class)
str.append(Arrays.toString((int[]) (int[]) o));
} else if (oClass == long[].class) {
else if (oClass == long[].class)
str.append(Arrays.toString((long[]) (long[]) o));
} else if (oClass == float[].class) {
else if (oClass == float[].class)
str.append(Arrays.toString((float[]) (float[]) o));
} else if (oClass == double[].class) {
else if (oClass == double[].class)
str.append(Arrays.toString((double[]) (double[]) o));
} else if (oClass == boolean[].class) {
else if (oClass == boolean[].class)
str.append(Arrays.toString((boolean[]) (boolean[]) o));
} else if (oClass == char[].class) {
else if (oClass == char[].class)
str.append(Arrays.toString((char[]) (char[]) o));
} else {
else {
String id = identityToString(o);
if (dejaVu.contains(id)) {
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
} else {
else {
dejaVu.add(id);
Object[] oArray = (Object[]) (Object[]) o;
str.append("[");
boolean first = true;
for (Object current : oArray) {
if (first) first = false;
else str.append(", ");
if (first)
first = false;
else
str.append(", ");
recursiveDeepToString(current, str, new HashSet(dejaVu));
}
str.append("]");
}
}
} else if ((o instanceof Map)) {
else if ((o instanceof Map)) {
String id = identityToString(o);
if (dejaVu.contains(id)) {
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
} else {
else {
dejaVu.add(id);
Map oMap = (Map) o;
str.append("{");
boolean isFirst = true;
for (Object o1 : oMap.entrySet()) {
Map.Entry current = (Map.Entry) o1;
if (isFirst) isFirst = false;
else str.append(", ");
if (isFirst)
isFirst = false;
else
str.append(", ");
Object key = current.getKey();
Object value = current.getValue();
recursiveDeepToString(key, str, new HashSet(dejaVu));
@@ -296,17 +301,19 @@ public class ParameterizedMessage
}
} else if ((o instanceof Collection)) {
String id = identityToString(o);
if (dejaVu.contains(id)) {
if (dejaVu.contains(id))
str.append("[...").append(id).append("...]");
} else {
else {
dejaVu.add(id);
Collection oCol = (Collection) o;
str.append("[");
boolean isFirst = true;
for (Iterator i$ = oCol.iterator(); i$.hasNext();) {
Object anOCol = i$.next();
if (isFirst) isFirst = false;
else str.append(", ");
if (isFirst)
isFirst = false;
else
str.append(", ");
recursiveDeepToString(anOCol, str, new HashSet(dejaVu));
}
str.append("]");
@@ -316,7 +323,7 @@ public class ParameterizedMessage
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
str.append(format.format(date));
} else {
} else
try {
str.append(o.toString());
} catch (Throwable t) {
@@ -332,16 +339,16 @@ public class ParameterizedMessage
}
str.append("!!!]");
}
}
}
public static String identityToString(Object obj) {
if (obj == null) return null;
return obj.getClass().getName()+"@"+Integer.toHexString(System.identityHashCode(obj));
if (obj == null)
return null;
return obj.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(obj));
}
@Override
public String toString() {
return "ParameterizedMessage[messagePattern="+this.messagePattern+", stringArgs="+Arrays.toString(this.stringArgs)+", throwable="+this.throwable+"]";
return "ParameterizedMessage[messagePattern=" + this.messagePattern + ", stringArgs=" + Arrays.toString(this.stringArgs) + ", throwable=" + this.throwable + "]";
}
}

View File

@@ -26,6 +26,6 @@ public final class ParameterizedMessageFactory extends AbstractMessageFactory {
@Override
public IMessage newMessage(String message, Object[] params) {
return new ParameterizedMessage(message, params);
return new ParameterizedMessage(message, params);
}
}

View File

@@ -21,60 +21,58 @@ package org.jackhuang.hellominecraft.logging.message;
* @author huangyuhui
*/
public class SimpleMessage
implements IMessage {
implements IMessage {
private static final long serialVersionUID = -8398002534962715992L;
private final String message;
public SimpleMessage() {
this(null);
this(null);
}
public SimpleMessage(String message) {
this.message = message;
this.message = message;
}
@Override
public String getFormattedMessage() {
return this.message;
return this.message;
}
@Override
public String getFormat() {
return this.message;
return this.message;
}
@Override
public Object[] getParameters() {
return null;
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
if (this == o)
return true;
if ((o == null) || (getClass() != o.getClass()))
return false;
SimpleMessage that = (SimpleMessage) o;
SimpleMessage that = (SimpleMessage) o;
return this.message != null ? this.message.equals(that.message) : that.message == null;
return this.message != null ? this.message.equals(that.message) : that.message == null;
}
@Override
public int hashCode() {
return this.message != null ? this.message.hashCode() : 0;
return this.message != null ? this.message.hashCode() : 0;
}
@Override
public String toString() {
return "SimpleMessage[message=" + this.message + "]";
return "SimpleMessage[message=" + this.message + "]";
}
@Override
public Throwable getThrowable() {
return null;
return null;
}
}

View File

@@ -20,7 +20,7 @@ import java.util.Arrays;
import java.util.IllegalFormatException;
public class StringFormattedMessage
implements IMessage {
implements IMessage {
private static final long serialVersionUID = -665975803997290697L;
private final String messagePattern;
@@ -30,76 +30,70 @@ public class StringFormattedMessage
private transient Throwable throwable;
public StringFormattedMessage(String messagePattern, Object[] arguments) {
this.messagePattern = messagePattern;
this.argArray = arguments;
if ((arguments != null) && (arguments.length > 0) && ((arguments[(arguments.length - 1)] instanceof Throwable))) {
this.throwable = ((Throwable) arguments[(arguments.length - 1)]);
}
this.messagePattern = messagePattern;
this.argArray = arguments;
if ((arguments != null) && (arguments.length > 0) && ((arguments[(arguments.length - 1)] instanceof Throwable)))
this.throwable = ((Throwable) arguments[(arguments.length - 1)]);
}
@Override
public String getFormattedMessage() {
if (this.formattedMessage == null) {
this.formattedMessage = formatMessage(this.messagePattern, this.argArray);
}
return this.formattedMessage;
if (this.formattedMessage == null)
this.formattedMessage = formatMessage(this.messagePattern, this.argArray);
return this.formattedMessage;
}
@Override
public String getFormat() {
return this.messagePattern;
return this.messagePattern;
}
@Override
public Object[] getParameters() {
if (this.argArray != null) {
return this.argArray;
}
return this.stringArgs;
if (this.argArray != null)
return this.argArray;
return this.stringArgs;
}
protected String formatMessage(String msgPattern, Object[] args) {
try {
return String.format(msgPattern, args);
} catch (IllegalFormatException ife) {
System.err.println("Unable to format msg: " + msgPattern);
ife.printStackTrace();
}
return msgPattern;
try {
return String.format(msgPattern, args);
} catch (IllegalFormatException ife) {
System.err.println("Unable to format msg: " + msgPattern);
ife.printStackTrace();
}
return msgPattern;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
if (this == o)
return true;
if ((o == null) || (getClass() != o.getClass()))
return false;
StringFormattedMessage that = (StringFormattedMessage) o;
StringFormattedMessage that = (StringFormattedMessage) o;
if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null) {
return false;
}
if (this.messagePattern != null ? !this.messagePattern.equals(that.messagePattern) : that.messagePattern != null)
return false;
return Arrays.equals(this.stringArgs, that.stringArgs);
return Arrays.equals(this.stringArgs, that.stringArgs);
}
@Override
public int hashCode() {
int result = this.messagePattern != null ? this.messagePattern.hashCode() : 0;
result = 31 * result + (this.stringArgs != null ? Arrays.hashCode(this.stringArgs) : 0);
return result;
int result = this.messagePattern != null ? this.messagePattern.hashCode() : 0;
result = 31 * result + (this.stringArgs != null ? Arrays.hashCode(this.stringArgs) : 0);
return result;
}
@Override
public String toString() {
return "StringFormatMessage[messagePattern=" + this.messagePattern + ", args=" + Arrays.toString(this.argArray) + "]";
return "StringFormatMessage[messagePattern=" + this.messagePattern + ", args=" + Arrays.toString(this.argArray) + "]";
}
@Override
public Throwable getThrowable() {
return this.throwable;
return this.throwable;
}
}

View File

@@ -42,9 +42,9 @@ public abstract class Task {
aborted = true;
return false;
}
protected boolean aborted = false;
public boolean isAborted() {
return aborted;
}
@@ -73,7 +73,7 @@ public abstract class Task {
public void setParallelExecuting(boolean parallelExecuting) {
this.parallelExecuting = parallelExecuting;
}
ArrayList<DoingDoneListener<Task>> taskListener = new ArrayList();
public Task addTaskListener(DoingDoneListener<Task> l) {
@@ -94,7 +94,7 @@ public abstract class Task {
public Collection<Task> getAfterTasks() {
return null;
}
protected ProgressProviderListener ppl;
public Task setProgressProviderListener(ProgressProviderListener p) {

View File

@@ -98,7 +98,8 @@ public class TaskList extends Thread {
}
while (!runningThread.isEmpty())
try {
if (this.isInterrupted()) return;
if (this.isInterrupted())
return;
Thread.sleep(1);
} catch (InterruptedException ignore) {
}
@@ -119,7 +120,7 @@ public class TaskList extends Thread {
boolean returns = false;
try {
returns = t.executeTask();
} catch(Throwable e) {
} catch (Throwable e) {
t.setFailReason(e);
}
if (returns) {
@@ -144,7 +145,7 @@ public class TaskList extends Thread {
threadPool.clear();
totTask = taskQueue.size();
while(!taskQueue.isEmpty())
while (!taskQueue.isEmpty())
executeTask(taskQueue.remove(0));
if (shouldContinue)
for (Runnable d : allDone)
@@ -160,7 +161,8 @@ public class TaskList extends Thread {
while (!threadPool.isEmpty())
synchronized (threadPool) {
InvokeThread it = threadPool.iterator().next();
if (!it.task.abort()) it.interrupt();
if (!it.task.abort())
it.interrupt();
threadPool.remove(it);
}
this.interrupt();

View File

@@ -27,7 +27,9 @@ import org.jackhuang.hellominecraft.utils.functions.Consumer;
* @param <T> Runnable&lt;T&gt;
*/
public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegistrar<T> {
private final Consumer<T> r;
public TaskRunnableArg1(String info, Consumer<T> r) {
super(info);
this.r = r;
@@ -35,16 +37,17 @@ public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegis
@Override
public boolean executeTask() {
if(al.size() != 1) throw new IllegalStateException("the count of args is not one.");
if (al.size() != 1)
throw new IllegalStateException("the count of args is not one.");
try {
r.accept(al.get(0).getResult());
return true;
} catch(Throwable t) {
} catch (Throwable t) {
setFailReason(t);
return false;
}
}
ArrayList<PreviousResult<T>> al = new ArrayList();
@Override
@@ -52,7 +55,5 @@ public class TaskRunnableArg1<T> extends TaskInfo implements PreviousResultRegis
al.add(pr);
return this;
}
}
}

View File

@@ -30,15 +30,15 @@ import org.jackhuang.hellominecraft.utils.SwingUtils;
* @author huangyuhui
*/
public class TaskWindow extends javax.swing.JDialog
implements ProgressProviderListener, Runnable, DoingDoneListener<Task> {
implements ProgressProviderListener, Runnable, DoingDoneListener<Task> {
private static final TaskWindow instance = new TaskWindow();
private static TaskWindow inst() {
instance.clean();
return instance;
}
public static TaskWindowFactory getInstance() {
return new TaskWindowFactory();
}
@@ -72,14 +72,16 @@ public class TaskWindow extends javax.swing.JDialog
}
public synchronized void clean() {
if (isVisible()) return;
if (isVisible())
return;
taskList = new TaskList();
taskList.addTaskListener(this);
taskList.addAllDoneListener(this);
}
public boolean start() {
if (isVisible() || taskList == null || taskList.isAlive()) return false;
if (isVisible() || taskList == null || taskList.isAlive())
return false;
pgsTotal.setValue(0);
suc = false;
SwingUtils.clearDefaultTable(lstDownload);
@@ -169,7 +171,8 @@ public class TaskWindow extends javax.swing.JDialog
}//GEN-LAST:event_btnCancelActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
if(taskList == null) return;
if (taskList == null)
return;
tasks.clear();
if (!this.failReasons.isEmpty()) {
@@ -203,7 +206,8 @@ public class TaskWindow extends javax.swing.JDialog
public void setProgress(Task task, int progress, int max) {
SwingUtilities.invokeLater(() -> {
int idx = tasks.indexOf(task);
if (idx == -1) return;
if (idx == -1)
return;
int pgs = progress * 100 / max;
if (progresses.contains(idx) && progresses.get(idx) != pgs && lstDownload.getRowCount() > idx) {
SwingUtils.setValueAt(lstDownload, pgs + "%", idx, 1);
@@ -224,7 +228,8 @@ public class TaskWindow extends javax.swing.JDialog
task.setProgressProviderListener(this);
SwingUtilities.invokeLater(() -> {
if(taskList == null) return;
if (taskList == null)
return;
tasks.add(task);
progresses.add(0);
SwingUtils.appendLast(lstDownload, task.getInfo(), "0%");
@@ -239,11 +244,13 @@ public class TaskWindow extends javax.swing.JDialog
@Override
public void onDone(Task task) {
SwingUtilities.invokeLater(() -> {
if(taskList == null) return;
if (taskList == null)
return;
pgsTotal.setMaximum(taskList.taskCount());
pgsTotal.setValue(pgsTotal.getValue() + 1);
int idx = tasks.indexOf(task);
if (idx == -1) return;
if (idx == -1)
return;
tasks.remove(idx);
progresses.remove(idx);
SwingUtils.removeRow(lstDownload, idx);
@@ -253,12 +260,14 @@ public class TaskWindow extends javax.swing.JDialog
@Override
public void onFailed(Task task) {
SwingUtilities.invokeLater(() -> {
if(taskList == null) return;
if (taskList == null)
return;
failReasons.add(task.getInfo() + ": " + (null == task.getFailReason() ? "No exception" : (StrUtils.isBlank(task.getFailReason().getLocalizedMessage()) ? task.getFailReason().getClass().getSimpleName() : task.getFailReason().getLocalizedMessage())));
pgsTotal.setMaximum(taskList.taskCount());
pgsTotal.setValue(pgsTotal.getValue() + 1);
int idx = tasks.indexOf(task);
if (idx == -1) return;
if (idx == -1)
return;
SwingUtils.setValueAt(lstDownload, task.getFailReason(), idx, 0);
SwingUtils.setValueAt(lstDownload, "0%", idx, 1);
SwingUtils.moveEnd(srlDownload);
@@ -273,26 +282,31 @@ public class TaskWindow extends javax.swing.JDialog
@Override
public void setStatus(Task task, String sta) {
SwingUtilities.invokeLater(() -> {
if(taskList == null) return;
if (taskList == null)
return;
int idx = tasks.indexOf(task);
if (idx == -1) return;
if (idx == -1)
return;
SwingUtils.setValueAt(lstDownload, task.getInfo() + ": " + sta, idx, 0);
});
}
public static class TaskWindowFactory {
LinkedList<Task> ll = new LinkedList<>();
public TaskWindowFactory addTask(Task t) {
ll.add(t);
return this;
}
public boolean start() {
synchronized(instance) {
if (instance.isVisible()) return false;
synchronized (instance) {
if (instance.isVisible())
return false;
TaskWindow tw = inst();
for(Task t : ll) tw.addTask(t);
for (Task t : ll)
tw.addTask(t);
return tw.start();
}
}

View File

@@ -22,7 +22,7 @@ package org.jackhuang.hellominecraft.tasks.communication;
* @param <T> Task result type
*/
public interface PreviousResult<T> {
T getResult();
}

View File

@@ -24,10 +24,11 @@ import org.jackhuang.hellominecraft.tasks.Task;
* @param <T> Previous task result type
*/
public interface PreviousResultRegistrar<T> {
/**
*
*
* @param pr previous task handler
*
* @return task self instance
*/
Task registerPreviousResult(PreviousResult<T> pr);

View File

@@ -37,7 +37,7 @@ public class ContentGetAndShowTask extends HTTPGetTask implements Event<String>
}
String info;
@Override
public String getInfo() {
return info;

View File

@@ -25,5 +25,6 @@ import org.jackhuang.hellominecraft.tasks.ProgressProviderListener;
public interface DownloadListener extends ProgressProviderListener {
boolean OnFailed();
void OnFailedMoreThan5Times(String url);
}
}

View File

@@ -103,7 +103,7 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
// Open connection to URL.
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
= (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("User-Agent", "Hello Minecraft! Launcher");
@@ -167,7 +167,8 @@ public class FileDownloadTask extends Task implements PreviousResult<File>, Prev
if (aborted)
tempFile.delete();
else {
if (filePath.exists()) filePath.delete();
if (filePath.exists())
filePath.delete();
tempFile.renameTo(filePath);
}
if (ppl != null)

View File

@@ -52,7 +52,8 @@ public class HTTPGetTask extends TaskInfo implements PreviousResult<String> {
@Override
public boolean executeTask() {
for (int repeat = 0; repeat < 6; repeat++) {
if (repeat > 0) HMCLog.warn("Failed to download, repeat: " + repeat);
if (repeat > 0)
HMCLog.warn("Failed to download, repeat: " + repeat);
try {
URLConnection conn = new URL(url).openConnection();
InputStream is = conn.getInputStream();
@@ -61,12 +62,10 @@ public class HTTPGetTask extends TaskInfo implements PreviousResult<String> {
int size = conn.getContentLength(), read = 0;
while ((i = is.read()) != -1) {
baos.write(i);
if (ppl != null) {
if (ppl != null)
ppl.setProgress(this, ++read, size);
}
if (!shouldContinue) {
if (!shouldContinue)
return true;
}
}
result = baos.toString();
tdtsl.execute(result);

View File

@@ -21,17 +21,17 @@ package org.jackhuang.hellominecraft.tasks.download;
* @author huangyuhui
*/
public class NetException extends RuntimeException {
public NetException(Exception message) {
super(message);
}
public NetException(String message) {
super(message);
}
public NetException(String message, Exception e) {
super(message, e);
}
}

View File

@@ -78,8 +78,10 @@ public class ArrayUtils {
}
public static <K> K getEnd(K[] k) {
if (k == null) return null;
else return k[k.length - 1];
if (k == null)
return null;
else
return k[k.length - 1];
}
public static List tryGetMapWithList(Map map, String key) {

View File

@@ -29,14 +29,16 @@ import java.util.Iterator;
public final class CollectionUtils {
public static <T> void forEach(Collection<T> coll, Consumer<T> p) {
for (T t : coll) p.accept(t);
for (T t : coll)
p.accept(t);
}
public static <T> Collection<T> sortOut(Collection<T> coll, Predicate<T> p) {
ArrayList<T> newColl = new ArrayList<>();
forEach(coll, t -> {
if (p.apply(t)) newColl.add(t);
});
if (p.apply(t))
newColl.add(t);
});
return newColl;
}

View File

@@ -44,7 +44,8 @@ public class EventHandler<T> {
public boolean execute(T x) {
boolean flag = true;
for (Event<T> t : handlers)
if (!t.call(sender, x)) flag = false;
if (!t.call(sender, x))
flag = false;
return flag;
}

View File

@@ -27,7 +27,7 @@ import org.jackhuang.hellominecraft.views.LogWindow;
* @author huangyuhui
*/
public class LogWindowOutputStream extends OutputStream {
private static final Timer TIMER = new Timer();
private final LogWindow txt;
@@ -84,9 +84,9 @@ public class LogWindowOutputStream extends OutputStream {
@Override
public final void write(int paramInt) {
append(new String(new byte[]{(byte) paramInt}));
append(new String(new byte[] {(byte) paramInt}));
}
public static void dispose() {
TIMER.cancel();
}

View File

@@ -44,9 +44,12 @@ public class MathUtils {
return Integer.parseInt(s);
} catch (Exception e) {
int a = parseInt(s.substring(0, s.length() - 1), def);
if (s.endsWith("g")) return a * 1024;
else if (s.endsWith("k")) return a / 1024;
else return a;
if (s.endsWith("g"))
return a * 1024;
else if (s.endsWith("k"))
return a / 1024;
else
return a;
}
}

View File

@@ -52,7 +52,7 @@ public final class NetUtils {
}
public static String getStreamContent(InputStream is, String encoding)
throws IOException {
throws IOException {
StringBuilder sb = new StringBuilder();
try (InputStreamReader br = new InputStreamReader(is, encoding)) {
int len;
@@ -82,15 +82,16 @@ public final class NetUtils {
/**
* Sends an HTTP GET request to a url
*
* @param endpoint - The URL of the server. (Example: "
* http://www.yahoo.com/search")
* @param endpoint - The URL of the server. (Example: "
* http://www.yahoo.com/search")
* @param requestParameters - all the request parameters (Example:
* "param1=val1&param2=val2"). Note: This method will add the question mark
* (?) to the request - DO NOT add it yourself
* "param1=val1&param2=val2"). Note: This method will add the question mark
* (?) to the request - DO NOT add it yourself
*
* @return - The response from the end point
*/
public static String sendGetRequest(String endpoint,
String requestParameters) {
String requestParameters) {
String result = null;
if (endpoint.startsWith("http://"))
// Send a GET request to the servlet
@@ -118,7 +119,7 @@ public final class NetUtils {
}
return result;
}
public static String post(URL u, Map<String, String> params) {
StringBuilder sb = new StringBuilder();
if (params != null) {
@@ -136,11 +137,11 @@ public final class NetUtils {
public static String post(URL u, String post) {
return post(u, post, "application/x-www-form-urlencoded");
}
public static String post(URL u, String post, String contentType) {
return post(u, post, contentType, Proxy.NO_PROXY);
}
public static String post(URL u, String post, String contentType, Proxy proxy) {
try {
HttpURLConnection con = (HttpURLConnection) u.openConnection(proxy);
@@ -157,16 +158,18 @@ public final class NetUtils {
os = con.getOutputStream();
IOUtils.write(post, os, DEFAULT_CHARSET);
} finally {
if (os != null) IOUtils.closeQuietly(os);
if (os != null)
IOUtils.closeQuietly(os);
}
String result = null;
InputStream is = null;
try {
is = con.getInputStream();
result = getStreamContent(is);
} catch(IOException ex) {
if (is != null) IOUtils.closeQuietly(is);
} catch (IOException ex) {
if (is != null)
IOUtils.closeQuietly(is);
is = con.getErrorStream();
result = getStreamContent(is);
}

View File

@@ -34,37 +34,32 @@ public final class StrUtils {
public static String substring(String src, int start_idx, int end_idx) {
byte[] b = src.getBytes();
String tgt = "";
for (int i = start_idx; i <= end_idx; i++) {
for (int i = start_idx; i <= end_idx; i++)
tgt += (char) b[i];
}
return tgt;
}
public static String makeCommand(List<String> cmd) {
StringBuilder cmdbuf = new StringBuilder(120);
for (int i = 0; i < cmd.size(); i++) {
if (i > 0) {
if (i > 0)
cmdbuf.append(' ');
}
String s = cmd.get(i);
if (s.indexOf(' ') >= 0 || s.indexOf('\t') >= 0) {
if (s.indexOf(' ') >= 0 || s.indexOf('\t') >= 0)
if (s.charAt(0) != '"') {
cmdbuf.append('"');
cmdbuf.append(s);
if (s.endsWith("\\")) {
if (s.endsWith("\\"))
cmdbuf.append("\\");
}
cmdbuf.append('"');
} else if (s.endsWith("\"")) {
} else if (s.endsWith("\""))
/* The argument has already been quoted. */
cmdbuf.append(s);
} else {
else
/* Unmatched quote for the argument. */
throw new IllegalArgumentException();
}
} else {
else
cmdbuf.append(s);
}
}
String str = cmdbuf.toString();
@@ -76,61 +71,49 @@ public final class StrUtils {
}
public static boolean startsWithOne(String[] a, String match) {
if (a == null) {
if (a == null)
return false;
}
for (String b : a) {
if (startsWith(match, b)) {
for (String b : a)
if (startsWith(match, b))
return true;
}
}
return false;
}
public static boolean equalsOne(String base, String... a) {
for (String s : a) {
if (base.equals(s)) {
for (String s : a)
if (base.equals(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())) {
for (String a : base)
for (String b : match)
if (a.toLowerCase().contains(b.toLowerCase()))
return true;
}
}
}
return false;
}
public static int getCharShowTime(String s, char c) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == c)
res++;
}
}
return res;
}
public static String formatVersion(String ver) {
if (isBlank(ver)) {
if (isBlank(ver))
return null;
} else {
for(char ch : ver.toCharArray()) {
if((ch < '0' || ch > '9') && ch != '.') return null;
}
}
else
for (char ch : ver.toCharArray())
if ((ch < '0' || ch > '9') && ch != '.')
return null;
int i = getCharShowTime(ver, '.');
if (i == 1) {
if (i == 1)
return ver + ".0";
} else {
else
return ver;
}
}
public static String parseParams(String addBefore, Collection paramArrayOfObject, String paramString) {
@@ -138,57 +121,49 @@ public final class StrUtils {
}
public static String parseParams(String addBefore, Object[] paramArrayOfObject, String paramString) {
if (paramArrayOfObject == null) {
if (paramArrayOfObject == null)
return "";
}
StringBuilder localStringBuffer = new StringBuilder();
for (int i = 0; i < paramArrayOfObject.length; i++) {
Object localObject = paramArrayOfObject[i];
if (i > 0) {
if (i > 0)
localStringBuffer.append(addBefore).append(paramString);
}
if (localObject == null) {
if (localObject == null)
localStringBuffer.append("null");
} else if (localObject.getClass().isArray()) {
else if (localObject.getClass().isArray()) {
localStringBuffer.append("[");
if ((localObject instanceof Object[])) {
Object[] arrayOfObject = (Object[]) localObject;
localStringBuffer.append(parseParams(addBefore, arrayOfObject, paramString));
} else {
} else
for (int j = 0; j < Array.getLength(localObject); j++) {
if (j > 0) {
if (j > 0)
localStringBuffer.append(paramString);
}
localStringBuffer.append(addBefore).append(Array.get(localObject, j));
}
}
localStringBuffer.append("]");
} else {
} else
localStringBuffer.append(addBefore).append(paramArrayOfObject[i]);
}
}
return localStringBuffer.toString();
}
public static boolean isEquals(String base, String to) {
if (base == null) {
if (base == null)
return (to == null);
} else {
else
return base.equals(to);
}
}
public static Dimension parseDimension(String str) {
String[] tokenized = tokenize(str, "x,");
if (tokenized.length != 2) {
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)) {
if ((i < 0) || (j < 0))
return null;
}
return new Dimension(i, j);
}
@@ -210,9 +185,8 @@ public final class StrUtils {
public static String trimExtension(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int i = filename.lastIndexOf('.');
if ((i > -1) && (i < (filename.length()))) {
if ((i > -1) && (i < (filename.length())))
return filename.substring(0, i);
}
}
return filename;
}

View File

@@ -38,28 +38,29 @@ public class SwingUtils {
* Make DefaultTableModel by overriding getColumnClass and isCellEditable of
* DefaultTableModel.
*
* @param titleA The title of each column.
* @param typesA The type of each column value.
* @param titleA The title of each column.
* @param typesA The type of each column value.
* @param canEditA Is column editable?
*
* @return
*/
public static DefaultTableModel makeDefaultTableModel(String[] titleA, final Class[] typesA, final boolean[] canEditA) {
return new javax.swing.table.DefaultTableModel(
new Object[][]{},
titleA) {
Class[] types = typesA;
boolean[] canEdit = canEditA;
new Object[][] {},
titleA) {
Class[] types = typesA;
boolean[] canEdit = canEditA;
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
};
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
};
}
/**
@@ -99,6 +100,7 @@ public class SwingUtils {
* Get the DefaultListModel from JList.
*
* @param list
*
* @return Forcely Type casted to DefaultListModel
*/
public static DefaultListModel getDefaultListModel(JList list) {
@@ -108,7 +110,7 @@ public class SwingUtils {
/**
* Append new element to JList
*
* @param list the JList
* @param list the JList
* @param element the Element
*/
public static void appendLast(JList list, Object element) {
@@ -152,12 +154,14 @@ public class SwingUtils {
}
public static String getParsedJPanelText(JLabel jLabel1, String longString) {
if (StrUtils.isBlank(longString)) return longString;
if (StrUtils.isBlank(longString))
return longString;
StringBuilder builder = new StringBuilder();
char[] chars = longString.toCharArray();
FontMetrics fontMetrics = jLabel1.getFontMetrics(jLabel1.getFont());
for (int beginIndex = 0, limit = 1;; limit++) {
if (beginIndex + limit >= chars.length) break;
if (beginIndex + limit >= chars.length)
break;
if (fontMetrics.charsWidth(chars, beginIndex, limit) < jLabel1.getWidth()) {
if (beginIndex + limit < chars.length)
continue;

View File

@@ -60,7 +60,9 @@ public final class Utils {
Field field = ClassLoader.class.getDeclaredField("usr_paths");
field.setAccessible(true);
String[] paths = (String[]) field.get(null);
for (String path : paths) if (s.equals(path)) return;
for (String path : paths)
if (s.equals(path))
return;
String[] tmp = new String[paths.length + 1];
System.arraycopy(paths, 0, tmp, 0, paths.length);
tmp[paths.length] = s;
@@ -166,6 +168,7 @@ public final class Utils {
/**
* In order to fight against the permission manager by Minecraft Forge.
*
* @param status exit code
*/
public static void shutdownForcely(int status) {
@@ -181,6 +184,7 @@ public final class Utils {
}
public static void requireNonNull(Object o) {
if (o == null) throw new NullPointerException("Oh dear, there is a problem...");
if (o == null)
throw new NullPointerException("Oh dear, there is a problem...");
}
}

View File

@@ -68,9 +68,12 @@ public final class VersionNumber implements Comparable<VersionNumber> {
@Override
public int compareTo(VersionNumber o) {
if (isOlder(this, o)) return -1;
else if (isOlder(o, this)) return 1;
else return 0;
if (isOlder(this, o))
return -1;
else if (isOlder(o, this))
return 1;
else
return 0;
}
}

View File

@@ -25,87 +25,80 @@ import java.io.UnsupportedEncodingException;
public class 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;
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, String charset) throws UnsupportedEncodingException {
return encode(s.getBytes(charset));
return encode(s.getBytes(charset));
}
public static char[] encode(String s) {
return encode(s.getBytes());
return encode(s.getBytes());
}
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;
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();
.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;
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

@@ -33,10 +33,10 @@ public class Charsets {
public static final Charset UTF_8 = Charset.forName("UTF-8");
public static Charset toCharset(Charset charset) {
return charset == null ? Charset.defaultCharset() : charset;
return charset == null ? Charset.defaultCharset() : charset;
}
public static Charset toCharset(String charset) {
return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
return charset == null ? Charset.defaultCharset() : Charset.forName(charset);
}
}

View File

@@ -30,255 +30,255 @@ public class DigestUtils {
private static final int STREAM_BUFFER_LENGTH = 1024;
private static byte[] digest(MessageDigest digest, InputStream data)
throws IOException {
return updateDigest(digest, data).digest();
throws IOException {
return updateDigest(digest, data).digest();
}
public static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
}
public static MessageDigest getMd2Digest() {
return getDigest("MD2");
return getDigest("MD2");
}
public static MessageDigest getMd5Digest() {
return getDigest("MD5");
return getDigest("MD5");
}
public static MessageDigest getSha1Digest() {
return getDigest("SHA-1");
return getDigest("SHA-1");
}
public static MessageDigest getSha256Digest() {
return getDigest("SHA-256");
return getDigest("SHA-256");
}
public static MessageDigest getSha384Digest() {
return getDigest("SHA-384");
return getDigest("SHA-384");
}
public static MessageDigest getSha512Digest() {
return getDigest("SHA-512");
return getDigest("SHA-512");
}
@Deprecated
public static MessageDigest getShaDigest() {
return getSha1Digest();
return getSha1Digest();
}
public static byte[] md2(byte[] data) {
return getMd2Digest().digest(data);
return getMd2Digest().digest(data);
}
public static byte[] md2(InputStream data)
throws IOException {
return digest(getMd2Digest(), data);
throws IOException {
return digest(getMd2Digest(), data);
}
public static byte[] md2(String data) {
return md2(data.getBytes(Charsets.UTF_8));
return md2(data.getBytes(Charsets.UTF_8));
}
public static String md2Hex(byte[] data) {
return Hex.encodeHexString(md2(data));
return Hex.encodeHexString(md2(data));
}
public static String md2Hex(InputStream data)
throws IOException {
return Hex.encodeHexString(md2(data));
throws IOException {
return Hex.encodeHexString(md2(data));
}
public static String md2Hex(String data) {
return Hex.encodeHexString(md2(data));
return Hex.encodeHexString(md2(data));
}
public static byte[] md5(byte[] data) {
return getMd5Digest().digest(data);
return getMd5Digest().digest(data);
}
public static byte[] md5(InputStream data)
throws IOException {
return digest(getMd5Digest(), data);
throws IOException {
return digest(getMd5Digest(), data);
}
public static byte[] md5(String data) {
return md5(data.getBytes(Charsets.UTF_8));
return md5(data.getBytes(Charsets.UTF_8));
}
public static String md5Hex(byte[] data) {
return Hex.encodeHexString(md5(data));
return Hex.encodeHexString(md5(data));
}
public static String md5Hex(InputStream data)
throws IOException {
return Hex.encodeHexString(md5(data));
throws IOException {
return Hex.encodeHexString(md5(data));
}
public static String md5Hex(String data) {
return Hex.encodeHexString(md5(data));
return Hex.encodeHexString(md5(data));
}
@Deprecated
public static byte[] sha(byte[] data) {
return sha1(data);
return sha1(data);
}
@Deprecated
public static byte[] sha(InputStream data)
throws IOException {
return sha1(data);
throws IOException {
return sha1(data);
}
@Deprecated
public static byte[] sha(String data) {
return sha1(data);
return sha1(data);
}
public static byte[] sha1(byte[] data) {
return getSha1Digest().digest(data);
return getSha1Digest().digest(data);
}
public static byte[] sha1(InputStream data)
throws IOException {
return digest(getSha1Digest(), data);
throws IOException {
return digest(getSha1Digest(), data);
}
public static byte[] sha1(String data) {
return sha1(data.getBytes(Charsets.UTF_8));
return sha1(data.getBytes(Charsets.UTF_8));
}
public static String sha1Hex(byte[] data) {
return Hex.encodeHexString(sha1(data));
return Hex.encodeHexString(sha1(data));
}
public static String sha1Hex(InputStream data)
throws IOException {
return Hex.encodeHexString(sha1(data));
throws IOException {
return Hex.encodeHexString(sha1(data));
}
public static String sha1Hex(String data) {
return Hex.encodeHexString(sha1(data));
return Hex.encodeHexString(sha1(data));
}
public static byte[] sha256(byte[] data) {
return getSha256Digest().digest(data);
return getSha256Digest().digest(data);
}
public static byte[] sha256(InputStream data)
throws IOException {
return digest(getSha256Digest(), data);
throws IOException {
return digest(getSha256Digest(), data);
}
public static byte[] sha256(String data) {
return sha256(data.getBytes(Charsets.UTF_8));
return sha256(data.getBytes(Charsets.UTF_8));
}
public static String sha256Hex(byte[] data) {
return Hex.encodeHexString(sha256(data));
return Hex.encodeHexString(sha256(data));
}
public static String sha256Hex(InputStream data)
throws IOException {
return Hex.encodeHexString(sha256(data));
throws IOException {
return Hex.encodeHexString(sha256(data));
}
public static String sha256Hex(String data) {
return Hex.encodeHexString(sha256(data));
return Hex.encodeHexString(sha256(data));
}
public static byte[] sha384(byte[] data) {
return getSha384Digest().digest(data);
return getSha384Digest().digest(data);
}
public static byte[] sha384(InputStream data)
throws IOException {
return digest(getSha384Digest(), data);
throws IOException {
return digest(getSha384Digest(), data);
}
public static byte[] sha384(String data) {
return sha384(data.getBytes(Charsets.UTF_8));
return sha384(data.getBytes(Charsets.UTF_8));
}
public static String sha384Hex(byte[] data) {
return Hex.encodeHexString(sha384(data));
return Hex.encodeHexString(sha384(data));
}
public static String sha384Hex(InputStream data)
throws IOException {
return Hex.encodeHexString(sha384(data));
throws IOException {
return Hex.encodeHexString(sha384(data));
}
public static String sha384Hex(String data) {
return Hex.encodeHexString(sha384(data));
return Hex.encodeHexString(sha384(data));
}
public static byte[] sha512(byte[] data) {
return getSha512Digest().digest(data);
return getSha512Digest().digest(data);
}
public static byte[] sha512(InputStream data)
throws IOException {
return digest(getSha512Digest(), data);
throws IOException {
return digest(getSha512Digest(), data);
}
public static byte[] sha512(String data) {
return sha512(data.getBytes(Charsets.UTF_8));
return sha512(data.getBytes(Charsets.UTF_8));
}
public static String sha512Hex(byte[] data) {
return Hex.encodeHexString(sha512(data));
return Hex.encodeHexString(sha512(data));
}
public static String sha512Hex(InputStream data)
throws IOException {
return Hex.encodeHexString(sha512(data));
throws IOException {
return Hex.encodeHexString(sha512(data));
}
public static String sha512Hex(String data) {
return Hex.encodeHexString(sha512(data));
return Hex.encodeHexString(sha512(data));
}
@Deprecated
public static String shaHex(byte[] data) {
return sha1Hex(data);
return sha1Hex(data);
}
@Deprecated
public static String shaHex(InputStream data)
throws IOException {
return sha1Hex(data);
throws IOException {
return sha1Hex(data);
}
@Deprecated
public static String shaHex(String data) {
return sha1Hex(data);
return sha1Hex(data);
}
public static MessageDigest updateDigest(MessageDigest messageDigest, byte[] valueToDigest) {
messageDigest.update(valueToDigest);
return messageDigest;
messageDigest.update(valueToDigest);
return messageDigest;
}
public static MessageDigest updateDigest(MessageDigest digest, InputStream data)
throws IOException {
byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
throws IOException {
byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
while (read > -1) {
digest.update(buffer, 0, read);
read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
}
while (read > -1) {
digest.update(buffer, 0, read);
read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
}
return digest;
return digest;
}
public static MessageDigest updateDigest(MessageDigest messageDigest, String valueToDigest) {
messageDigest.update(valueToDigest.getBytes(Charsets.UTF_8));
return messageDigest;
messageDigest.update(valueToDigest.getBytes(Charsets.UTF_8));
return messageDigest;
}
}

View File

@@ -28,108 +28,106 @@ public class Hex {
private final Charset charset;
public static byte[] decodeHex(char[] data) throws Exception {
int len = data.length;
int len = data.length;
if ((len & 0x1) != 0) {
throw new Exception("Odd number of characters.");
}
if ((len & 0x1) != 0)
throw new Exception("Odd number of characters.");
byte[] out = new byte[len >> 1];
byte[] out = new byte[len >> 1];
int i = 0;
for (int j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f |= toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
int i = 0;
for (int j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f |= toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
return out;
}
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
return encodeHex(data, true);
}
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
int l = data.length;
char[] out = new char[l << 1];
int i = 0;
for (int j = 0; i < l; i++) {
out[(j++)] = toDigits[((0xF0 & data[i]) >>> 4)];
out[(j++)] = toDigits[(0xF & data[i])];
}
return out;
int i = 0;
for (int j = 0; i < l; i++) {
out[(j++)] = toDigits[((0xF0 & data[i]) >>> 4)];
out[(j++)] = toDigits[(0xF & data[i])];
}
return out;
}
public static String encodeHexString(byte[] data) {
return new String(encodeHex(data));
return new String(encodeHex(data));
}
protected static int toDigit(char ch, int index) throws Exception {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
}
return digit;
int digit = Character.digit(ch, 16);
if (digit == -1)
throw new Exception("Illegal hexadecimal character " + ch + " at index " + index);
return digit;
}
public Hex() {
this.charset = DEFAULT_CHARSET;
this.charset = DEFAULT_CHARSET;
}
public Hex(Charset charset) {
this.charset = charset;
this.charset = charset;
}
public Hex(String charsetName) {
this(Charset.forName(charsetName));
this(Charset.forName(charsetName));
}
public byte[] decode(byte[] array) throws Exception {
return decodeHex(new String(array, getCharset()).toCharArray());
return decodeHex(new String(array, getCharset()).toCharArray());
}
public Object decode(Object object) throws Exception {
try {
char[] charArray = (object instanceof String) ? ((String) object).toCharArray() : (char[]) (char[]) object;
return decodeHex(charArray);
} catch (ClassCastException e) {
throw new Exception(e.getMessage(), e);
}
try {
char[] charArray = (object instanceof String) ? ((String) object).toCharArray() : (char[]) (char[]) object;
return decodeHex(charArray);
} catch (ClassCastException e) {
throw new Exception(e.getMessage(), e);
}
}
public byte[] encode(byte[] array) {
return encodeHexString(array).getBytes(getCharset());
return encodeHexString(array).getBytes(getCharset());
}
public Object encode(Object object)
throws Exception {
try {
byte[] byteArray = (object instanceof String) ? ((String) object).getBytes(getCharset()) : (byte[]) (byte[]) object;
throws Exception {
try {
byte[] byteArray = (object instanceof String) ? ((String) object).getBytes(getCharset()) : (byte[]) (byte[]) object;
return encodeHex(byteArray);
} catch (ClassCastException e) {
throw new Exception(e.getMessage(), e);
}
return encodeHex(byteArray);
} catch (ClassCastException e) {
throw new Exception(e.getMessage(), e);
}
}
public Charset getCharset() {
return this.charset;
return this.charset;
}
public String getCharsetName() {
return this.charset.name();
return this.charset.name();
}
@Override
public String toString() {
return super.toString() + "[charsetName=" + this.charset + "]";
return super.toString() + "[charsetName=" + this.charset + "]";
}
}

View File

@@ -26,5 +26,5 @@ public class FalseFunction implements NonFunction<Boolean> {
public Boolean apply() {
return Boolean.FALSE;
}
}

View File

@@ -23,12 +23,13 @@ package org.jackhuang.hellominecraft.utils.functions;
public class TrueFunction implements NonFunction<Boolean> {
public static final TrueFunction instance = new TrueFunction();
private TrueFunction(){}
private TrueFunction() {
}
@Override
public Boolean apply() {
return Boolean.TRUE;
}
}

View File

@@ -43,7 +43,8 @@ public class Compressor {
* 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件
*
* @param sourceDir 源文件夹
* @param zipFile 压缩生成的zip文件路径。
* @param zipFile 压缩生成的zip文件路径。
*
* @throws java.io.IOException 压缩失败或无法读取
*/
public static void zip(File sourceDir, File zipFile) throws IOException {
@@ -64,12 +65,12 @@ public class Compressor {
/**
* 将文件压缩成zip文件
*
* @param source zip文件路径
* @param source zip文件路径
* @param basePath 待压缩文件根目录
* @param zos zip文件的os
* @param zos zip文件的os
*/
private static void zipFile(File source, String basePath,
ZipOutputStream zos) throws IOException {
ZipOutputStream zos) throws IOException {
File[] files;
if (source.isDirectory())
files = source.listFiles();
@@ -83,7 +84,7 @@ public class Compressor {
for (File file : files)
if (file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1)
+ "/";
+ "/";
if (file.getName().toLowerCase().contains("meta-inf"))
continue;
zos.putNextEntry(new ZipEntry(pathName));
@@ -111,8 +112,9 @@ public class Compressor {
* 将文件压缩成zip文件
*
* @param zipFileName zip文件路径
* @param extPlace 待压缩文件根目录
* @param without 带前缀的不解压
* @param extPlace 待压缩文件根目录
* @param without 带前缀的不解压
*
* @throws java.io.IOException 解压失败或无法写入
*/
public static void unzip(File zipFileName, File extPlace, String[] without) throws IOException {
@@ -125,7 +127,8 @@ public class Compressor {
while (e.hasMoreElements()) {
ZipEntry zipEnt = (ZipEntry) e.nextElement();
gbkPath = zipEnt.getName();
if (StrUtils.startsWithOne(without, gbkPath)) continue;
if (StrUtils.startsWithOne(without, gbkPath))
continue;
if (zipEnt.isDirectory()) {
strtemp = strPath + File.separator + gbkPath;
File dir = new File(strtemp);
@@ -160,7 +163,8 @@ public class Compressor {
* 将zip1合并到zip2里面即保留zip2
*
* @param destFile zip1
* @param srcFile zip2
* @param srcFile zip2
*
* @throws java.io.IOException 无法写入或读取
*/
public static void merge(File destFile, File srcFile) throws IOException {

View File

@@ -36,7 +36,7 @@ import org.jackhuang.hellominecraft.utils.NetUtils;
public class FileUtils {
public static void deleteDirectory(File directory)
throws IOException {
throws IOException {
if (!directory.exists())
return;
@@ -71,7 +71,7 @@ public class FileUtils {
}
public static void cleanDirectory(File directory)
throws IOException {
throws IOException {
if (!directory.exists()) {
//String message = directory + " does not exist";
//throw new IllegalArgumentException(message);
@@ -101,7 +101,7 @@ public class FileUtils {
}
public static void forceDelete(File file)
throws IOException {
throws IOException {
if (file.isDirectory())
deleteDirectory(file);
else {
@@ -117,7 +117,7 @@ public class FileUtils {
}
public static boolean isSymlink(File file)
throws IOException {
throws IOException {
if (file == null)
throw new NullPointerException("File must not be null");
if (File.separatorChar == '\\')
@@ -134,22 +134,22 @@ public class FileUtils {
}
public static void copyDirectory(File srcDir, File destDir)
throws IOException {
throws IOException {
copyDirectory(srcDir, destDir, true);
}
public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate)
throws IOException {
throws IOException {
copyDirectory(srcDir, destDir, null, preserveFileDate);
}
public static void copyDirectory(File srcDir, File destDir, FileFilter filter)
throws IOException {
throws IOException {
copyDirectory(srcDir, destDir, filter, true);
}
public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)
throws IOException {
throws IOException {
if (srcDir == null)
throw new NullPointerException("Source must not be null");
if (destDir == null)
@@ -176,7 +176,7 @@ public class FileUtils {
}
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList)
throws IOException {
throws IOException {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles == null)
throw new IOException("Failed to list contents of " + srcDir);
@@ -203,7 +203,7 @@ public class FileUtils {
}
public static String readFileToString(File file)
throws IOException {
throws IOException {
return NetUtils.getStreamContent(IOUtils.openInputStream(file));
}
@@ -217,7 +217,7 @@ public class FileUtils {
}
public static String readFileToString(File file, String charset)
throws IOException {
throws IOException {
return NetUtils.getStreamContent(IOUtils.openInputStream(file), charset);
}
@@ -228,7 +228,7 @@ public class FileUtils {
return "";
}
}
public static void copyFileQuietly(File srcFile, File destFile) {
try {
copyFile(srcFile, destFile);
@@ -238,12 +238,12 @@ public class FileUtils {
}
public static void copyFile(File srcFile, File destFile)
throws IOException {
throws IOException {
copyFile(srcFile, destFile, true);
}
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException {
throws IOException {
if (srcFile == null)
throw new NullPointerException("Source must not be null");
if (destFile == null)
@@ -256,7 +256,7 @@ public class FileUtils {
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
File parentFile = destFile.getParentFile();
if ((parentFile != null)
&& (!parentFile.mkdirs()) && (!parentFile.isDirectory()))
&& (!parentFile.mkdirs()) && (!parentFile.isDirectory()))
throw new IOException("Destination '" + parentFile + "' directory cannot be created");
if ((destFile.exists()) && (!destFile.canWrite()))
@@ -265,7 +265,7 @@ public class FileUtils {
}
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
throws IOException {
throws IOException {
if ((destFile.exists()) && (destFile.isDirectory()))
throw new IOException("Destination '" + destFile + "' exists but is a directory");
@@ -355,38 +355,38 @@ public class FileUtils {
}
public static void write(File file, CharSequence data)
throws IOException {
throws IOException {
write(file, data, "UTF-8", false);
}
public static void write(File file, CharSequence data, boolean append)
throws IOException {
throws IOException {
write(file, data, "UTF-8", append);
}
public static void write(File file, CharSequence data, String encoding)
throws IOException {
throws IOException {
write(file, data, encoding, false);
}
public static void write(File file, CharSequence data, String encoding, boolean append)
throws IOException {
throws IOException {
String str = data == null ? null : data.toString();
writeStringToFile(file, str, encoding, append);
}
public static void writeStringToFile(File file, String data)
throws IOException {
throws IOException {
writeStringToFile(file, data, "UTF-8", false);
}
public static void writeStringToFile(File file, String data, String encoding)
throws IOException {
throws IOException {
writeStringToFile(file, data, encoding, false);
}
public static void writeStringToFile(File file, String data, String encoding, boolean append)
throws IOException {
throws IOException {
OutputStream out = null;
try {
out = openOutputStream(file, append);
@@ -398,7 +398,7 @@ public class FileUtils {
}
public static FileInputStream openInputStream(File file)
throws IOException {
throws IOException {
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory");
@@ -410,12 +410,12 @@ public class FileUtils {
}
public static FileOutputStream openOutputStream(File file)
throws IOException {
throws IOException {
return openOutputStream(file, false);
}
public static FileOutputStream openOutputStream(File file, boolean append)
throws IOException {
throws IOException {
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory");
@@ -424,7 +424,7 @@ public class FileUtils {
} else {
File parent = file.getParentFile();
if ((parent != null)
&& (!parent.mkdirs()) && (!parent.isDirectory()))
&& (!parent.mkdirs()) && (!parent.isDirectory()))
throw new IOException("Directory '" + parent + "' could not be created");
file.createNewFile();
}
@@ -435,9 +435,11 @@ public class FileUtils {
public static File[] searchSuffix(File dir, String suffix) {
ArrayList<File> al = new ArrayList();
File[] files = dir.listFiles();
if (files == null) return new File[0];
if (files == null)
return new File[0];
for (File f : files)
if (f.getName().endsWith(suffix)) al.add(f);
if (f.getName().endsWith(suffix))
al.add(f);
return al.toArray(new File[0]);
}
}

View File

@@ -169,7 +169,7 @@ public class IOUtils {
public static String getJavaDir() {
return getJavaDir(System.getProperty("java.home"));
}
public static String getJavaDir(String home) {
String path = home + File.separatorChar + "bin" + File.separatorChar;
path = addSeparator(path);
@@ -218,19 +218,19 @@ public class IOUtils {
}
public static void write(byte[] data, OutputStream output)
throws IOException {
throws IOException {
if (data != null)
output.write(data);
}
public static void write(String data, OutputStream output, String encoding)
throws IOException {
throws IOException {
if (data != null)
output.write(data.getBytes(encoding));
}
public static FileInputStream openInputStream(File file)
throws IOException {
throws IOException {
if (file.exists()) {
if (file.isDirectory())
throw new IOException("File '" + file + "' exists but is a directory");
@@ -277,29 +277,27 @@ public class IOUtils {
return null;
}
}
public static List<String> readProcessByInputStream(String[] cmd) throws IOException, InterruptedException {
JavaProcess jp = new JavaProcess(cmd, new ProcessBuilder(cmd).start(), null);
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getInputStream()))) {
jp.getRawProcess().waitFor();
String line;
while((line = br.readLine()) != null) {
while ((line = br.readLine()) != null)
lines.add(line);
}
}
return lines;
}
public static List<String> readProcessByErrorStream(String[] cmd) throws IOException, InterruptedException {
JavaProcess jp = new JavaProcess(cmd, new ProcessBuilder(cmd).start(), null);
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(jp.getRawProcess().getErrorStream()))) {
jp.getRawProcess().waitFor();
String line;
while((line = br.readLine()) != null) {
while ((line = br.readLine()) != null)
lines.add(line);
}
}
return lines;
}

View File

@@ -52,7 +52,8 @@ public class Java {
if (obj instanceof Java) {
Java j = (Java) obj;
return (j.getName() == null && this.getName() == null) || ((Java) obj).getName().equals(this.getName());
} else return false;
} else
return false;
}
@Override
@@ -88,8 +89,10 @@ public class Java {
for (String java : javas) {
int s = 0;
for (char c : java.toCharArray())
if (c == '.') s++;
if (s <= 1) continue;
if (c == '.')
s++;
if (s <= 1)
continue;
String javahome = queryRegValue(java, "JavaHome");
if (javahome != null)
ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\".length()), javahome));
@@ -98,8 +101,10 @@ public class Java {
for (String java : javas) {
int s = 0;
for (char c : java.toCharArray())
if (c == '.') s++;
if (s <= 1) continue;
if (c == '.')
s++;
if (s <= 1)
continue;
String javahome = queryRegValue(java, "JavaHome");
if (javahome != null)
ans.add(new Java(java.substring("HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\".length()), javahome));
@@ -111,7 +116,7 @@ public class Java {
}
private static List<String> queryRegSubFolders(String location) throws IOException, InterruptedException {
String[] cmd = new String[]{"cmd", "/c", "reg", "query", location};
String[] cmd = new String[] {"cmd", "/c", "reg", "query", location};
List<String> l = IOUtils.readProcessByInputStream(cmd);
List<String> ans = new ArrayList<>();
for (String line : l)
@@ -121,11 +126,12 @@ public class Java {
}
private static String queryRegValue(String location, String name) throws IOException, InterruptedException {
String[] cmd = new String[]{"cmd", "/c", "reg", "query", location, "/v", name};
String[] cmd = new String[] {"cmd", "/c", "reg", "query", location, "/v", name};
List<String> l = IOUtils.readProcessByInputStream(cmd);
boolean last = false;
for (String s : l) {
if (s.trim().isEmpty()) continue;
if (s.trim().isEmpty())
continue;
if (last == true && s.trim().startsWith(name)) {
int begins = s.indexOf(name);
if (begins > 0) {
@@ -137,7 +143,8 @@ public class Java {
}
}
}
if (s.trim().equals(location)) last = true;
if (s.trim().equals(location))
last = true;
}
return null;
}

View File

@@ -34,7 +34,8 @@ public class JavaProcess {
public JavaProcess(List<String> commands, Process process, ProcessManager pm) {
this.commands = commands;
this.process = process;
if (pm != null) pm.registerProcess(this);
if (pm != null)
pm.registerProcess(this);
}
public JavaProcess(String[] commands, Process process, ProcessManager pm) {

View File

@@ -40,16 +40,16 @@ public class JavaProcessMonitor {
public void start() {
Event<JavaProcess> event = (sender2, t) -> {
if(t.getExitCode() != 0) {
if (t.getExitCode() != 0)
MessageBox.Show(C.i18n("launch.exited_abnormally"));
}
processThreadStopped((ProcessThread) sender2, false);
return true;
};
Event<JavaProcess> event2 = (sender3, p1) -> {
if (p1.getExitCode() != 0 && p1.getStdErrLines().size() > 0 && StrUtils.containsOne(p1.getStdErrLines(), Arrays.asList("Could not create the Java Virtual Machine.",
"Error occurred during initialization of VM",
"A fatal exception has occurred. Program will exit."))) MessageBox.Show(C.i18n("launch.cannot_create_jvm"));
"Error occurred during initialization of VM",
"A fatal exception has occurred. Program will exit.")))
MessageBox.Show(C.i18n("launch.cannot_create_jvm"));
processThreadStopped((ProcessThread) sender3, false);
return true;
};
@@ -71,7 +71,8 @@ public class JavaProcessMonitor {
al.remove(t);
al.removeAll(CollectionUtils.sortOut(al, t1 -> !t1.isAlive()));
if (al.isEmpty() || forceTermintate) {
for (Thread a : al) a.interrupt();
for (Thread a : al)
a.interrupt();
al.clear();
stoppedEvent.execute(p);
}

View File

@@ -55,9 +55,10 @@ public final class JdkVersion {
@Override
public boolean equals(Object obj) {
if (!(obj instanceof JdkVersion)) return false;
if (!(obj instanceof JdkVersion))
return false;
JdkVersion b = (JdkVersion) obj;
if(b.location == null || location == null)
if (b.location == null || location == null)
return b.location == location;
return new File(b.location).equals(new File(location));
}
@@ -69,7 +70,8 @@ public final class JdkVersion {
public JdkVersion(String location) {
File f = new File(location);
if (f.exists() && f.isFile()) f = f.getParentFile();
if (f.exists() && f.isFile())
f = f.getParentFile();
this.location = f.getAbsolutePath();
}
@@ -110,12 +112,17 @@ public final class JdkVersion {
}
private static int parseVersion(String javaVersion) {
if (StrUtils.isBlank(javaVersion)) return UNKOWN;
if (StrUtils.isBlank(javaVersion))
return UNKOWN;
int a = UNKOWN;
if (javaVersion.contains("1.9.")) a = JAVA_19;
else if (javaVersion.contains("1.8.")) a = JAVA_18;
else if (javaVersion.contains("1.7.")) a = JAVA_17;
else if (javaVersion.contains("1.6.")) a = JAVA_16;
if (javaVersion.contains("1.9."))
a = JAVA_19;
else if (javaVersion.contains("1.8."))
a = JAVA_18;
else if (javaVersion.contains("1.7."))
a = JAVA_17;
else if (javaVersion.contains("1.6."))
a = JAVA_16;
return a;
}
@@ -124,6 +131,7 @@ public final class JdkVersion {
* <code>System.getProperty("java.version")</code>.
*
* @return the full Java version string
*
* @see System#getProperty(String)
*/
public static String getJavaVersion() {
@@ -138,6 +146,7 @@ public final class JdkVersion {
* rn a code comparable to the JAVA_XX codes in this class
*
* @return
*
* @see #JAVA_13
* @see #JAVA_14
* @see #JAVA_15
@@ -156,11 +165,11 @@ public final class JdkVersion {
private static final Pattern p = Pattern.compile("java version \"[1-9]*\\.[1-9]*\\.[0-9]*(.*?)\"");
public static JdkVersion getJavaVersionFromExecutable(String file) throws IOException {
String[] str = new String[]{file, "-version"};
String[] str = new String[] {file, "-version"};
Platform platform = Platform.BIT_32;
String ver = null;
try {
for(String line : IOUtils.readProcessByErrorStream(str)) {
for (String line : IOUtils.readProcessByErrorStream(str)) {
Matcher m = p.matcher(line);
if (m.find()) {
ver = m.group();

View File

@@ -85,9 +85,10 @@ public class MessageBox {
/**
* Show MsgBox with title and options
*
* @param Msg The Message
* @param Title The title of MsgBox.
* @param Msg The Message
* @param Title The title of MsgBox.
* @param Option The type of MsgBox.
*
* @return user operation.
*/
public static int Show(String Msg, String Title, int Option) {
@@ -105,8 +106,9 @@ public class MessageBox {
/**
* Show MsgBox with options
*
* @param Msg The Message
* @param Msg The Message
* @param Option The type of MsgBox.
*
* @return User Operation
*/
public static int Show(String Msg, int Option) {
@@ -117,6 +119,7 @@ public class MessageBox {
* Show Default MsgBox
*
* @param Msg The Message
*
* @return User Operation
*/
public static int Show(String Msg) {

View File

@@ -41,7 +41,7 @@ public enum OS {
public static OS os() {
String str;
if ((str = System.getProperty("os.name").toLowerCase())
.contains("win"))
.contains("win"))
return OS.WINDOWS;
if (str.contains("mac"))
return OS.OSX;

View File

@@ -24,28 +24,28 @@ public enum Platform {
UNKNOWN {
@Override
public String getBit() {
return "unknown";
}
@Override
public String getBit() {
return "unknown";
}
},
},
BIT_32 {
@Override
public String getBit() {
return "32";
}
@Override
public String getBit() {
return "32";
}
},
},
BIT_64 {
@Override
public String getBit() {
return "64";
}
@Override
public String getBit() {
return "64";
}
};
};
public abstract String getBit();

View File

@@ -56,8 +56,8 @@ public class ProcessThread extends Thread {
HMCLog.warn("Unsupported encoding: " + System.getProperty("sun.jnu.encoding", "UTF-8"), ex);
br = new InputStreamReader(in);
}
}
else br = null;
} else
br = null;
int ch;
String line = "";

View File

@@ -21,7 +21,7 @@ package org.jackhuang.hellominecraft.version;
* @author huangyuhui
*/
public class MinecraftRemoteLatestVersion {
public String snapshot, release;
}

View File

@@ -24,7 +24,7 @@ import org.jackhuang.hellominecraft.C;
public class MinecraftVersionRequest {
public static final int Unkown = 0, Invaild = 1, InvaildJar = 2,
Modified = 3, OK = 4, NotFound = 5, NotReadable = 6, NotAFile = 7;
Modified = 3, OK = 4, NotFound = 5, NotReadable = 6, NotAFile = 7;
public int type;
public String version;

View File

@@ -27,7 +27,7 @@ import java.awt.image.Raster;
import java.awt.image.WritableRaster;
public abstract class AbstractFilter
implements BufferedImageOp {
implements BufferedImageOp {
@Override
public abstract BufferedImage filter(BufferedImage paramBufferedImage1, BufferedImage paramBufferedImage2);

View File

@@ -23,12 +23,12 @@ import java.awt.Color;
* @author huangyuhui
*/
public class BasicColors {
private static Color getWebColor(String c){
private static Color getWebColor(String c) {
return new Color(
Integer.parseInt(c.substring(0,2),16),
Integer.parseInt(c.substring(2,4),16),
Integer.parseInt(c.substring(4,6),16)
Integer.parseInt(c.substring(0, 2), 16),
Integer.parseInt(c.substring(2, 4), 16),
Integer.parseInt(c.substring(4, 6), 16)
);
}
@@ -39,7 +39,7 @@ public class BasicColors {
public static final Color COLOR_BLUE_DARKER = new Color(12, 94, 145);
public static final Color COLOR_WHITE_TEXT = new Color(254, 254, 254);
public static final Color COLOR_CENTRAL_BACK = new Color(25, 30, 34, 160);
public static final Color bgcolors[] = new Color[] {
COLOR_BLUE,
getWebColor("1ABC9C"),

View File

@@ -27,9 +27,8 @@ public class FastBlurFilter extends AbstractFilter {
}
public FastBlurFilter(int radius) {
if (radius < 1) {
if (radius < 1)
radius = 1;
}
this.radius = radius;
}
@@ -43,9 +42,8 @@ public class FastBlurFilter extends AbstractFilter {
int width = src.getWidth();
int height = src.getHeight();
if (dst == null) {
if (dst == null)
dst = createCompatibleDestImage(src, null);
}
int[] srcPixels = new int[width * height];
int[] dstPixels = new int[width * height];
@@ -68,22 +66,18 @@ public class FastBlurFilter extends AbstractFilter {
int srcIndex = 0;
int[] sumLookupTable = new int[256 * windowSize];
for (int i = 0; i < sumLookupTable.length; i++) {
for (int i = 0; i < sumLookupTable.length; i++)
sumLookupTable[i] = (i / windowSize);
}
int[] indexLookupTable = new int[radiusPlusOne];
if (radius < width) {
for (int i = 0; i < indexLookupTable.length; i++) {
if (radius < width)
for (int i = 0; i < indexLookupTable.length; i++)
indexLookupTable[i] = i;
}
} else {
for (int i = 0; i < width; i++) {
else {
for (int i = 0; i < width; i++)
indexLookupTable[i] = i;
}
for (int i = width; i < indexLookupTable.length; i++) {
for (int i = width; i < indexLookupTable.length; i++)
indexLookupTable[i] = (width - 1);
}
}
for (int y = 0; y < height; y++) {
@@ -113,14 +107,12 @@ public class FastBlurFilter extends AbstractFilter {
dstIndex += height;
int nextPixelIndex = x + radiusPlusOne;
if (nextPixelIndex >= width) {
if (nextPixelIndex >= width)
nextPixelIndex = width - 1;
}
int previousPixelIndex = x - radius;
if (previousPixelIndex < 0) {
if (previousPixelIndex < 0)
previousPixelIndex = 0;
}
int nextPixel = srcPixels[(srcIndex + nextPixelIndex)];
int previousPixel = srcPixels[(srcIndex + previousPixelIndex)];

View File

@@ -238,11 +238,11 @@ public class LogWindow extends javax.swing.JFrame {
public void log(String status) {
log(status, Level.INFO);
}
public void warning(String status) {
log(status, Level.WARN);
}
public void log(String status, Level c) {
status = status.replace("\t", " ");
Document d = txtLog.getStyledDocument();

View File

@@ -32,9 +32,9 @@ public class Selector extends javax.swing.JDialog {
public static int failedToSel = -1;
/**
* @param parent null
* @param parent null
* @param selList Selection List
* @param msg Message
* @param msg Message
*/
public Selector(java.awt.Frame parent, String[] selList, String msg) {
super(parent, true);

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -16,6 +15,7 @@ import org.tukaani.xz.simple.ARM;
* BCJ filter for little endian ARM instructions.
*/
public class ARMOptions extends BCJOptions {
private static final int ALIGNMENT = 4;
public ARMOptions() {

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -16,6 +15,7 @@ import org.tukaani.xz.simple.ARMThumb;
* BCJ filter for little endian ARM-Thumb instructions.
*/
public class ARMThumbOptions extends BCJOptions {
private static final int ALIGNMENT = 2;
public ARMThumbOptions() {

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
abstract class BCJCoder implements FilterCoder {
public static final long X86_FILTER_ID = 0x04;
public static final long POWERPC_FILTER_ID = 0x05;
public static final long IA64_FILTER_ID = 0x06;

View File

@@ -6,33 +6,32 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
import org.tukaani.xz.simple.*;
class BCJDecoder extends BCJCoder implements FilterDecoder {
private final long filterID;
private final int startOffset;
BCJDecoder(long filterID, byte[] props)
throws UnsupportedOptionsException {
throws UnsupportedOptionsException {
assert isBCJFilterID(filterID);
this.filterID = filterID;
if (props.length == 0) {
if (props.length == 0)
startOffset = 0;
} else if (props.length == 4) {
else if (props.length == 4) {
int n = 0;
for (int i = 0; i < 4; ++i)
n |= (props[i] & 0xFF) << (i * 8);
startOffset = n;
} else {
} else
throw new UnsupportedOptionsException(
"Unsupported BCJ filter properties");
}
"Unsupported BCJ filter properties");
}
public int getMemoryUsage() {

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
class BCJEncoder extends BCJCoder implements FilterEncoder {
private final BCJOptions options;
private final long filterID;
private final byte[] props;
@@ -18,16 +18,16 @@ class BCJEncoder extends BCJCoder implements FilterEncoder {
assert isBCJFilterID(filterID);
int startOffset = options.getStartOffset();
if (startOffset == 0) {
if (startOffset == 0)
props = new byte[0];
} else {
else {
props = new byte[4];
for (int i = 0; i < 4; ++i)
props[i] = (byte)(startOffset >>> (i * 8));
props[i] = (byte) (startOffset >>> (i * 8));
}
this.filterID = filterID;
this.options = (BCJOptions)options.clone();
this.options = (BCJOptions) options.clone();
}
public long getFilterID() {

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
abstract class BCJOptions extends FilterOptions {
private final int alignment;
int startOffset = 0;
@@ -23,10 +23,10 @@ abstract class BCJOptions extends FilterOptions {
* The default value is <code>0</code>.
*/
public void setStartOffset(int startOffset)
throws UnsupportedOptionsException {
throws UnsupportedOptionsException {
if ((startOffset & (alignment - 1)) != 0)
throw new UnsupportedOptionsException(
"Start offset must be a multiple of " + alignment);
"Start offset must be a multiple of " + alignment);
this.startOffset = startOffset;
}

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -18,6 +17,7 @@ import org.tukaani.xz.common.DecoderUtil;
import org.tukaani.xz.check.Check;
class BlockInputStream extends InputStream {
private final DataInputStream inData;
private final CountingInputStream inCounted;
private InputStream filterChain;
@@ -35,7 +35,7 @@ class BlockInputStream extends InputStream {
public BlockInputStream(InputStream in, Check check, int memoryLimit,
long unpaddedSizeInIndex,
long uncompressedSizeInIndex)
throws IOException, IndexIndicatorException {
throws IOException, IndexIndicatorException {
this.check = check;
inData = new DataInputStream(in);
@@ -59,7 +59,7 @@ class BlockInputStream extends InputStream {
// Check for reserved bits in Block Flags.
if ((buf[1] & 0x3C) != 0)
throw new UnsupportedOptionsException(
"Unsupported options in XZ Block Header");
"Unsupported options in XZ Block Header");
// Memory for the Filter Flags field
int filterCount = (buf[1] & 0x03) + 1;
@@ -69,7 +69,7 @@ class BlockInputStream extends InputStream {
// Use a stream to parse the fields after the Block Flags field.
// Exclude the CRC32 field at the end.
ByteArrayInputStream bufStream = new ByteArrayInputStream(
buf, 2, headerSize - 6);
buf, 2, headerSize - 6);
try {
// Set the maximum valid compressed size. This is overriden
@@ -83,7 +83,7 @@ class BlockInputStream extends InputStream {
compressedSizeInHeader = DecoderUtil.decodeVLI(bufStream);
if (compressedSizeInHeader == 0
|| compressedSizeInHeader > compressedSizeLimit)
|| compressedSizeInHeader > compressedSizeLimit)
throw new CorruptedInputException();
compressedSizeLimit = compressedSizeInHeader;
@@ -102,7 +102,7 @@ class BlockInputStream extends InputStream {
if (filterPropsSize > bufStream.available())
throw new CorruptedInputException();
filterProps[i] = new byte[(int)filterPropsSize];
filterProps[i] = new byte[(int) filterPropsSize];
bufStream.read(filterProps[i]);
}
@@ -114,7 +114,7 @@ class BlockInputStream extends InputStream {
for (int i = bufStream.available(); i > 0; --i)
if (bufStream.read() != 0x00)
throw new UnsupportedOptionsException(
"Unsupported options in XZ Block Header");
"Unsupported options in XZ Block Header");
// Validate the Blcok Header against the Index when doing
// random access reading.
@@ -125,26 +125,26 @@ class BlockInputStream extends InputStream {
int headerAndCheckSize = headerSize + check.getSize();
if (headerAndCheckSize >= unpaddedSizeInIndex)
throw new CorruptedInputException(
"XZ Index does not match a Block Header");
"XZ Index does not match a Block Header");
// The compressed size calculated from Unpadded Size must
// match the value stored in the Compressed Size field in
// the Block Header.
long compressedSizeFromIndex
= unpaddedSizeInIndex - headerAndCheckSize;
= unpaddedSizeInIndex - headerAndCheckSize;
if (compressedSizeFromIndex > compressedSizeLimit
|| (compressedSizeInHeader != -1
&& compressedSizeInHeader != compressedSizeFromIndex))
|| (compressedSizeInHeader != -1
&& compressedSizeInHeader != compressedSizeFromIndex))
throw new CorruptedInputException(
"XZ Index does not match a Block Header");
"XZ Index does not match a Block Header");
// The uncompressed size stored in the Index must match
// the value stored in the Uncompressed Size field in
// the Block Header.
if (uncompressedSizeInHeader != -1
&& uncompressedSizeInHeader != uncompressedSizeInIndex)
&& uncompressedSizeInHeader != uncompressedSizeInIndex)
throw new CorruptedInputException(
"XZ Index does not match a Block Header");
"XZ Index does not match a Block Header");
// For further validation, pretend that the values from the Index
// were stored in the Block Header.
@@ -158,7 +158,7 @@ class BlockInputStream extends InputStream {
// supported by this decoder implementation.
FilterDecoder[] filters = new FilterDecoder[filterIDs.length];
for (int i = 0; i < filters.length; ++i) {
for (int i = 0; i < filters.length; ++i)
if (filterIDs[i] == LZMA2Coder.FILTER_ID)
filters[i] = new LZMA2Decoder(filterProps[i]);
@@ -170,8 +170,7 @@ class BlockInputStream extends InputStream {
else
throw new UnsupportedOptionsException(
"Unknown Filter ID " + filterIDs[i]);
}
"Unknown Filter ID " + filterIDs[i]);
RawCoder.validate(filters);
@@ -214,10 +213,10 @@ class BlockInputStream extends InputStream {
// Catch invalid values.
long compressedSize = inCounted.getSize();
if (compressedSize < 0
|| compressedSize > compressedSizeLimit
|| uncompressedSize < 0
|| (uncompressedSizeInHeader != -1
&& uncompressedSize > uncompressedSizeInHeader))
|| compressedSize > compressedSizeLimit
|| uncompressedSize < 0
|| (uncompressedSizeInHeader != -1
&& uncompressedSize > uncompressedSizeInHeader))
throw new CorruptedInputException();
// Check the Block integrity as soon as possible:
@@ -248,9 +247,9 @@ class BlockInputStream extends InputStream {
// Validate Compressed Size and Uncompressed Size if they were
// present in Block Header.
if ((compressedSizeInHeader != -1
&& compressedSizeInHeader != compressedSize)
|| (uncompressedSizeInHeader != -1
&& uncompressedSizeInHeader != uncompressedSize))
&& compressedSizeInHeader != compressedSize)
|| (uncompressedSizeInHeader != -1
&& uncompressedSizeInHeader != uncompressedSize))
throw new CorruptedInputException();
// Block Padding bytes must be zeros.
@@ -263,7 +262,7 @@ class BlockInputStream extends InputStream {
inData.readFully(storedCheck);
if (!Arrays.equals(check.finish(), storedCheck))
throw new CorruptedInputException("Integrity check ("
+ check.getName() + ") does not match");
+ check.getName() + ") does not match");
}
public int available() throws IOException {

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.OutputStream;
@@ -16,6 +15,7 @@ import org.tukaani.xz.common.EncoderUtil;
import org.tukaani.xz.check.Check;
class BlockOutputStream extends FinishableOutputStream {
private final OutputStream out;
private final CountingOutputStream outCounted;
private FinishableOutputStream filterChain;
@@ -72,7 +72,7 @@ class BlockOutputStream extends FinishableOutputStream {
throw new UnsupportedOptionsException();
// Block Header Size
buf[0] = (byte)(buf.length / 4);
buf[0] = (byte) (buf.length / 4);
// Write the Block Header field to the output stream.
out.write(buf);
@@ -85,7 +85,7 @@ class BlockOutputStream extends FinishableOutputStream {
}
public void write(int b) throws IOException {
tempBuf[0] = (byte)b;
tempBuf[0] = (byte) b;
write(tempBuf, 0, 1);
}
@@ -120,7 +120,7 @@ class BlockOutputStream extends FinishableOutputStream {
// It is very hard to trigger this exception.
// This is just to be pedantic.
if (compressedSize < 0 || compressedSize > compressedSizeLimit
|| uncompressedSize < 0)
|| uncompressedSize < 0)
throw new XZIOException("XZ Stream has grown too big");
}

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
/**
@@ -15,6 +14,7 @@ package org.tukaani.xz;
* already read from the input stream was corrupt too.
*/
public class CorruptedInputException extends XZIOException {
private static final long serialVersionUID = 3L;
/**
@@ -29,7 +29,7 @@ public class CorruptedInputException extends XZIOException {
* Creates a new CorruptedInputException with
* the specified error detail message.
*
* @param s error detail message
* @param s error detail message
*/
public CorruptedInputException(String s) {
super(s);

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.FilterInputStream;
@@ -17,6 +16,7 @@ import java.io.IOException;
* Counts the number of bytes read from an input stream.
*/
class CountingInputStream extends FilterInputStream {
private long size = 0;
public CountingInputStream(InputStream in) {

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.OutputStream;
@@ -21,6 +20,7 @@ import java.io.IOException;
* using this as the output stream for a chain of raw filters.
*/
class CountingOutputStream extends FinishableOutputStream {
private final OutputStream out;
private long size = 0;

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
abstract class DeltaCoder implements FilterCoder {
public static final long FILTER_ID = 0x03;
public boolean changesSize() {

View File

@@ -6,18 +6,18 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
class DeltaDecoder extends DeltaCoder implements FilterDecoder {
private final int distance;
DeltaDecoder(byte[] props) throws UnsupportedOptionsException {
if (props.length != 1)
throw new UnsupportedOptionsException(
"Unsupported Delta filter properties");
"Unsupported Delta filter properties");
distance = (props[0] & 0xFF) + 1;
}

View File

@@ -6,16 +6,16 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
class DeltaEncoder extends DeltaCoder implements FilterEncoder {
private final DeltaOptions options;
private final byte[] props = new byte[1];
DeltaEncoder(DeltaOptions options) {
props[0] = (byte)(options.getDistance() - 1);
this.options = (DeltaOptions)options.clone();
props[0] = (byte) (options.getDistance() - 1);
this.options = (DeltaOptions) options.clone();
}
public long getFilterID() {

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -21,6 +20,7 @@ import org.tukaani.xz.delta.DeltaDecoder;
* its input stream indicates end of input.
*/
public class DeltaInputStream extends InputStream {
/**
* Smallest supported delta calculation distance.
*/
@@ -41,12 +41,12 @@ public class DeltaInputStream extends InputStream {
/**
* Creates a new Delta decoder with the given delta calculation distance.
*
* @param in input stream from which Delta filtered data
* is read
* @param in input stream from which Delta filtered data
* is read
*
* @param distance delta calculation distance, must be in the
* range [<code>DISTANCE_MIN</code>,
* <code>DISTANCE_MAX</code>]
* @param distance delta calculation distance, must be in the
* range [<code>DISTANCE_MIN</code>,
* <code>DISTANCE_MAX</code>]
*/
public DeltaInputStream(InputStream in, int distance) {
// Check for null because otherwise null isn't detect
@@ -61,10 +61,10 @@ public class DeltaInputStream extends InputStream {
/**
* Decode the next byte from this input stream.
*
* @return the next decoded byte, or <code>-1</code> to indicate
* the end of input on the input stream <code>in</code>
* @return the next decoded byte, or <code>-1</code> to indicate
* the end of input on the input stream <code>in</code>
*
* @throws IOException may be thrown by <code>in</code>
* @throws IOException may be thrown by <code>in</code>
*/
public int read() throws IOException {
return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF);
@@ -76,17 +76,17 @@ public class DeltaInputStream extends InputStream {
* This calls <code>in.read(buf, off, len)</code> and defilters the
* returned data.
*
* @param buf target buffer for decoded data
* @param off start offset in <code>buf</code>
* @param len maximum number of bytes to read
* @param buf target buffer for decoded data
* @param off start offset in <code>buf</code>
* @param len maximum number of bytes to read
*
* @return number of bytes read, or <code>-1</code> to indicate
* the end of the input stream <code>in</code>
* @return number of bytes read, or <code>-1</code> to indicate
* the end of the input stream <code>in</code>
*
* @throws XZIOException if the stream has been closed
* @throws XZIOException if the stream has been closed
*
* @throws IOException may be thrown by underlaying input
* stream <code>in</code>
* @throws IOException may be thrown by underlaying input
* stream <code>in</code>
*/
public int read(byte[] buf, int off, int len) throws IOException {
if (len == 0)
@@ -116,7 +116,7 @@ public class DeltaInputStream extends InputStream {
/**
* Calls <code>in.available()</code>.
*
* @return the value returned by <code>in.available()</code>
* @return the value returned by <code>in.available()</code>
*/
public int available() throws IOException {
if (in == null)
@@ -132,15 +132,14 @@ public class DeltaInputStream extends InputStream {
* Closes the stream and calls <code>in.close()</code>.
* If the stream was already closed, this does nothing.
*
* @throws IOException if thrown by <code>in.close()</code>
* @throws IOException if thrown by <code>in.close()</code>
*/
public void close() throws IOException {
if (in != null) {
if (in != null)
try {
in.close();
} finally {
in = null;
}
}
}
}

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -27,6 +26,7 @@ import java.io.InputStream;
* FLAC will give much smaller result at much better compression speed.
*/
public class DeltaOptions extends FilterOptions {
/**
* Smallest supported delta calculation distance.
*/
@@ -42,7 +42,8 @@ public class DeltaOptions extends FilterOptions {
/**
* Creates new Delta options and sets the delta distance to 1 byte.
*/
public DeltaOptions() {}
public DeltaOptions() {
}
/**
* Creates new Delta options and sets the distance to the given value.
@@ -58,8 +59,8 @@ public class DeltaOptions extends FilterOptions {
public void setDistance(int distance) throws UnsupportedOptionsException {
if (distance < DISTANCE_MIN || distance > DISTANCE_MAX)
throw new UnsupportedOptionsException(
"Delta distance must be in the range [" + DISTANCE_MIN
+ ", " + DISTANCE_MAX + "]: " + distance);
"Delta distance must be in the range [" + DISTANCE_MIN
+ ", " + DISTANCE_MAX + "]: " + distance);
this.distance = distance;
}

View File

@@ -6,13 +6,13 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.IOException;
import org.tukaani.xz.delta.DeltaEncoder;
class DeltaOutputStream extends FinishableOutputStream {
private static final int FILTER_BUF_SIZE = 4096;
private FinishableOutputStream out;
@@ -34,7 +34,7 @@ class DeltaOutputStream extends FinishableOutputStream {
}
public void write(int b) throws IOException {
tempBuf[0] = (byte)b;
tempBuf[0] = (byte) b;
write(tempBuf, 0, 1);
}

View File

@@ -6,11 +6,13 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
interface FilterCoder {
boolean changesSize();
boolean nonLastOK();
boolean lastOK();
}

View File

@@ -6,12 +6,13 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
interface FilterDecoder extends FilterCoder {
int getMemoryUsage();
InputStream getInputStream(InputStream in);
}

View File

@@ -6,12 +6,15 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
interface FilterEncoder extends FilterCoder {
long getFilterID();
byte[] getFilterProps();
boolean supportsFlushing();
FinishableOutputStream getOutputStream(FinishableOutputStream out);
}

View File

@@ -7,7 +7,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -17,6 +16,7 @@ import java.io.IOException;
* Base class for filter-specific options classes.
*/
public abstract class FilterOptions implements Cloneable {
/**
* Gets how much memory the encoder will need with
* the given filter chain. This function simply calls
@@ -60,7 +60,7 @@ public abstract class FilterOptions implements Cloneable {
* to XZOutputStream.
*/
public abstract FinishableOutputStream getOutputStream(
FinishableOutputStream out);
FinishableOutputStream out);
/**
* Gets how much memory the decoder will need to decompress the data
@@ -72,9 +72,10 @@ public abstract class FilterOptions implements Cloneable {
* Gets a raw (no XZ headers) decoder input stream using these options.
*/
public abstract InputStream getInputStream(InputStream in)
throws IOException;
throws IOException;
abstract FilterEncoder getFilterEncoder();
FilterOptions() {}
FilterOptions() {
}
}

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.OutputStream;
@@ -17,6 +16,7 @@ import java.io.IOException;
* the underlying stream.
*/
public abstract class FinishableOutputStream extends OutputStream {
/**
* Finish the stream without closing the underlying stream.
* No more data may be written to the stream after finishing.
@@ -25,7 +25,9 @@ public abstract class FinishableOutputStream extends OutputStream {
* does nothing. Subclasses should override it if they need finishing
* support, which is the case, for example, with compressors.
*
* @throws IOException
* @throws IOException
*/
public void finish() throws IOException {};
public void finish() throws IOException {
}
;
}

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.OutputStream;
@@ -18,6 +17,7 @@ import java.io.IOException;
* people will never need this.
*/
public class FinishableWrapperOutputStream extends FinishableOutputStream {
/**
* The {@link java.io.OutputStream OutputStream} that has been
* wrapped into a FinishableWrapperOutputStream.
@@ -48,7 +48,7 @@ public class FinishableWrapperOutputStream extends FinishableOutputStream {
/**
* Calls {@link java.io.OutputStream#write(byte[],int,int)
out.write(buf, off, len)}.
* out.write(buf, off, len)}.
*/
public void write(byte[] buf, int off, int len) throws IOException {
out.write(buf, off, len);

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -16,6 +15,7 @@ import org.tukaani.xz.simple.IA64;
* BCJ filter for Itanium (IA-64) instructions.
*/
public class IA64Options extends BCJOptions {
private static final int ALIGNMENT = 16;
public IA64Options() {

View File

@@ -6,9 +6,9 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
class IndexIndicatorException extends Exception {
private static final long serialVersionUID = 1L;
}

View File

@@ -6,10 +6,10 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
abstract class LZMA2Coder implements FilterCoder {
public static final long FILTER_ID = 0x21;
public boolean changesSize() {

View File

@@ -6,12 +6,12 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
class LZMA2Decoder extends LZMA2Coder implements FilterDecoder {
private int dictSize;
LZMA2Decoder(byte[] props) throws UnsupportedOptionsException {
@@ -19,7 +19,7 @@ class LZMA2Decoder extends LZMA2Coder implements FilterDecoder {
// are too big for int.
if (props.length != 1 || (props[0] & 0xFF) > 37)
throw new UnsupportedOptionsException(
"Unsupported LZMA2 properties");
"Unsupported LZMA2 properties");
dictSize = 2 | (props[0] & 1);
dictSize <<= (props[0] >>> 1) + 11;

View File

@@ -6,30 +6,30 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import org.tukaani.xz.lzma.LZMAEncoder;
class LZMA2Encoder extends LZMA2Coder implements FilterEncoder {
private final LZMA2Options options;
private final byte[] props = new byte[1];
LZMA2Encoder(LZMA2Options options) {
if (options.getPresetDict() != null)
throw new IllegalArgumentException(
"XZ doesn't support a preset dictionary for now");
"XZ doesn't support a preset dictionary for now");
if (options.getMode() == LZMA2Options.MODE_UNCOMPRESSED) {
props[0] = (byte)0;
} else {
if (options.getMode() == LZMA2Options.MODE_UNCOMPRESSED)
props[0] = (byte) 0;
else {
int d = Math.max(options.getDictSize(),
LZMA2Options.DICT_SIZE_MIN);
props[0] = (byte)(LZMAEncoder.getDistSlot(d - 1) - 23);
props[0] = (byte) (LZMAEncoder.getDistSlot(d - 1) - 23);
}
// Make a private copy so that the caller is free to change its copy.
this.options = (LZMA2Options)options.clone();
this.options = (LZMA2Options) options.clone();
}
public long getFilterID() {

View File

@@ -7,7 +7,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -21,6 +20,7 @@ import org.tukaani.xz.lzma.LZMADecoder;
* Decompresses a raw LZMA2 stream (no XZ headers).
*/
public class LZMA2InputStream extends InputStream {
/**
* Smallest valid LZMA2 dictionary size.
* <p>
@@ -47,7 +47,7 @@ public class LZMA2InputStream extends InputStream {
private final LZDecoder lz;
private final RangeDecoderFromBuffer rc
= new RangeDecoderFromBuffer(COMPRESSED_SIZE_MAX);
= new RangeDecoderFromBuffer(COMPRESSED_SIZE_MAX);
private LZMADecoder lzma;
private int uncompressedSize = 0;
@@ -65,11 +65,11 @@ public class LZMA2InputStream extends InputStream {
* Gets approximate decompressor memory requirements as kibibytes for
* the given dictionary size.
*
* @param dictSize LZMA2 dictionary size as bytes, must be
* in the range [<code>DICT_SIZE_MIN</code>,
* <code>DICT_SIZE_MAX</code>]
* @param dictSize LZMA2 dictionary size as bytes, must be
* in the range [<code>DICT_SIZE_MIN</code>,
* <code>DICT_SIZE_MAX</code>]
*
* @return approximate memory requirements as kibibytes (KiB)
* @return approximate memory requirements as kibibytes (KiB)
*/
public static int getMemoryUsage(int dictSize) {
// The base state is around 30-40 KiB (probabilities etc.),
@@ -81,7 +81,7 @@ public class LZMA2InputStream extends InputStream {
private static int getDictSize(int dictSize) {
if (dictSize < DICT_SIZE_MIN || dictSize > DICT_SIZE_MAX)
throw new IllegalArgumentException(
"Unsupported dictionary size " + dictSize);
"Unsupported dictionary size " + dictSize);
// Round dictionary size upward to a multiple of 16. This way LZMA
// can use LZDecoder.getPos() for calculating LZMA's posMask.
@@ -106,12 +106,12 @@ public class LZMA2InputStream extends InputStream {
* was used when compressing. If you know the uncompressed size
* of the data, this might allow saving some memory.
*
* @param in input stream from which LZMA2-compressed
* data is read
* @param in input stream from which LZMA2-compressed
* data is read
*
* @param dictSize LZMA2 dictionary size as bytes, must be
* in the range [<code>DICT_SIZE_MIN</code>,
* <code>DICT_SIZE_MAX</code>]
* @param dictSize LZMA2 dictionary size as bytes, must be
* in the range [<code>DICT_SIZE_MIN</code>,
* <code>DICT_SIZE_MAX</code>]
*/
public LZMA2InputStream(InputStream in, int dictSize) {
this(in, dictSize, null);
@@ -125,15 +125,15 @@ public class LZMA2InputStream extends InputStream {
* If a preset dictionary was used when compressing the data, the
* same preset dictionary must be provided when decompressing.
*
* @param in input stream from which LZMA2-compressed
* data is read
* @param in input stream from which LZMA2-compressed
* data is read
*
* @param dictSize LZMA2 dictionary size as bytes, must be
* in the range [<code>DICT_SIZE_MIN</code>,
* <code>DICT_SIZE_MAX</code>]
* @param dictSize LZMA2 dictionary size as bytes, must be
* in the range [<code>DICT_SIZE_MIN</code>,
* <code>DICT_SIZE_MAX</code>]
*
* @param presetDict preset dictionary or <code>null</code>
* to use no preset dictionary
* @param presetDict preset dictionary or <code>null</code>
* to use no preset dictionary
*/
public LZMA2InputStream(InputStream in, int dictSize, byte[] presetDict) {
// Check for null because otherwise null isn't detect
@@ -155,17 +155,17 @@ public class LZMA2InputStream extends InputStream {
* may be inefficient. Wrap it in <code>java.io.BufferedInputStream</code>
* if you need to read lots of data one byte at a time.
*
* @return the next decompressed byte, or <code>-1</code>
* to indicate the end of the compressed stream
* @return the next decompressed byte, or <code>-1</code>
* to indicate the end of the compressed stream
*
* @throws CorruptedInputException
* @throws CorruptedInputException
*
* @throws XZIOException if the stream has been closed
* @throws XZIOException if the stream has been closed
*
* @throws EOFException
* compressed input is truncated or corrupt
* @throws EOFException
* compressed input is truncated or corrupt
*
* @throws IOException may be thrown by <code>in</code>
* @throws IOException may be thrown by <code>in</code>
*/
public int read() throws IOException {
return read(tempBuf, 0, 1) == -1 ? -1 : (tempBuf[0] & 0xFF);
@@ -179,21 +179,21 @@ public class LZMA2InputStream extends InputStream {
* bytes have been decompressed, the end of the LZMA2 stream is reached,
* or an exception is thrown.
*
* @param buf target buffer for uncompressed data
* @param off start offset in <code>buf</code>
* @param len maximum number of uncompressed bytes to read
* @param buf target buffer for uncompressed data
* @param off start offset in <code>buf</code>
* @param len maximum number of uncompressed bytes to read
*
* @return number of bytes read, or <code>-1</code> to indicate
* the end of the compressed stream
* @return number of bytes read, or <code>-1</code> to indicate
* the end of the compressed stream
*
* @throws CorruptedInputException
* @throws CorruptedInputException
*
* @throws XZIOException if the stream has been closed
* @throws XZIOException if the stream has been closed
*
* @throws EOFException
* compressed input is truncated or corrupt
* @throws EOFException
* compressed input is truncated or corrupt
*
* @throws IOException may be thrown by <code>in</code>
* @throws IOException may be thrown by <code>in</code>
*/
public int read(byte[] buf, int off, int len) throws IOException {
if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length)
@@ -223,9 +223,9 @@ public class LZMA2InputStream extends InputStream {
int copySizeMax = Math.min(uncompressedSize, len);
if (!isLZMAChunk) {
if (!isLZMAChunk)
lz.copyUncompressed(in, copySizeMax);
} else {
else {
lz.setLimit(copySizeMax);
lzma.decode();
if (!rc.isInBufferOK())
@@ -263,9 +263,8 @@ public class LZMA2InputStream extends InputStream {
needProps = true;
needDictReset = false;
lz.reset();
} else if (needDictReset) {
} else if (needDictReset)
throw new CorruptedInputException();
}
if (control >= 0x80) {
isLZMAChunk = true;
@@ -279,19 +278,16 @@ public class LZMA2InputStream extends InputStream {
needProps = false;
decodeProps();
} else if (needProps) {
} else if (needProps)
throw new CorruptedInputException();
} else if (control >= 0xA0) {
else if (control >= 0xA0)
lzma.reset();
}
rc.prepareInputBuffer(in, compressedSize);
} else if (control > 0x02) {
} else if (control > 0x02)
throw new CorruptedInputException();
} else {
else {
isLZMAChunk = false;
uncompressedSize = in.readUnsignedShort() + 1;
}
@@ -327,8 +323,8 @@ public class LZMA2InputStream extends InputStream {
* will then be the number of uncompressed bytes remaining from that
* chunk.
*
* @return the number of uncompressed bytes that can be read
* without blocking
* @return the number of uncompressed bytes that can be read
* without blocking
*/
public int available() throws IOException {
if (in == null)
@@ -344,15 +340,14 @@ public class LZMA2InputStream extends InputStream {
* Closes the stream and calls <code>in.close()</code>.
* If the stream was already closed, this does nothing.
*
* @throws IOException if thrown by <code>in.close()</code>
* @throws IOException if thrown by <code>in.close()</code>
*/
public void close() throws IOException {
if (in != null) {
if (in != null)
try {
in.close();
} finally {
in = null;
}
}
}
}

View File

@@ -6,7 +6,6 @@
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
package org.tukaani.xz;
import java.io.InputStream;
@@ -22,6 +21,7 @@ import org.tukaani.xz.lzma.LZMAEncoder;
* <code>LZMA2Options(int)</code>.
*/
public class LZMA2Options extends FilterOptions {
/**
* Minimum valid compression preset level is 0.
*/
@@ -124,10 +124,10 @@ public class LZMA2Options extends FilterOptions {
public static final int MF_BT4 = LZEncoder.MF_BT4;
private static final int[] presetToDictSize = {
1 << 18, 1 << 20, 1 << 21, 1 << 22, 1 << 22,
1 << 23, 1 << 23, 1 << 24, 1 << 25, 1 << 26 };
1 << 18, 1 << 20, 1 << 21, 1 << 22, 1 << 22,
1 << 23, 1 << 23, 1 << 24, 1 << 25, 1 << 26};
private static final int[] presetToDepthLimit = { 4, 8, 24, 48 };
private static final int[] presetToDepthLimit = {4, 8, 24, 48};
private int dictSize;
private byte[] presetDict = null;
@@ -155,8 +155,8 @@ public class LZMA2Options extends FilterOptions {
/**
* Creates new LZMA2 options and sets them to the given preset.
*
* @throws UnsupportedOptionsException
* <code>preset</code> is not supported
* @throws UnsupportedOptionsException
* <code>preset</code> is not supported
*/
public LZMA2Options(int preset) throws UnsupportedOptionsException {
setPreset(preset);
@@ -165,12 +165,12 @@ public class LZMA2Options extends FilterOptions {
/**
* Creates new LZMA2 options and sets them to the given custom values.
*
* @throws UnsupportedOptionsException
* unsupported options were specified
* @throws UnsupportedOptionsException
* unsupported options were specified
*/
public LZMA2Options(int dictSize, int lc, int lp, int pb, int mode,
int niceLen, int mf, int depthLimit)
throws UnsupportedOptionsException {
throws UnsupportedOptionsException {
setDictSize(dictSize);
setLcLp(lc, lp);
setPb(pb);
@@ -193,13 +193,13 @@ public class LZMA2Options extends FilterOptions {
* 16&nbsp;MiB, or 32&nbsp;MiB, it is waste of memory to use the
* presets 7, 8, or 9, respectively.
*
* @throws UnsupportedOptionsException
* <code>preset</code> is not supported
* @throws UnsupportedOptionsException
* <code>preset</code> is not supported
*/
public void setPreset(int preset) throws UnsupportedOptionsException {
if (preset < 0 || preset > 9)
throw new UnsupportedOptionsException(
"Unsupported preset: " + preset);
"Unsupported preset: " + preset);
lc = LC_DEFAULT;
lp = LP_DEFAULT;
@@ -231,19 +231,19 @@ public class LZMA2Options extends FilterOptions {
* but sizes of 2^n and 2^n&nbsp;+&nbsp;2^(n-1) bytes are somewhat
* recommended.
*
* @throws UnsupportedOptionsException
* <code>dictSize</code> is not supported
* @throws UnsupportedOptionsException
* <code>dictSize</code> is not supported
*/
public void setDictSize(int dictSize) throws UnsupportedOptionsException {
if (dictSize < DICT_SIZE_MIN)
throw new UnsupportedOptionsException(
"LZMA2 dictionary size must be at least 4 KiB: "
+ dictSize + " B");
"LZMA2 dictionary size must be at least 4 KiB: "
+ dictSize + " B");
if (dictSize > DICT_SIZE_MAX)
throw new UnsupportedOptionsException(
"LZMA2 dictionary size must not exceed "
+ (DICT_SIZE_MAX >> 20) + " MiB: " + dictSize + " B");
"LZMA2 dictionary size must not exceed "
+ (DICT_SIZE_MAX >> 20) + " MiB: " + dictSize + " B");
this.dictSize = dictSize;
}
@@ -287,16 +287,16 @@ public class LZMA2Options extends FilterOptions {
* Trying to exceed it will throw an exception. This function lets
* you change both at the same time.
*
* @throws UnsupportedOptionsException
* <code>lc</code> and <code>lp</code>
* are invalid
* @throws UnsupportedOptionsException
* <code>lc</code> and <code>lp</code>
* are invalid
*/
public void setLcLp(int lc, int lp) throws UnsupportedOptionsException {
if (lc < 0 || lp < 0 || lc > LC_LP_MAX || lp > LC_LP_MAX
|| lc + lp > LC_LP_MAX)
|| lc + lp > LC_LP_MAX)
throw new UnsupportedOptionsException(
"lc + lp must not exceed " + LC_LP_MAX + ": "
+ lc + " + " + lp);
"lc + lp must not exceed " + LC_LP_MAX + ": "
+ lc + " + " + lp);
this.lc = lc;
this.lp = lp;
@@ -316,17 +316,17 @@ public class LZMA2Options extends FilterOptions {
* followed by another lower-case letter. In the US-ASCII character set,
* the highest three bits are 010 for upper-case letters and 011 for
* lower-case letters. When <code>lc</code> is at least 3, the literal
* coding can take advantage of this property in the uncompressed data.
* coding can take advantage of this property in the uncompressed data.
* <p>
* The default value (3) is usually good. If you want maximum compression,
* try <code>setLc(4)</code>. Sometimes it helps a little, and sometimes it
* makes compression worse. If it makes it worse, test for example
* <code>setLc(2)</code> too.
*
* @throws UnsupportedOptionsException
* <code>lc</code> is invalid, or the sum
* of <code>lc</code> and <code>lp</code>
* exceed LC_LP_MAX
* @throws UnsupportedOptionsException
* <code>lc</code> is invalid, or the sum
* of <code>lc</code> and <code>lp</code>
* exceed LC_LP_MAX
*/
public void setLc(int lc) throws UnsupportedOptionsException {
setLcLp(lc, lp);
@@ -339,10 +339,10 @@ public class LZMA2Options extends FilterOptions {
* assumed when encoding literals. See {@link #setPb(int) setPb} for
* more information about alignment.
*
* @throws UnsupportedOptionsException
* <code>lp</code> is invalid, or the sum
* of <code>lc</code> and <code>lp</code>
* exceed LC_LP_MAX
* @throws UnsupportedOptionsException
* <code>lp</code> is invalid, or the sum
* of <code>lc</code> and <code>lp</code>
* exceed LC_LP_MAX
*/
public void setLp(int lp) throws UnsupportedOptionsException {
setLcLp(lc, lp);
@@ -383,13 +383,13 @@ public class LZMA2Options extends FilterOptions {
* 16-byte alignment. It might be worth taking into account when designing
* file formats that are likely to be often compressed with LZMA2.
*
* @throws UnsupportedOptionsException
* <code>pb</code> is invalid
* @throws UnsupportedOptionsException
* <code>pb</code> is invalid
*/
public void setPb(int pb) throws UnsupportedOptionsException {
if (pb < 0 || pb > PB_MAX)
throw new UnsupportedOptionsException(
"pb must not exceed " + PB_MAX + ": " + pb);
"pb must not exceed " + PB_MAX + ": " + pb);
this.pb = pb;
}
@@ -416,13 +416,13 @@ public class LZMA2Options extends FilterOptions {
* compress the data at all (and doesn't use a match finder) and will
* simply wrap it in uncompressed LZMA2 chunks.
*
* @throws UnsupportedOptionsException
* <code>mode</code> is not supported
* @throws UnsupportedOptionsException
* <code>mode</code> is not supported
*/
public void setMode(int mode) throws UnsupportedOptionsException {
if (mode < MODE_UNCOMPRESSED || mode > MODE_NORMAL)
throw new UnsupportedOptionsException(
"Unsupported compression mode: " + mode);
"Unsupported compression mode: " + mode);
this.mode = mode;
}
@@ -441,19 +441,19 @@ public class LZMA2Options extends FilterOptions {
* to give better compression at the expense of speed. The default
* depends on the preset.
*
* @throws UnsupportedOptionsException
* <code>niceLen</code> is invalid
* @throws UnsupportedOptionsException
* <code>niceLen</code> is invalid
*/
public void setNiceLen(int niceLen) throws UnsupportedOptionsException {
if (niceLen < NICE_LEN_MIN)
throw new UnsupportedOptionsException(
"Minimum nice length of matches is "
+ NICE_LEN_MIN + " bytes: " + niceLen);
"Minimum nice length of matches is "
+ NICE_LEN_MIN + " bytes: " + niceLen);
if (niceLen > NICE_LEN_MAX)
throw new UnsupportedOptionsException(
"Maximum nice length of matches is " + NICE_LEN_MAX
+ ": " + niceLen);
"Maximum nice length of matches is " + NICE_LEN_MAX
+ ": " + niceLen);
this.niceLen = niceLen;
}
@@ -473,13 +473,13 @@ public class LZMA2Options extends FilterOptions {
* than Binary Tree match finders. The default depends on the preset:
* 0-3 use <code>MF_HC4</code> and 4-9 use <code>MF_BT4</code>.
*
* @throws UnsupportedOptionsException
* <code>mf</code> is not supported
* @throws UnsupportedOptionsException
* <code>mf</code> is not supported
*/
public void setMatchFinder(int mf) throws UnsupportedOptionsException {
if (mf != MF_HC4 && mf != MF_BT4)
throw new UnsupportedOptionsException(
"Unsupported match finder: " + mf);
"Unsupported match finder: " + mf);
this.mf = mf;
}
@@ -504,14 +504,14 @@ public class LZMA2Options extends FilterOptions {
* higher than 1000 unless you are prepared to interrupt the compression
* in case it is taking far too long.
*
* @throws UnsupportedOptionsException
* <code>depthLimit</code> is invalid
* @throws UnsupportedOptionsException
* <code>depthLimit</code> is invalid
*/
public void setDepthLimit(int depthLimit)
throws UnsupportedOptionsException {
throws UnsupportedOptionsException {
if (depthLimit < 0)
throw new UnsupportedOptionsException(
"Depth limit cannot be negative: " + depthLimit);
"Depth limit cannot be negative: " + depthLimit);
this.depthLimit = depthLimit;
}

Some files were not shown because too many files have changed in this diff Show More