Updated license info. Code cleanup

This commit is contained in:
nathan 2015-07-20 16:45:40 +02:00
parent 19409170a4
commit bf9a83c2e2
59 changed files with 1643 additions and 825 deletions

View File

@ -15,22 +15,20 @@
*/ */
package dorkbox.util; package dorkbox.util;
import java.lang.reflect.Array; import java.lang.reflect.*;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
public class ClassHelper { public
class ClassHelper {
/** /**
* Retrieves the generic type parameter for the PARENT (super) class of the specified class. This ONLY works * Retrieves the generic type parameter for the PARENT (super) class of the specified class. This ONLY works
* on parent classes because of how type erasure works in java! * on parent classes because of how type erasure works in java!
* *
* @param clazz class to get the parameter from * @param clazz class to get the parameter from
* @param genericParameterToGet 0-based index of parameter as class to get * @param genericParameterToGet 0-based index of parameter as class to get
*/ */
public final static Class<?> getGenericParameterAsClassForSuperClass(Class<?> clazz, int genericParameterToGet) { public static
Class<?> getGenericParameterAsClassForSuperClass(Class<?> clazz, int genericParameterToGet) {
Class<?> classToCheck = clazz; Class<?> classToCheck = clazz;
// case of multiple inheritance, we are trying to get the first available generic info // case of multiple inheritance, we are trying to get the first available generic info
@ -44,7 +42,8 @@ public class ClassHelper {
if (actualTypeArguments.length > genericParameterToGet) { if (actualTypeArguments.length > genericParameterToGet) {
Class<?> rawTypeAsClass = ClassHelper.getRawTypeAsClass(actualTypeArguments[genericParameterToGet]); Class<?> rawTypeAsClass = ClassHelper.getRawTypeAsClass(actualTypeArguments[genericParameterToGet]);
return rawTypeAsClass; return rawTypeAsClass;
} else { }
else {
// record the parameters. // record the parameters.
} }
@ -68,7 +67,8 @@ public class ClassHelper {
if (actualTypeArguments.length > genericParameterToGet) { if (actualTypeArguments.length > genericParameterToGet) {
Class<?> rawTypeAsClass = ClassHelper.getRawTypeAsClass(actualTypeArguments[genericParameterToGet]); Class<?> rawTypeAsClass = ClassHelper.getRawTypeAsClass(actualTypeArguments[genericParameterToGet]);
return rawTypeAsClass; return rawTypeAsClass;
} else { }
else {
// record the parameters. // record the parameters.
} }
@ -88,34 +88,39 @@ public class ClassHelper {
/** /**
* Return the class that is this type. * Return the class that is this type.
*/ */
public final static Class<?> getRawTypeAsClass(Type type) { public static
Class<?> getRawTypeAsClass(Type type) {
if (type instanceof Class) { if (type instanceof Class) {
Class<?> class1 = (Class<?>)type; Class<?> class1 = (Class<?>) type;
// if (class1.isArray()) { // if (class1.isArray()) {
// System.err.println("CLASS IS ARRAY TYPE: SHOULD WE DO ANYTHING WITH IT? " + class1.getSimpleName()); // System.err.println("CLASS IS ARRAY TYPE: SHOULD WE DO ANYTHING WITH IT? " + class1.getSimpleName());
// return class1.getComponentType(); // return class1.getComponentType();
// } else { // } else {
return class1; return class1;
// } // }
} else if (type instanceof GenericArrayType) { }
else if (type instanceof GenericArrayType) {
// note: cannot have primitive types here, only objects that are arrays (byte[], Integer[], etc) // note: cannot have primitive types here, only objects that are arrays (byte[], Integer[], etc)
Type type2 = ((GenericArrayType) type).getGenericComponentType(); Type type2 = ((GenericArrayType) type).getGenericComponentType();
Class<?> rawType = getRawTypeAsClass(type2); Class<?> rawType = getRawTypeAsClass(type2);
return Array.newInstance(rawType, 0).getClass(); return Array.newInstance(rawType, 0)
} else if (type instanceof ParameterizedType) { .getClass();
}
else if (type instanceof ParameterizedType) {
// we cannot use parameterized types, because java can't go between classes and ptypes - and this // we cannot use parameterized types, because java can't go between classes and ptypes - and this
// going "in-between" is the magic -- and value -- of this entire infrastructure. // going "in-between" is the magic -- and value -- of this entire infrastructure.
// return the type. // return the type.
return (Class<?>) ((ParameterizedType) type).getRawType(); return (Class<?>) ((ParameterizedType) type).getRawType();
// Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments(); // Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
// return (Class<?>) actualTypeArguments[0]; // return (Class<?>) actualTypeArguments[0];
} else if (type instanceof TypeVariable) { }
else if (type instanceof TypeVariable) {
// we have a COMPLEX type parameter // we have a COMPLEX type parameter
Type[] bounds = ((TypeVariable<?>)type).getBounds(); Type[] bounds = ((TypeVariable<?>) type).getBounds();
if (bounds.length > 0) { if (bounds.length > 0) {
return getRawTypeAsClass(bounds[0]); return getRawTypeAsClass(bounds[0]);
} }
@ -126,10 +131,11 @@ public class ClassHelper {
/** /**
* Check to see if clazz or interface directly has one of the interfaces defined by clazzItMustHave * Check to see if clazz or interface directly has one of the interfaces defined by clazzItMustHave
* <p> * <p/>
* If the class DOES NOT directly have the interface it will fail. the PARENT class is not checked. * If the class DOES NOT directly have the interface it will fail. the PARENT class is not checked.
*/ */
public final static boolean hasInterface(Class<?> clazzItMustHave, Class<?> clazz) { public static
boolean hasInterface(Class<?> clazzItMustHave, Class<?> clazz) {
if (clazzItMustHave == clazz) { if (clazzItMustHave == clazz) {
return true; return true;
} }
@ -151,10 +157,12 @@ public class ClassHelper {
/** /**
* Checks to see if the clazz is a subclass of a parent class. * Checks to see if the clazz is a subclass of a parent class.
*
* @param baseClass * @param baseClass
* @param genericClass * @param genericClass
*/ */
public static boolean hasParentClass(Class<?> parentClazz, Class<?> clazz) { public static
boolean hasParentClass(Class<?> parentClazz, Class<?> clazz) {
Class<?> superClass = clazz.getSuperclass(); Class<?> superClass = clazz.getSuperclass();
if (parentClazz == superClass) { if (parentClazz == superClass) {
return true; return true;

View File

@ -18,17 +18,61 @@ package dorkbox.util;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.AbstractQueuedSynchronizer;
public class CountingLatch { public
class CountingLatch {
private final Sync sync;
public
CountingLatch() {
this.sync = new Sync();
}
public
CountingLatch(final int initialCount) {
this.sync = new Sync(initialCount);
}
public
void increment() {
this.sync.releaseShared(1);
}
public
int getCount() {
return this.sync.getCount();
}
public
void decrement() {
this.sync.releaseShared(-1);
}
public
void await() throws InterruptedException {
this.sync.acquireSharedInterruptibly(1);
}
public
boolean await(final long timeout) throws InterruptedException {
return this.sync.tryAcquireSharedNanos(1, TimeUnit.MILLISECONDS.toNanos(timeout));
}
/** /**
* Synchronization control for CountingLatch. Uses AQS state to represent * Synchronization control for CountingLatch. Uses AQS state to represent
* count. * count.
*/ */
private static final class Sync extends AbstractQueuedSynchronizer { private static final
class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Sync() {} private
Sync() {
}
private Sync(final int initialState) { private
Sync(final int initialState) {
setState(initialState); setState(initialState);
} }
@ -37,14 +81,16 @@ public class CountingLatch {
} }
@Override @Override
protected int tryAcquireShared(final int acquires) { protected
int tryAcquireShared(final int acquires) {
return getState() == 0 ? 1 : -1; return getState() == 0 ? 1 : -1;
} }
@Override @Override
protected boolean tryReleaseShared(final int delta) { protected
boolean tryReleaseShared(final int delta) {
// Decrement count; signal when transition to zero // Decrement count; signal when transition to zero
for (;;) { for (; ; ) {
final int c = getState(); final int c = getState();
final int nextc = c + delta; final int nextc = c + delta;
if (nextc < 0) { if (nextc < 0) {
@ -56,34 +102,4 @@ public class CountingLatch {
} }
} }
} }
}
private final Sync sync;
public CountingLatch() {
this.sync = new Sync();
}
public CountingLatch(final int initialCount) {
this.sync = new Sync(initialCount);
}
public void increment() {
this.sync.releaseShared(1);
}
public int getCount() {
return this.sync.getCount();
}
public void decrement() {
this.sync.releaseShared(-1);
}
public void await() throws InterruptedException {
this.sync.acquireSharedInterruptibly(1);
}
public boolean await(final long timeout) throws InterruptedException {
return this.sync.tryAcquireSharedNanos(1, TimeUnit.MILLISECONDS.toNanos(timeout));
}
}

View File

@ -18,29 +18,28 @@ package dorkbox.util;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
public class DelayTimer { public
public interface Callback { class DelayTimer {
public void execute();
}
private final String name; private final String name;
private final boolean isDaemon; private final boolean isDaemon;
private final Callback listener; private final Callback listener;
private Timer timer; private Timer timer;
private long delay; private long delay;
public DelayTimer(Callback listener) { public
DelayTimer(Callback listener) {
this(null, true, listener); this(null, true, listener);
} }
/** /**
* Sometimes you want to make sure that this timer will complete, even if the calling thread has terminated. * Sometimes you want to make sure that this timer will complete, even if the calling thread has terminated.
* @param name the name of the thread (if you want to specify one) *
* @param name the name of the thread (if you want to specify one)
* @param isDaemon true if you want this timer to be run on a daemon thread * @param isDaemon true if you want this timer to be run on a daemon thread
* @param listener the callback listener to execute * @param listener the callback listener to execute
*/ */
public DelayTimer(String name, boolean isDaemon, Callback listener) { public
DelayTimer(String name, boolean isDaemon, Callback listener) {
this.name = name; this.name = name;
this.listener = listener; this.listener = listener;
this.isDaemon = isDaemon; this.isDaemon = isDaemon;
@ -49,14 +48,16 @@ public class DelayTimer {
/** /**
* @return true if this timer is still waiting to run. * @return true if this timer is still waiting to run.
*/ */
public synchronized boolean isWaiting() { public synchronized
boolean isWaiting() {
return this.timer != null; return this.timer != null;
} }
/** /**
* Cancel the delay timer! * Cancel the delay timer!
*/ */
public synchronized void cancel() { public synchronized
void cancel() {
if (this.timer != null) { if (this.timer != null) {
this.timer.cancel(); this.timer.cancel();
this.timer.purge(); this.timer.purge();
@ -67,32 +68,43 @@ public class DelayTimer {
/** /**
* @param delay milliseconds to wait * @param delay milliseconds to wait
*/ */
public synchronized void delay(long delay) { public synchronized
void delay(long delay) {
this.delay = delay; this.delay = delay;
cancel(); cancel();
if (delay > 0) { if (delay > 0) {
if (this.name != null) { if (this.name != null) {
this.timer = new Timer(this.name, this.isDaemon); this.timer = new Timer(this.name, this.isDaemon);
} else { }
else {
this.timer = new Timer(this.isDaemon); this.timer = new Timer(this.isDaemon);
} }
TimerTask t = new TimerTask() { TimerTask t = new TimerTask() {
@Override @Override
public void run() { public
void run() {
DelayTimer.this.listener.execute(); DelayTimer.this.listener.execute();
DelayTimer.this.cancel(); DelayTimer.this.cancel();
} }
}; };
this.timer.schedule(t, delay); this.timer.schedule(t, delay);
} else { }
else {
this.listener.execute(); this.listener.execute();
this.timer = null; this.timer = null;
} }
} }
public synchronized long getDelay() { public synchronized
long getDelay() {
return this.delay; return this.delay;
} }
public
interface Callback {
public
void execute();
}
} }

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util; package dorkbox.util;
import dorkbox.util.messagebus.IMessageBus; import dorkbox.util.messagebus.IMessageBus;
@ -19,11 +34,13 @@ class MBus {
IPublicationErrorHandler ExceptionCounter = new IPublicationErrorHandler() { IPublicationErrorHandler ExceptionCounter = new IPublicationErrorHandler() {
@Override @Override
public void handleError(PublicationError error) { public
void handleError(PublicationError error) {
logger.error(error.toString()); logger.error(error.toString());
if (error.getCause() != null) { if (error.getCause() != null) {
error.getCause().printStackTrace(); error.getCause()
.printStackTrace();
} }
} }
@ -31,11 +48,15 @@ class MBus {
public public
void handleError(final String error, final Class<?> listenerClass) { void handleError(final String error, final Class<?> listenerClass) {
// Printout the error itself // Printout the error itself
logger.error(new StringBuilder().append(error).append(": ").append(listenerClass.getSimpleName()).toString()); logger.error(new StringBuilder().append(error)
.append(": ")
.append(listenerClass.getSimpleName())
.toString());
} }
}; };
messageBus.getErrorHandler().addErrorHandler(ExceptionCounter); messageBus.getErrorHandler()
.addErrorHandler(ExceptionCounter);
messageBus.start(); messageBus.start();
bus = messageBus; bus = messageBus;

View File

@ -1,11 +1,11 @@
/******************************************************************************* /*
* Copyright 2011 See AUTHORS file. * Copyright 2010 dorkbox, llc
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -14,64 +14,73 @@
* limitations under the License. * limitations under the License.
*/ */
// pruned/limited version from libGDX, modified by dorkbox, llc
package dorkbox.util; package dorkbox.util;
public class MathUtils { @SuppressWarnings("unused")
public
class MathUtils {
// --- // ---
private static ThreadLocal<MersenneTwisterFast> random = new ThreadLocal<MersenneTwisterFast>(); private static final ThreadLocal<MersenneTwisterFast> random = new ThreadLocal<MersenneTwisterFast>();
/** /**
* Creates the thread local MersenneTwister (as it's not thread safe), if necessary * Creates the thread local MersenneTwister (as it's not thread safe), if necessary
*/ */
public static MersenneTwisterFast random() { public static
MersenneTwisterFast random() {
MersenneTwisterFast mersenneTwisterFast = random.get(); MersenneTwisterFast mersenneTwisterFast = random.get();
if (mersenneTwisterFast == null) { if (mersenneTwisterFast == null) {
mersenneTwisterFast = new MersenneTwisterFast(); mersenneTwisterFast = new MersenneTwisterFast();
random.set(mersenneTwisterFast); random.set(mersenneTwisterFast);
return mersenneTwisterFast; return mersenneTwisterFast;
} else { }
else {
return mersenneTwisterFast; return mersenneTwisterFast;
} }
} }
/** Returns a random integer */ /** Returns a random integer */
static public final int randomInt () { public static
int randomInt() {
return random().nextInt(); return random().nextInt();
} }
/** Returns a random number between 0 (inclusive) and the specified value (inclusive). */ /** Returns a random number between 0 (inclusive) and the specified value (inclusive). */
static public final int randomInt (int range) { public static
int randomInt(int range) {
return random().nextInt(range + 1); return random().nextInt(range + 1);
} }
/** Returns a random number between start (inclusive) and end (inclusive). */ /** Returns a random number between start (inclusive) and end (inclusive). */
static public final int randomInt (int start, int end) { public static
int randomInt(int start, int end) {
return start + random().nextInt(end - start + 1); return start + random().nextInt(end - start + 1);
} }
/** Returns a random boolean value. */ /** Returns a random boolean value. */
static public final boolean randomBoolean () { public static
boolean randomBoolean() {
return random().nextBoolean(); return random().nextBoolean();
} }
/** Returns random number between 0.0 (inclusive) and 1.0 (exclusive). */ /** Returns random number between 0.0 (inclusive) and 1.0 (exclusive). */
static public final float randomFloat () { public static
float randomFloat() {
return random().nextFloat(); return random().nextFloat();
} }
/** Returns a random number between 0 (inclusive) and the specified value (exclusive). */ /** Returns a random number between 0 (inclusive) and the specified value (exclusive). */
static public final float randomFloat (float range) { public static
float randomFloat(float range) {
return random().nextFloat() * range; return random().nextFloat() * range;
} }
/** Returns a random number between start (inclusive) and end (exclusive). */ /** Returns a random number between start (inclusive) and end (exclusive). */
static public final float randomFloat (float start, float end) { public static
float randomFloat(float start, float end) {
return start + random().nextFloat() * (end - start); return start + random().nextFloat() * (end - start);
} }
@ -79,26 +88,15 @@ public class MathUtils {
/** /**
* Returns the next power of two. Returns the specified value if the value * Returns the next power of two. Returns the specified value if the value is already a power of two.
* is already a power of two.
*/ */
public static int nextPowerOfTwo(int value) { public static
if (value == 0) { int nextPowerOfTwo(int value) {
return 1; return 1 << (32 - Integer.numberOfLeadingZeros(value - 1));
}
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
return value + 1;
} }
public static boolean isPowerOfTwo(int value) { public static
boolean isPowerOfTwo(int value) {
return value != 0 && (value & value - 1) == 0; return value != 0 && (value & value - 1) == 0;
} }
} }

View File

@ -1,3 +1,18 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util; package dorkbox.util;
import java.io.Serializable; import java.io.Serializable;

View File

@ -21,17 +21,18 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* The default thread factory with names. * The default thread factory with names.
*/ */
public class NamedThreadFactory implements ThreadFactory { public
class NamedThreadFactory implements ThreadFactory {
private static final AtomicInteger poolId = new AtomicInteger(); private static final AtomicInteger poolId = new AtomicInteger();
// permit this to be changed! // permit this to be changed!
/** /**
* The stack size is arbitrary based on JVM implementation. Default is 0 * The stack size is arbitrary based on JVM implementation. Default is 0
* 8k is the size of the android stack. Depending on the version of android, this can either change, or will always be 8k * 8k is the size of the android stack. Depending on the version of android, this can either change, or will always be 8k
*<p> * <p/>
* To be honest, 8k is pretty reasonable for an asynchronous/event based system (32bit) or 16k (64bit) * To be honest, 8k is pretty reasonable for an asynchronous/event based system (32bit) or 16k (64bit)
* Setting the size MAY or MAY NOT have any effect!!! * Setting the size MAY or MAY NOT have any effect!!!
* <p> * <p/>
* Stack size must be specified in bytes. Default is 8k * Stack size must be specified in bytes. Default is 8k
*/ */
public static int stackSizeForThreads = 8192; public static int stackSizeForThreads = 8192;
@ -39,56 +40,72 @@ public class NamedThreadFactory implements ThreadFactory {
private final AtomicInteger nextId = new AtomicInteger(); private final AtomicInteger nextId = new AtomicInteger();
private final ThreadGroup group; private final ThreadGroup group;
private final String namePrefix; private final String namePrefix;
private final int threadPriority; private final int threadPriority;
private final boolean daemon; private final boolean daemon;
/** /**
* Creates a DAEMON thread * Creates a DAEMON thread
*/ */
public NamedThreadFactory(String poolNamePrefix) { public
this(poolNamePrefix, Thread.currentThread().getThreadGroup(), Thread.MAX_PRIORITY, true); NamedThreadFactory(String poolNamePrefix) {
this(poolNamePrefix,
Thread.currentThread()
.getThreadGroup(),
Thread.MAX_PRIORITY,
true);
} }
public NamedThreadFactory(String poolNamePrefix, boolean isDaemon) { public
this(poolNamePrefix, Thread.currentThread().getThreadGroup(), Thread.MAX_PRIORITY, isDaemon); NamedThreadFactory(String poolNamePrefix, boolean isDaemon) {
this(poolNamePrefix,
Thread.currentThread()
.getThreadGroup(),
Thread.MAX_PRIORITY,
isDaemon);
} }
/** /**
* Creates a DAEMON thread * Creates a DAEMON thread
*/ */
public NamedThreadFactory(String poolNamePrefix, ThreadGroup group) { public
NamedThreadFactory(String poolNamePrefix, ThreadGroup group) {
this(poolNamePrefix, group, Thread.MAX_PRIORITY, true); this(poolNamePrefix, group, Thread.MAX_PRIORITY, true);
} }
public NamedThreadFactory(String poolNamePrefix, ThreadGroup group, boolean isDaemon) { public
NamedThreadFactory(String poolNamePrefix, ThreadGroup group, boolean isDaemon) {
this(poolNamePrefix, group, Thread.MAX_PRIORITY, isDaemon); this(poolNamePrefix, group, Thread.MAX_PRIORITY, isDaemon);
} }
/** /**
* Creates a DAEMON thread * Creates a DAEMON thread
*/ */
public NamedThreadFactory(String poolNamePrefix, int threadPriority) { public
this(poolNamePrefix, threadPriority, true); NamedThreadFactory(String poolNamePrefix, int threadPriority) {
this(poolNamePrefix, threadPriority, true);
} }
public NamedThreadFactory(String poolNamePrefix, int threadPriority, boolean isDaemon) { public
NamedThreadFactory(String poolNamePrefix, int threadPriority, boolean isDaemon) {
this(poolNamePrefix, null, threadPriority, isDaemon); this(poolNamePrefix, null, threadPriority, isDaemon);
} }
/** /**
*
* @param poolNamePrefix what you want the subsequent threads to be named. * @param poolNamePrefix what you want the subsequent threads to be named.
* @param group the group this thread will belong to. If NULL, it will belong to the current thread group. * @param group the group this thread will belong to. If NULL, it will belong to the current thread group.
* @param threadPriority Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, Thread.MAX_PRIORITY * @param threadPriority Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, Thread.MAX_PRIORITY
*/ */
public NamedThreadFactory(String poolNamePrefix, ThreadGroup group, int threadPriority, boolean isDaemon) { public
NamedThreadFactory(String poolNamePrefix, ThreadGroup group, int threadPriority, boolean isDaemon) {
this.daemon = isDaemon; this.daemon = isDaemon;
this.namePrefix = poolNamePrefix + '-' + poolId.incrementAndGet(); this.namePrefix = poolNamePrefix + '-' + poolId.incrementAndGet();
if (group == null) { if (group == null) {
this.group = Thread.currentThread().getThreadGroup(); this.group = Thread.currentThread()
} else { .getThreadGroup();
}
else {
this.group = group; this.group = group;
} }
@ -99,16 +116,17 @@ public class NamedThreadFactory implements ThreadFactory {
} }
@Override @Override
public Thread newThread(Runnable r) { public
Thread newThread(Runnable r) {
// stack size is arbitrary based on JVM implementation. Default is 0 // stack size is arbitrary based on JVM implementation. Default is 0
// 8k is the size of the android stack. Depending on the version of android, this can either change, or will always be 8k // 8k is the size of the android stack. Depending on the version of android, this can either change, or will always be 8k
// To be honest, 8k is pretty reasonable for an asynchronous/event based system (32bit) or 16k (64bit) // To be honest, 8k is pretty reasonable for an asynchronous/event based system (32bit) or 16k (64bit)
// Setting the size MAY or MAY NOT have any effect!!! // Setting the size MAY or MAY NOT have any effect!!!
Thread t = new Thread(this.group, r, this.namePrefix + '-' + this.nextId.incrementAndGet(), stackSizeForThreads); Thread t = new Thread(this.group, r, this.namePrefix + '-' + this.nextId.incrementAndGet(), stackSizeForThreads);
t.setDaemon(this.daemon); t.setDaemon(this.daemon);
if (t.getPriority() != this.threadPriority) { if (t.getPriority() != this.threadPriority) {
t.setPriority(this.threadPriority); t.setPriority(this.threadPriority);
} }
return t; return t;
} }
} }

View File

@ -1,3 +1,18 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util; package dorkbox.util;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
@ -7,13 +22,9 @@ import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.io.Output;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
/**
*
*/
public public
interface SerializationManager { interface SerializationManager {
/** /**
* Registers the class using the lowest, next available integer ID and the * Registers the class using the lowest, next available integer ID and the
* {@link Kryo#getDefaultSerializer(Class) default serializer}. If the class * {@link Kryo#getDefaultSerializer(Class) default serializer}. If the class

View File

@ -15,46 +15,48 @@
*/ */
package dorkbox.util; package dorkbox.util;
import java.awt.Container; import javax.swing.*;
import java.awt.EventQueue; import java.awt.*;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList; import java.util.ArrayList;
import javax.swing.SwingUtilities; public
class SwingUtil {
public class SwingUtil { public static
public static void showOnSameScreenAsMouseCenter(Container frame) { void showOnSameScreenAsMouseCenter(Container frame) {
Point mouseLocation = MouseInfo.getPointerInfo().getLocation(); Point mouseLocation = MouseInfo.getPointerInfo()
.getLocation();
GraphicsDevice deviceAtMouse = getGraphicsDeviceAt(mouseLocation); GraphicsDevice deviceAtMouse = getGraphicsDeviceAt(mouseLocation);
Rectangle bounds = deviceAtMouse.getDefaultConfiguration().getBounds(); Rectangle bounds = deviceAtMouse.getDefaultConfiguration()
.getBounds();
frame.setLocation(bounds.x + bounds.width / 2 - frame.getWidth() / 2, bounds.height / 2 - frame.getHeight() / 2); frame.setLocation(bounds.x + bounds.width / 2 - frame.getWidth() / 2, bounds.height / 2 - frame.getHeight() / 2);
} }
public static void showOnSameScreenAsMouse(Container frame) { public static
Point mouseLocation = MouseInfo.getPointerInfo().getLocation(); void showOnSameScreenAsMouse(Container frame) {
Point mouseLocation = MouseInfo.getPointerInfo()
.getLocation();
GraphicsDevice deviceAtMouse = getGraphicsDeviceAt(mouseLocation); GraphicsDevice deviceAtMouse = getGraphicsDeviceAt(mouseLocation);
frame.setLocation(deviceAtMouse.getDefaultConfiguration().getBounds().x, frame.getY()); frame.setLocation(deviceAtMouse.getDefaultConfiguration()
.getBounds().x, frame.getY());
} }
public static Rectangle getScreenBoundsAt(Point pos) { public static
Rectangle getScreenBoundsAt(Point pos) {
GraphicsDevice gd = SwingUtil.getGraphicsDeviceAt(pos); GraphicsDevice gd = SwingUtil.getGraphicsDeviceAt(pos);
Rectangle bounds = null; Rectangle bounds = null;
if (gd != null) { if (gd != null) {
bounds = gd.getDefaultConfiguration().getBounds(); bounds = gd.getDefaultConfiguration()
.getBounds();
} }
return bounds; return bounds;
} }
public static GraphicsDevice getGraphicsDeviceAt(Point pos) { public static
GraphicsDevice getGraphicsDeviceAt(Point pos) {
GraphicsDevice device; GraphicsDevice device;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
@ -74,7 +76,8 @@ public class SwingUtil {
if (lstDevices.size() > 0) { if (lstDevices.size() > 0) {
device = lstDevices.get(0); device = lstDevices.get(0);
} else { }
else {
device = ge.getDefaultScreenDevice(); device = ge.getDefaultScreenDevice();
} }
@ -104,18 +107,22 @@ public class SwingUtil {
// return insets; // return insets;
// } // }
public static void invokeLater(Runnable runnable) { public static
void invokeLater(Runnable runnable) {
if (EventQueue.isDispatchThread()) { if (EventQueue.isDispatchThread()) {
runnable.run(); runnable.run();
} else { }
else {
SwingUtilities.invokeLater(runnable); SwingUtilities.invokeLater(runnable);
} }
} }
public static void invokeAndWait(Runnable runnable) { public static
void invokeAndWait(Runnable runnable) {
if (EventQueue.isDispatchThread()) { if (EventQueue.isDispatchThread()) {
runnable.run(); runnable.run();
} else { }
else {
try { try {
EventQueue.invokeAndWait(runnable); EventQueue.invokeAndWait(runnable);
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {

View File

@ -25,7 +25,8 @@ import java.util.Map.Entry;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public @SuppressWarnings("unused")
public final
class Sys { class Sys {
public static final int javaVersion = getJavaVersion(); public static final int javaVersion = getJavaVersion();
public static final boolean isAndroid = getIsAndroid(); public static final boolean isAndroid = getIsAndroid();
@ -35,9 +36,9 @@ class Sys {
public static final int GIGABYTE = 1024 * MEGABYTE; public static final int GIGABYTE = 1024 * MEGABYTE;
public static final long TERABYTE = 1024L * GIGABYTE; public static final long TERABYTE = 1024L * GIGABYTE;
public static char[] HEX_CHARS = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public static final char[] HEX_CHARS = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static final public static
char[] convertStringToChars(String string) { char[] convertStringToChars(String string) {
char[] charArray = string.toCharArray(); char[] charArray = string.toCharArray();
@ -89,7 +90,7 @@ class Sys {
public static final public static
void eraseString(String string) { void eraseString(String string) {
// You can change the value of the inner char[] using reflection. // You can change the value of the inner char[] using reflection.
// //
@ -271,7 +272,7 @@ class Sys {
public static public static
<T extends OutputStream> T copyStream(InputStream inputStream, T outputStream) throws IOException { <T extends OutputStream> T copyStream(InputStream inputStream, T outputStream) throws IOException {
byte[] buffer = new byte[4096]; byte[] buffer = new byte[4096];
int read = 0; int read;
while ((read = inputStream.read(buffer)) > 0) { while ((read = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, read); outputStream.write(buffer, 0, read);
} }
@ -287,7 +288,7 @@ class Sys {
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
byte[] buffer = new byte[4096]; byte[] buffer = new byte[4096];
int read = 0; int read;
while ((read = inputStream.read(buffer)) > 0) { while ((read = inputStream.read(buffer)) > 0) {
baos.write(buffer, 0, read); baos.write(buffer, 0, read);
} }
@ -297,12 +298,12 @@ class Sys {
return baos.toByteArray(); return baos.toByteArray();
} }
public static final public static
byte[] copyBytes(byte[] src) { byte[] copyBytes(byte[] src) {
return copyBytes(src, 0); return copyBytes(src, 0);
} }
public static final public static
byte[] copyBytes(byte[] src, int position) { byte[] copyBytes(byte[] src, int position) {
int length = src.length - position; int length = src.length - position;
@ -311,7 +312,7 @@ class Sys {
return b; return b;
} }
public static final public static
byte[] concatBytes(byte[]... arrayBytes) { byte[] concatBytes(byte[]... arrayBytes) {
int length = 0; int length = 0;
for (byte[] bytes : arrayBytes) { for (byte[] bytes : arrayBytes) {
@ -332,7 +333,7 @@ class Sys {
/** /**
* gets the SHA256 hash + SALT of the specified username, as UTF-16 * gets the SHA256 hash + SALT of the specified username, as UTF-16
*/ */
public static final public static
byte[] getSha256WithSalt(String username, byte[] saltBytes) { byte[] getSha256WithSalt(String username, byte[] saltBytes) {
if (username == null) { if (username == null) {
return null; return null;
@ -353,7 +354,7 @@ class Sys {
/** /**
* gets the SHA256 hash of the specified string, as UTF-16 * gets the SHA256 hash of the specified string, as UTF-16
*/ */
public static final public static
byte[] getSha256(String string) { byte[] getSha256(String string) {
byte[] charToBytes = Sys.charToBytes(string.toCharArray()); byte[] charToBytes = Sys.charToBytes(string.toCharArray());
@ -368,7 +369,7 @@ class Sys {
/** /**
* gets the SHA256 hash of the specified byte array * gets the SHA256 hash of the specified byte array
*/ */
public static final public static
byte[] getSha256(byte[] bytes) { byte[] getSha256(byte[] bytes) {
SHA256Digest sha256 = new SHA256Digest(); SHA256Digest sha256 = new SHA256Digest();
@ -382,7 +383,7 @@ class Sys {
/** /**
* this saves the char array in UTF-16 format of bytes * this saves the char array in UTF-16 format of bytes
*/ */
public static final public static
byte[] charToBytes(char[] text) { byte[] charToBytes(char[] text) {
// NOTE: this saves the char array in UTF-16 format of bytes. // NOTE: this saves the char array in UTF-16 format of bytes.
byte[] bytes = new byte[text.length * 2]; byte[] bytes = new byte[text.length * 2];
@ -395,7 +396,7 @@ class Sys {
} }
public static final public static
byte[] intsToBytes(int[] ints) { byte[] intsToBytes(int[] ints) {
int length = ints.length; int length = ints.length;
byte[] bytes = new byte[length]; byte[] bytes = new byte[length];
@ -413,7 +414,7 @@ class Sys {
return bytes; return bytes;
} }
public static final public static
int[] bytesToInts(byte[] bytes) { int[] bytesToInts(byte[] bytes) {
int length = bytes.length; int length = bytes.length;
int[] ints = new int[length]; int[] ints = new int[length];
@ -425,12 +426,12 @@ class Sys {
return ints; return ints;
} }
public static final public static
String bytesToHex(byte[] bytes) { String bytesToHex(byte[] bytes) {
return bytesToHex(bytes, false); return bytesToHex(bytes, false);
} }
public static final public static
String bytesToHex(byte[] bytes, boolean padding) { String bytesToHex(byte[] bytes, boolean padding) {
if (padding) { if (padding) {
char[] hexString = new char[3 * bytes.length]; char[] hexString = new char[3 * bytes.length];
@ -461,7 +462,7 @@ class Sys {
* Converts an ASCII character representing a hexadecimal * Converts an ASCII character representing a hexadecimal
* value into its integer equivalent. * value into its integer equivalent.
*/ */
public static final public static
int hexByteToInt(byte b) { int hexByteToInt(byte b) {
switch (b) { switch (b) {
case '0': case '0':
@ -510,7 +511,7 @@ class Sys {
/** /**
* A 4-digit hex result. * A 4-digit hex result.
*/ */
public static final public static
void hex4(char c, StringBuilder sb) { void hex4(char c, StringBuilder sb) {
sb.append(HEX_CHARS[(c & 0xF000) >> 12]); sb.append(HEX_CHARS[(c & 0xF000) >> 12]);
sb.append(HEX_CHARS[(c & 0x0F00) >> 8]); sb.append(HEX_CHARS[(c & 0x0F00) >> 8]);
@ -526,7 +527,7 @@ class Sys {
* @return a string representation of the byte array as a series of * @return a string representation of the byte array as a series of
* hexadecimal characters * hexadecimal characters
*/ */
public static final public static
String toHexString(byte[] bytes) { String toHexString(byte[] bytes) {
char[] hexString = new char[2 * bytes.length]; char[] hexString = new char[2 * bytes.length];
int j = 0; int j = 0;
@ -558,14 +559,12 @@ class Sys {
public static final public static
byte[] encodeStringArray(List<String> array) { byte[] encodeStringArray(List<String> array) {
int length = 0; int length = 0;
for (String s : array) { for (String s : array) {
byte[] bytes = s.getBytes(); byte[] bytes = s.getBytes();
if (bytes != null) { length += bytes.length;
length += bytes.length;
}
} }
if (length == 0) { if (length == 0) {
@ -585,7 +584,7 @@ class Sys {
return bytes; return bytes;
} }
public static final public static
ArrayList<String> decodeStringArray(byte[] bytes) { ArrayList<String> decodeStringArray(byte[] bytes) {
int length = bytes.length; int length = bytes.length;
int position = 0; int position = 0;
@ -609,24 +608,23 @@ class Sys {
} }
public static public static
String printArrayRaw(byte[] bytes) { String printArrayRaw(final byte[] bytes) {
return printArrayRaw(bytes, 0); return printArrayRaw(bytes, 0);
} }
public static public static
String printArrayRaw(byte[] bytes, int lineLength) { String printArrayRaw(final byte[] bytes, final int lineLength) {
if (lineLength > 0) { if (lineLength > 0) {
int mod = lineLength;
int length = bytes.length; int length = bytes.length;
int comma = length - 1; int comma = length - 1;
StringBuilder builder = new StringBuilder(length + length / mod); StringBuilder builder = new StringBuilder(length + length / lineLength);
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
builder.append(bytes[i]); builder.append(bytes[i]);
if (i < comma) { if (i < comma) {
builder.append(","); builder.append(",");
} }
if (i > 0 && i % mod == 0) { if (i > 0 && i % lineLength == 0) {
builder.append(OS.LINE_SEPARATOR); builder.append(OS.LINE_SEPARATOR);
} }
} }
@ -777,9 +775,17 @@ class Sys {
// dig +short myip.opendns.com @resolver1.opendns.com // dig +short myip.opendns.com @resolver1.opendns.com
// method 2: use public http servers // method 2: use public http servers
final String websites[] = {"http://ip.dorkbox.com/", "http://ip.javalauncher.com/", "http://checkip.dyndns.com/", // @formatter:off
"http://checkip.dyn.com/", "http://curlmyip.com/", "http://tnx.nl/ip", "http://ipecho.net/plain", final String websites[] = {"http://ip.dorkbox.com/",
"http://icanhazip.com/", "http://ip.appspot.com/",}; "http://ip.javalauncher.com/",
"http://checkip.dyndns.com/",
"http://checkip.dyn.com/",
"http://curlmyip.com/",
"http://tnx.nl/ip",
"http://ipecho.net/plain",
"http://icanhazip.com/",
"http://ip.appspot.com/",};
// @formatter:on
// loop, since they won't always work. // loop, since they won't always work.
for (int i = 0; i < websites.length; i++) { for (int i = 0; i < websites.length; i++) {
@ -793,11 +799,10 @@ class Sys {
Pattern pattern = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"); Pattern pattern = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b");
Matcher matcher = pattern.matcher(response); Matcher matcher = pattern.matcher(response);
if (matcher.find()) { if (matcher.find()) {
String IP = matcher.group() return matcher.group()
.trim(); .trim();
return IP;
} }
} catch (Exception e) { } catch (Exception ignored) {
} }
} }
@ -890,9 +895,13 @@ class Sys {
} }
} }
} }
} catch (SocketException e) { } catch (SocketException ignored) {
} }
return null; return null;
} }
private
Sys() {
}
} }

View File

@ -24,29 +24,31 @@ import java.nio.ByteBuffer;
/** /**
* This is (mostly) motorola, and is "network byte order". * This is (mostly) motorola, and is "network byte order".
* This is also the default for Java. * This is also the default for Java.
* <p> * <p/>
* arm is technically bi-endian * arm is technically bi-endian
*/ */
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
public class BigEndian { public
class BigEndian {
// the following are ALL in Bit-Endian (byte[0] is most significant) // the following are ALL in Bit-Endian (byte[0] is most significant)
// TODO: switch these to big endian. these are a copy of little endian // TODO: switch these to big endian. these are a copy of little endian
/** CHAR to and from bytes */
/**
* CHAR to and from bytes
*/
public static final public static final
class Char_ { class Char_ {
private
Char_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
char from(byte[] bytes, int offset, int bytenum) { char from(byte[] bytes, int offset, int bytenum) {
char number = 0; char number = 0;
switch (bytenum) { switch (bytenum) {
case 2: number |= (bytes[offset+0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+1] & 0xFF) << 0; number |= (bytes[offset + 0] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 1] & 0xFF) << 0;
} }
return number; return number;
@ -58,8 +60,10 @@ public class BigEndian {
char number = 0; char number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[1] & 0xFF) << 0; number |= (bytes[0] & 0xFF) << 8;
case 1:
number |= (bytes[1] & 0xFF) << 0;
} }
return number; return number;
@ -67,15 +71,12 @@ public class BigEndian {
public static public static
char from(byte b0, byte b1) { char from(byte b0, byte b1) {
return (char) ((b0 & 0xFF) << 8 | return (char) ((b0 & 0xFF) << 8 | (b1 & 0xFF) << 0);
(b1 & 0xFF) << 0);
} }
public static public static
byte[] toBytes(char x) { byte[] toBytes(char x) {
return new byte[] {(byte) (x >> 8), return new byte[] {(byte) (x >> 8), (byte) (x >> 0)};
(byte) (x >> 0)
};
} }
public static public static
@ -92,23 +93,28 @@ public class BigEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
Char_() {
}
} }
/** UNSIGNED CHAR to and from bytes */
/**
* UNSIGNED CHAR to and from bytes
*/
public static final public static final
class UChar_ { class UChar_ {
private
UChar_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
UShort from(byte[] bytes, int offset, int bytenum) { UShort from(byte[] bytes, int offset, int bytenum) {
char number = 0; char number = 0;
switch (bytenum) { switch (bytenum) {
case 2: number |= (bytes[offset+0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+1] & 0xFF) << 0; number |= (bytes[offset + 0] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 1] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -120,8 +126,10 @@ public class BigEndian {
short number = 0; short number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[1] & 0xFF) << 0; number |= (bytes[0] & 0xFF) << 8;
case 1:
number |= (bytes[1] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -129,19 +137,14 @@ public class BigEndian {
public static public static
UShort from(byte b0, byte b1) { UShort from(byte b0, byte b1) {
return UShort.valueOf((short) return UShort.valueOf((short) ((b0 & 0xFF) << 8) | (b1 & 0xFF) << 0);
((b0 & 0xFF) << 8) |
(b1 & 0xFF) << 0) ;
} }
public static public static
byte[] toBytes(UShort x) { byte[] toBytes(UShort x) {
int num = x.intValue(); int num = x.intValue();
return new byte[] {(byte) ((num & 0xFF00) >> 8), return new byte[] {(byte) ((num & 0xFF00) >> 8), (byte) (num & 0x00FF >> 0),};
(byte) (num & 0x00FF >> 0),
};
} }
public static public static
@ -158,23 +161,28 @@ public class BigEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
UChar_() {
}
} }
/** SHORT to and from bytes */
/**
* SHORT to and from bytes
*/
public static final public static final
class Short_ { class Short_ {
private
Short_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
short from(byte[] bytes, int offset, int bytenum) { short from(byte[] bytes, int offset, int bytenum) {
short number = 0; short number = 0;
switch (bytenum) { switch (bytenum) {
case 2: number |= (bytes[offset+0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+1] & 0xFF) << 0; number |= (bytes[offset + 0] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 1] & 0xFF) << 0;
} }
return number; return number;
@ -186,8 +194,10 @@ public class BigEndian {
short number = 0; short number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[1] & 0xFF) << 0; number |= (bytes[0] & 0xFF) << 8;
case 1:
number |= (bytes[1] & 0xFF) << 0;
} }
return number; return number;
@ -195,16 +205,12 @@ public class BigEndian {
public static public static
short from(byte b0, byte b1) { short from(byte b0, byte b1) {
return (short) ((b0 & 0xFF) << 8 | return (short) ((b0 & 0xFF) << 8 | (b1 & 0xFF) << 0);
(b1 & 0xFF) << 0);
} }
public static public static
byte[] toBytes(short x) { byte[] toBytes(short x) {
return new byte[] {(byte) (x >> 8), return new byte[] {(byte) (x >> 8), (byte) (x >> 0)};
(byte) (x >> 0)
};
} }
public static public static
@ -221,23 +227,28 @@ public class BigEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
Short_() {
}
} }
/** UNSIGNED SHORT to and from bytes */
/**
* UNSIGNED SHORT to and from bytes
*/
public static final public static final
class UShort_ { class UShort_ {
private
UShort_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
UShort from(byte[] bytes, int offset, int bytenum) { UShort from(byte[] bytes, int offset, int bytenum) {
char number = 0; char number = 0;
switch (bytenum) { switch (bytenum) {
case 2: number |= (bytes[offset+0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+1] & 0xFF) << 0; number |= (bytes[offset + 0] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 1] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -249,8 +260,10 @@ public class BigEndian {
short number = 0; short number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[0] & 0xFF) << 8; case 2:
case 1: number |= (bytes[1] & 0xFF) << 0; number |= (bytes[0] & 0xFF) << 8;
case 1:
number |= (bytes[1] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -258,19 +271,14 @@ public class BigEndian {
public static public static
UShort from(byte b0, byte b1) { UShort from(byte b0, byte b1) {
return UShort.valueOf((short) return UShort.valueOf((short) ((b0 & 0xFF) << 8) | (b1 & 0xFF) << 0);
((b0 & 0xFF) << 8) |
(b1 & 0xFF) << 0) ;
} }
public static public static
byte[] toBytes(UShort x) { byte[] toBytes(UShort x) {
int num = x.intValue(); int num = x.intValue();
return new byte[] {(byte) ((num & 0xFF00) >> 8), return new byte[] {(byte) ((num & 0xFF00) >> 8), (byte) (num & 0x00FF >> 0),};
(byte) (num & 0x00FF >> 0),
};
} }
public static public static
@ -287,25 +295,32 @@ public class BigEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
UShort_() {
}
} }
/** INT to and from bytes */
/**
* INT to and from bytes
*/
public static final public static final
class Int_ { class Int_ {
private
Int_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
int from(byte[] bytes, int offset, int bytenum) { int from(byte[] bytes, int offset, int bytenum) {
int number = 0; int number = 0;
switch (bytenum) { switch (bytenum) {
case 4: number |= (bytes[offset+0] & 0xFF) << 24; case 4:
case 3: number |= (bytes[offset+1] & 0xFF) << 16; number |= (bytes[offset + 0] & 0xFF) << 24;
case 2: number |= (bytes[offset+2] & 0xFF) << 8; case 3:
case 1: number |= (bytes[offset+3] & 0xFF) << 0; number |= (bytes[offset + 1] & 0xFF) << 16;
case 2:
number |= (bytes[offset + 2] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 3] & 0xFF) << 0;
} }
return number; return number;
@ -317,10 +332,14 @@ public class BigEndian {
int number = 0; int number = 0;
switch (bytes.length) { switch (bytes.length) {
case 4: number |= (bytes[0] & 0xFF) << 24; case 4:
case 3: number |= (bytes[1] & 0xFF) << 16; number |= (bytes[0] & 0xFF) << 24;
case 2: number |= (bytes[2] & 0xFF) << 8; case 3:
case 1: number |= (bytes[3] & 0xFF) << 0; number |= (bytes[1] & 0xFF) << 16;
case 2:
number |= (bytes[2] & 0xFF) << 8;
case 1:
number |= (bytes[3] & 0xFF) << 0;
} }
return number; return number;
@ -330,17 +349,13 @@ public class BigEndian {
int from(byte b0, byte b1, byte b2, byte b3) { int from(byte b0, byte b1, byte b2, byte b3) {
return (b0 & 0xFF) << 24 | return (b0 & 0xFF) << 24 |
(b1 & 0xFF) << 16 | (b1 & 0xFF) << 16 |
(b2 & 0xFF) << 8 | (b2 & 0xFF) << 8 |
(b3 & 0xFF) << 0; (b3 & 0xFF) << 0;
} }
public static public static
byte[] toBytes(int x) { byte[] toBytes(int x) {
return new byte[] {(byte) (x >> 24), return new byte[] {(byte) (x >> 24), (byte) (x >> 16), (byte) (x >> 8), (byte) (x >> 0)};
(byte) (x >> 16),
(byte) (x >> 8),
(byte) (x >> 0)
} ;
} }
public static public static
@ -357,25 +372,32 @@ public class BigEndian {
return from(b[0], b[1], b[2], b[3]); return from(b[0], b[1], b[2], b[3]);
} }
private
Int_() {
}
} }
/** UNSIGNED INT to and from bytes */
/**
* UNSIGNED INT to and from bytes
*/
public static final public static final
class UInt_ { class UInt_ {
private
UInt_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
UInteger from(byte[] bytes, int offset, int bytenum) { UInteger from(byte[] bytes, int offset, int bytenum) {
int number = 0; int number = 0;
switch (bytenum) { switch (bytenum) {
case 4: number |= (bytes[offset+0] & 0xFF) << 24; case 4:
case 3: number |= (bytes[offset+1] & 0xFF) << 16; number |= (bytes[offset + 0] & 0xFF) << 24;
case 2: number |= (bytes[offset+2] & 0xFF) << 8; case 3:
case 1: number |= (bytes[offset+3] & 0xFF) << 0; number |= (bytes[offset + 1] & 0xFF) << 16;
case 2:
number |= (bytes[offset + 2] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 3] & 0xFF) << 0;
} }
return UInteger.valueOf(number); return UInteger.valueOf(number);
@ -387,10 +409,14 @@ public class BigEndian {
int number = 0; int number = 0;
switch (bytes.length) { switch (bytes.length) {
case 4: number |= (bytes[0] & 0xFF) << 24; case 4:
case 3: number |= (bytes[1] & 0xFF) << 16; number |= (bytes[0] & 0xFF) << 24;
case 2: number |= (bytes[2] & 0xFF) << 8; case 3:
case 1: number |= (bytes[3] & 0xFF) << 0; number |= (bytes[1] & 0xFF) << 16;
case 2:
number |= (bytes[2] & 0xFF) << 8;
case 1:
number |= (bytes[3] & 0xFF) << 0;
} }
return UInteger.valueOf(number); return UInteger.valueOf(number);
@ -400,8 +426,8 @@ public class BigEndian {
UInteger from(byte b0, byte b1, byte b2, byte b3) { UInteger from(byte b0, byte b1, byte b2, byte b3) {
int number = (b0 & 0xFF) << 24 | int number = (b0 & 0xFF) << 24 |
(b1 & 0xFF) << 16 | (b1 & 0xFF) << 16 |
(b2 & 0xFF) << 8 | (b2 & 0xFF) << 8 |
(b3 & 0xFF) << 0; (b3 & 0xFF) << 0;
return UInteger.valueOf(number); return UInteger.valueOf(number);
} }
@ -410,11 +436,8 @@ public class BigEndian {
byte[] toBytes(UInteger x) { byte[] toBytes(UInteger x) {
long num = x.longValue(); long num = x.longValue();
return new byte[] {(byte) ((num & 0xFF000000L) >> 24), return new byte[] {(byte) ((num & 0xFF000000L) >> 24), (byte) ((num & 0x00FF0000L) >> 16), (byte) ((num & 0x0000FF00L) >> 8),
(byte) ((num & 0x00FF0000L) >> 16), (byte) (num & 0x000000FFL >> 0)};
(byte) ((num & 0x0000FF00L) >> 8),
(byte) (num & 0x000000FFL >> 0)
};
} }
public static public static
@ -431,29 +454,40 @@ public class BigEndian {
return from(b[0], b[1], b[2], b[3]); return from(b[0], b[1], b[2], b[3]);
} }
private
UInt_() {
}
} }
/** LONG to and from bytes */
/**
* LONG to and from bytes
*/
public static final public static final
class Long_ { class Long_ {
private
Long_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
long from(byte[] bytes, int offset, int bytenum) { long from(byte[] bytes, int offset, int bytenum) {
long number = 0; long number = 0;
switch (bytenum) { switch (bytenum) {
case 8: number |= (long) (bytes[offset+0] & 0xFF) << 56; case 8:
case 7: number |= (long) (bytes[offset+1] & 0xFF) << 48; number |= (long) (bytes[offset + 0] & 0xFF) << 56;
case 6: number |= (long) (bytes[offset+2] & 0xFF) << 40; case 7:
case 5: number |= (long) (bytes[offset+3] & 0xFF) << 32; number |= (long) (bytes[offset + 1] & 0xFF) << 48;
case 4: number |= (long) (bytes[offset+4] & 0xFF) << 24; case 6:
case 3: number |= (long) (bytes[offset+5] & 0xFF) << 16; number |= (long) (bytes[offset + 2] & 0xFF) << 40;
case 2: number |= (long) (bytes[offset+6] & 0xFF) << 8; case 5:
case 1: number |= (long) (bytes[offset+7] & 0xFF) << 0; number |= (long) (bytes[offset + 3] & 0xFF) << 32;
case 4:
number |= (long) (bytes[offset + 4] & 0xFF) << 24;
case 3:
number |= (long) (bytes[offset + 5] & 0xFF) << 16;
case 2:
number |= (long) (bytes[offset + 6] & 0xFF) << 8;
case 1:
number |= (long) (bytes[offset + 7] & 0xFF) << 0;
} }
return number; return number;
@ -465,14 +499,22 @@ public class BigEndian {
long number = 0L; long number = 0L;
switch (bytes.length) { switch (bytes.length) {
case 8: number |= (long) (bytes[0] & 0xFF) << 56; case 8:
case 7: number |= (long) (bytes[1] & 0xFF) << 48; number |= (long) (bytes[0] & 0xFF) << 56;
case 6: number |= (long) (bytes[2] & 0xFF) << 40; case 7:
case 5: number |= (long) (bytes[3] & 0xFF) << 32; number |= (long) (bytes[1] & 0xFF) << 48;
case 4: number |= (long) (bytes[4] & 0xFF) << 24; case 6:
case 3: number |= (long) (bytes[5] & 0xFF) << 16; number |= (long) (bytes[2] & 0xFF) << 40;
case 2: number |= (long) (bytes[6] & 0xFF) << 8; case 5:
case 1: number |= (long) (bytes[7] & 0xFF) << 0; number |= (long) (bytes[3] & 0xFF) << 32;
case 4:
number |= (long) (bytes[4] & 0xFF) << 24;
case 3:
number |= (long) (bytes[5] & 0xFF) << 16;
case 2:
number |= (long) (bytes[6] & 0xFF) << 8;
case 1:
number |= (long) (bytes[7] & 0xFF) << 0;
} }
return number; return number;
@ -486,21 +528,14 @@ public class BigEndian {
(long) (b3 & 0xFF) << 32 | (long) (b3 & 0xFF) << 32 |
(long) (b4 & 0xFF) << 24 | (long) (b4 & 0xFF) << 24 |
(long) (b5 & 0xFF) << 16 | (long) (b5 & 0xFF) << 16 |
(long) (b6 & 0xFF) << 8 | (long) (b6 & 0xFF) << 8 |
(long) (b7 & 0xFF) << 0; (long) (b7 & 0xFF) << 0;
} }
public static public static
byte[] toBytes (long x) { byte[] toBytes(long x) {
return new byte[] {(byte) (x >> 56), return new byte[] {(byte) (x >> 56), (byte) (x >> 48), (byte) (x >> 40), (byte) (x >> 32), (byte) (x >> 24), (byte) (x >> 16),
(byte) (x >> 48), (byte) (x >> 8), (byte) (x >> 0)};
(byte) (x >> 40),
(byte) (x >> 32),
(byte) (x >> 24),
(byte) (x >> 16),
(byte) (x >> 8),
(byte) (x >> 0)
};
} }
public static public static
@ -517,35 +552,47 @@ public class BigEndian {
return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]); return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
} }
private
Long_() {
}
} }
/** UNSIGNED LONG to and from bytes */
/**
* UNSIGNED LONG to and from bytes
*/
public static final public static final
class ULong_ { class ULong_ {
private
ULong_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
ULong from(byte[] bytes, int offset, int bytenum) { ULong from(byte[] bytes, int offset, int bytenum) {
long number = 0; long number = 0;
switch (bytenum) { switch (bytenum) {
case 8: number |= (long) (bytes[offset+0] & 0xFF) << 56; case 8:
case 7: number |= (long) (bytes[offset+1] & 0xFF) << 48; number |= (long) (bytes[offset + 0] & 0xFF) << 56;
case 6: number |= (long) (bytes[offset+2] & 0xFF) << 40; case 7:
case 5: number |= (long) (bytes[offset+3] & 0xFF) << 32; number |= (long) (bytes[offset + 1] & 0xFF) << 48;
case 4: number |= (long) (bytes[offset+4] & 0xFF) << 24; case 6:
case 3: number |= (long) (bytes[offset+5] & 0xFF) << 16; number |= (long) (bytes[offset + 2] & 0xFF) << 40;
case 2: number |= (long) (bytes[offset+6] & 0xFF) << 8; case 5:
case 1: number |= (long) (bytes[offset+7] & 0xFF) << 0; number |= (long) (bytes[offset + 3] & 0xFF) << 32;
case 4:
number |= (long) (bytes[offset + 4] & 0xFF) << 24;
case 3:
number |= (long) (bytes[offset + 5] & 0xFF) << 16;
case 2:
number |= (long) (bytes[offset + 6] & 0xFF) << 8;
case 1:
number |= (long) (bytes[offset + 7] & 0xFF) << 0;
} }
return ULong.valueOf(number); return ULong.valueOf(number);
} }
public static ULong from(byte[] bytes) { public static
ULong from(byte[] bytes) {
BigInteger ulong = new BigInteger(1, bytes); BigInteger ulong = new BigInteger(1, bytes);
return ULong.valueOf(ulong); return ULong.valueOf(ulong);
} }
@ -558,9 +605,10 @@ public class BigEndian {
} }
public static public static
byte[] toBytes (ULong x) { byte[] toBytes(ULong x) {
// returns the shortest length byte array possible // returns the shortest length byte array possible
byte[] bytes = x.toBigInteger().toByteArray(); byte[] bytes = x.toBigInteger()
.toByteArray();
if (bytes.length < 8) { if (bytes.length < 8) {
@ -595,6 +643,10 @@ public class BigEndian {
return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]); return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
} }
private
ULong_() {
}
} }
} }

View File

@ -17,9 +17,11 @@ package dorkbox.util.bytes;
import dorkbox.util.objectPool.PoolableObject; import dorkbox.util.objectPool.PoolableObject;
public class ByteBuffer2Poolable implements PoolableObject<ByteBuffer2> { public
class ByteBuffer2Poolable implements PoolableObject<ByteBuffer2> {
@Override @Override
public ByteBuffer2 create() { public
ByteBuffer2 create() {
return new ByteBuffer2(8, -1); return new ByteBuffer2(8, -1);
} }
} }

View File

@ -23,30 +23,32 @@ import java.nio.ByteBuffer;
/** /**
* This is intel/amd/arm arch! * This is intel/amd/arm arch!
* <p> * <p/>
* arm is technically bi-endian * arm is technically bi-endian
* <p> * <p/>
* Network byte order IS big endian, as is Java. * Network byte order IS big endian, as is Java.
*/ */
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
public class LittleEndian { public
class LittleEndian {
// the following are ALL in Little-Endian (byte[0] is least significant) // the following are ALL in Little-Endian (byte[0] is least significant)
/** CHAR to and from bytes */
/**
* CHAR to and from bytes
*/
public static final public static final
class Char_ { class Char_ {
private
Char_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
char from(byte[] bytes, int offset, int byteNum) { char from(byte[] bytes, int offset, int byteNum) {
char number = 0; char number = 0;
switch (byteNum) { switch (byteNum) {
case 2: number |= (bytes[offset+1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+0] & 0xFF) << 0; number |= (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 0] & 0xFF) << 0;
} }
return number; return number;
@ -58,8 +60,10 @@ public class LittleEndian {
char number = 0; char number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[0] & 0xFF) << 0; number |= (bytes[1] & 0xFF) << 8;
case 1:
number |= (bytes[0] & 0xFF) << 0;
} }
return number; return number;
@ -67,15 +71,12 @@ public class LittleEndian {
public static public static
char from(byte b0, byte b1) { char from(byte b0, byte b1) {
return (char) ((b1 & 0xFF) << 8 | return (char) ((b1 & 0xFF) << 8 | (b0 & 0xFF) << 0);
(b0 & 0xFF) << 0);
} }
public static public static
byte[] toBytes(char x) { byte[] toBytes(char x) {
return new byte[] {(byte) (x >> 0), return new byte[] {(byte) (x >> 0), (byte) (x >> 8)};
(byte) (x >> 8)
};
} }
public static public static
@ -92,23 +93,28 @@ public class LittleEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
Char_() {
}
} }
/** UNSIGNED CHAR to and from bytes */
/**
* UNSIGNED CHAR to and from bytes
*/
public static final public static final
class UChar_ { class UChar_ {
private
UChar_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
UShort from(byte[] bytes, int offset, int bytenum) { UShort from(byte[] bytes, int offset, int bytenum) {
char number = 0; char number = 0;
switch (bytenum) { switch (bytenum) {
case 2: number |= (bytes[offset+1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+0] & 0xFF) << 0; number |= (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 0] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -120,8 +126,10 @@ public class LittleEndian {
short number = 0; short number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[0] & 0xFF) << 0; number |= (bytes[1] & 0xFF) << 8;
case 1:
number |= (bytes[0] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -129,19 +137,14 @@ public class LittleEndian {
public static public static
UShort from(byte b0, byte b1) { UShort from(byte b0, byte b1) {
return UShort.valueOf((short) return UShort.valueOf((short) ((b1 & 0xFF) << 8) | (b0 & 0xFF) << 0);
((b1 & 0xFF) << 8) |
(b0 & 0xFF) << 0) ;
} }
public static public static
byte[] toBytes(UShort x) { byte[] toBytes(UShort x) {
int num = x.intValue(); int num = x.intValue();
return new byte[] {(byte) (num & 0x00FF >> 0), return new byte[] {(byte) (num & 0x00FF >> 0), (byte) ((num & 0xFF00) >> 8)};
(byte) ((num & 0xFF00) >> 8)
};
} }
public static public static
@ -158,23 +161,28 @@ public class LittleEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
UChar_() {
}
} }
/** SHORT to and from bytes */
/**
* SHORT to and from bytes
*/
public static final public static final
class Short_ { class Short_ {
private
Short_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
short from(byte[] bytes, int offset, int bytenum) { short from(byte[] bytes, int offset, int bytenum) {
short number = 0; short number = 0;
switch (bytenum) { switch (bytenum) {
case 2: number |= (bytes[offset+1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+0] & 0xFF) << 0; number |= (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 0] & 0xFF) << 0;
} }
return number; return number;
@ -186,8 +194,10 @@ public class LittleEndian {
short number = 0; short number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[0] & 0xFF) << 0; number |= (bytes[1] & 0xFF) << 8;
case 1:
number |= (bytes[0] & 0xFF) << 0;
} }
return number; return number;
@ -195,16 +205,12 @@ public class LittleEndian {
public static public static
short from(byte b0, byte b1) { short from(byte b0, byte b1) {
return (short) ((b1 & 0xFF) << 8 | return (short) ((b1 & 0xFF) << 8 | (b0 & 0xFF) << 0);
(b0 & 0xFF) << 0);
} }
public static public static
byte[] toBytes(short x) { byte[] toBytes(short x) {
return new byte[] {(byte) (x >> 0), return new byte[] {(byte) (x >> 0), (byte) (x >> 8)};
(byte) (x >> 8)
};
} }
public static public static
@ -221,23 +227,28 @@ public class LittleEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
Short_() {
}
} }
/** UNSIGNED SHORT to and from bytes */
/**
* UNSIGNED SHORT to and from bytes
*/
public static final public static final
class UShort_ { class UShort_ {
private
UShort_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
UShort from(byte[] bytes, int offset, int bytenum) { UShort from(byte[] bytes, int offset, int bytenum) {
short number = 0; short number = 0;
switch (bytenum) { switch (bytenum) {
case 2: number |= (bytes[offset+1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[offset+0] & 0xFF) << 0; number |= (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 0] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -249,8 +260,10 @@ public class LittleEndian {
short number = 0; short number = 0;
switch (bytes.length) { switch (bytes.length) {
case 2: number |= (bytes[1] & 0xFF) << 8; case 2:
case 1: number |= (bytes[0] & 0xFF) << 0; number |= (bytes[1] & 0xFF) << 8;
case 1:
number |= (bytes[0] & 0xFF) << 0;
} }
return UShort.valueOf(number); return UShort.valueOf(number);
@ -258,19 +271,14 @@ public class LittleEndian {
public static public static
UShort from(byte b0, byte b1) { UShort from(byte b0, byte b1) {
return UShort.valueOf((short) return UShort.valueOf((short) ((b1 & 0xFF) << 8 | (b0 & 0xFF) << 0));
((b1 & 0xFF) << 8 |
(b0 & 0xFF) << 0));
} }
public static public static
byte[] toBytes(UShort x) { byte[] toBytes(UShort x) {
int num = x.intValue(); int num = x.intValue();
return new byte[] {(byte) (num & 0x00FF >> 0), return new byte[] {(byte) (num & 0x00FF >> 0), (byte) ((num & 0xFF00) >> 8)};
(byte) ((num & 0xFF00) >> 8)
};
} }
public static public static
@ -287,25 +295,32 @@ public class LittleEndian {
return from(b[0], b[1]); return from(b[0], b[1]);
} }
private
UShort_() {
}
} }
/** INT to and from bytes */
/**
* INT to and from bytes
*/
public static final public static final
class Int_ { class Int_ {
private
Int_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
int from(byte[] bytes, int offset, int bytenum) { int from(byte[] bytes, int offset, int bytenum) {
int number = 0; int number = 0;
switch (bytenum) { switch (bytenum) {
case 4: number |= (bytes[offset+3] & 0xFF) << 24; case 4:
case 3: number |= (bytes[offset+2] & 0xFF) << 16; number |= (bytes[offset + 3] & 0xFF) << 24;
case 2: number |= (bytes[offset+1] & 0xFF) << 8; case 3:
case 1: number |= (bytes[offset+0] & 0xFF) << 0; number |= (bytes[offset + 2] & 0xFF) << 16;
case 2:
number |= (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 0] & 0xFF) << 0;
} }
return number; return number;
@ -317,10 +332,14 @@ public class LittleEndian {
int number = 0; int number = 0;
switch (bytes.length) { switch (bytes.length) {
case 4: number |= (bytes[3] & 0xFF) << 24; case 4:
case 3: number |= (bytes[2] & 0xFF) << 16; number |= (bytes[3] & 0xFF) << 24;
case 2: number |= (bytes[1] & 0xFF) << 8; case 3:
case 1: number |= (bytes[0] & 0xFF) << 0; number |= (bytes[2] & 0xFF) << 16;
case 2:
number |= (bytes[1] & 0xFF) << 8;
case 1:
number |= (bytes[0] & 0xFF) << 0;
} }
return number; return number;
@ -330,17 +349,13 @@ public class LittleEndian {
int from(byte b0, byte b1, byte b2, byte b3) { int from(byte b0, byte b1, byte b2, byte b3) {
return (b3 & 0xFF) << 24 | return (b3 & 0xFF) << 24 |
(b2 & 0xFF) << 16 | (b2 & 0xFF) << 16 |
(b1 & 0xFF) << 8 | (b1 & 0xFF) << 8 |
(b0 & 0xFF) << 0; (b0 & 0xFF) << 0;
} }
public static public static
byte[] toBytes(int x) { byte[] toBytes(int x) {
return new byte[] {(byte) (x >> 0), return new byte[] {(byte) (x >> 0), (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24)};
(byte) (x >> 8),
(byte) (x >> 16),
(byte) (x >> 24)
} ;
} }
public static public static
@ -357,25 +372,32 @@ public class LittleEndian {
return from(b[0], b[1], b[2], b[3]); return from(b[0], b[1], b[2], b[3]);
} }
private
Int_() {
}
} }
/** UNSIGNED INT to and from bytes */
/**
* UNSIGNED INT to and from bytes
*/
public static final public static final
class UInt_ { class UInt_ {
private
UInt_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
UInteger from(byte[] bytes, int offset, int bytenum) { UInteger from(byte[] bytes, int offset, int bytenum) {
int number = 0; int number = 0;
switch (bytenum) { switch (bytenum) {
case 4: number |= (bytes[offset+3] & 0xFF) << 24; case 4:
case 3: number |= (bytes[offset+2] & 0xFF) << 16; number |= (bytes[offset + 3] & 0xFF) << 24;
case 2: number |= (bytes[offset+1] & 0xFF) << 8; case 3:
case 1: number |= (bytes[offset+0] & 0xFF) << 0; number |= (bytes[offset + 2] & 0xFF) << 16;
case 2:
number |= (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (bytes[offset + 0] & 0xFF) << 0;
} }
return UInteger.valueOf(number); return UInteger.valueOf(number);
@ -387,20 +409,25 @@ public class LittleEndian {
int number = 0; int number = 0;
switch (bytes.length) { switch (bytes.length) {
case 4: number |= (bytes[3] & 0xFF) << 24; case 4:
case 3: number |= (bytes[2] & 0xFF) << 16; number |= (bytes[3] & 0xFF) << 24;
case 2: number |= (bytes[1] & 0xFF) << 8; case 3:
case 1: number |= (bytes[0] & 0xFF) << 0; number |= (bytes[2] & 0xFF) << 16;
case 2:
number |= (bytes[1] & 0xFF) << 8;
case 1:
number |= (bytes[0] & 0xFF) << 0;
} }
return UInteger.valueOf(number); return UInteger.valueOf(number);
} }
public static UInteger from(byte b0, byte b1, byte b2, byte b3) { public static
UInteger from(byte b0, byte b1, byte b2, byte b3) {
int number = (b3 & 0xFF) << 24 | int number = (b3 & 0xFF) << 24 |
(b2 & 0xFF) << 16 | (b2 & 0xFF) << 16 |
(b1 & 0xFF) << 8 | (b1 & 0xFF) << 8 |
(b0 & 0xFF) << 0; (b0 & 0xFF) << 0;
return UInteger.valueOf(number); return UInteger.valueOf(number);
} }
@ -409,11 +436,8 @@ public class LittleEndian {
byte[] toBytes(UInteger x) { byte[] toBytes(UInteger x) {
long num = x.longValue(); long num = x.longValue();
return new byte[] {(byte) (num & 0x000000FFL >> 0), return new byte[] {(byte) (num & 0x000000FFL >> 0), (byte) ((num & 0x0000FF00L) >> 8), (byte) ((num & 0x00FF0000L) >> 16),
(byte) ((num & 0x0000FF00L) >> 8), (byte) ((num & 0xFF000000L) >> 24)};
(byte) ((num & 0x00FF0000L) >> 16),
(byte) ((num & 0xFF000000L) >> 24)
};
} }
public static public static
@ -430,29 +454,40 @@ public class LittleEndian {
return from(b[0], b[1], b[2], b[3]); return from(b[0], b[1], b[2], b[3]);
} }
private
UInt_() {
}
} }
/** LONG to and from bytes */
/**
* LONG to and from bytes
*/
public static final public static final
class Long_ { class Long_ {
private
Long_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
long from(byte[] bytes, int offset, int bytenum) { long from(byte[] bytes, int offset, int bytenum) {
long number = 0; long number = 0;
switch (bytenum) { switch (bytenum) {
case 8: number |= (long) (bytes[offset+7] & 0xFF) << 56; case 8:
case 7: number |= (long) (bytes[offset+6] & 0xFF) << 48; number |= (long) (bytes[offset + 7] & 0xFF) << 56;
case 6: number |= (long) (bytes[offset+5] & 0xFF) << 40; case 7:
case 5: number |= (long) (bytes[offset+4] & 0xFF) << 32; number |= (long) (bytes[offset + 6] & 0xFF) << 48;
case 4: number |= (long) (bytes[offset+3] & 0xFF) << 24; case 6:
case 3: number |= (long) (bytes[offset+2] & 0xFF) << 16; number |= (long) (bytes[offset + 5] & 0xFF) << 40;
case 2: number |= (long) (bytes[offset+1] & 0xFF) << 8; case 5:
case 1: number |= (long) (bytes[offset+0] & 0xFF) << 0; number |= (long) (bytes[offset + 4] & 0xFF) << 32;
case 4:
number |= (long) (bytes[offset + 3] & 0xFF) << 24;
case 3:
number |= (long) (bytes[offset + 2] & 0xFF) << 16;
case 2:
number |= (long) (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (long) (bytes[offset + 0] & 0xFF) << 0;
} }
return number; return number;
@ -464,14 +499,22 @@ public class LittleEndian {
long number = 0L; long number = 0L;
switch (bytes.length) { switch (bytes.length) {
case 8: number |= (long) (bytes[7] & 0xFF) << 56; case 8:
case 7: number |= (long) (bytes[6] & 0xFF) << 48; number |= (long) (bytes[7] & 0xFF) << 56;
case 6: number |= (long) (bytes[5] & 0xFF) << 40; case 7:
case 5: number |= (long) (bytes[4] & 0xFF) << 32; number |= (long) (bytes[6] & 0xFF) << 48;
case 4: number |= (long) (bytes[3] & 0xFF) << 24; case 6:
case 3: number |= (long) (bytes[2] & 0xFF) << 16; number |= (long) (bytes[5] & 0xFF) << 40;
case 2: number |= (long) (bytes[1] & 0xFF) << 8; case 5:
case 1: number |= (long) (bytes[0] & 0xFF) << 0; number |= (long) (bytes[4] & 0xFF) << 32;
case 4:
number |= (long) (bytes[3] & 0xFF) << 24;
case 3:
number |= (long) (bytes[2] & 0xFF) << 16;
case 2:
number |= (long) (bytes[1] & 0xFF) << 8;
case 1:
number |= (long) (bytes[0] & 0xFF) << 0;
} }
return number; return number;
@ -485,21 +528,14 @@ public class LittleEndian {
(long) (b4 & 0xFF) << 32 | (long) (b4 & 0xFF) << 32 |
(long) (b3 & 0xFF) << 24 | (long) (b3 & 0xFF) << 24 |
(long) (b2 & 0xFF) << 16 | (long) (b2 & 0xFF) << 16 |
(long) (b1 & 0xFF) << 8 | (long) (b1 & 0xFF) << 8 |
(long) (b0 & 0xFF) << 0; (long) (b0 & 0xFF) << 0;
} }
public static public static
byte[] toBytes (long x) { byte[] toBytes(long x) {
return new byte[] {(byte) (x >> 0), return new byte[] {(byte) (x >> 0), (byte) (x >> 8), (byte) (x >> 16), (byte) (x >> 24), (byte) (x >> 32), (byte) (x >> 40),
(byte) (x >> 8), (byte) (x >> 48), (byte) (x >> 56),};
(byte) (x >> 16),
(byte) (x >> 24),
(byte) (x >> 32),
(byte) (x >> 40),
(byte) (x >> 48),
(byte) (x >> 56),
};
} }
public static public static
@ -516,29 +552,40 @@ public class LittleEndian {
return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]); return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
} }
private
Long_() {
}
} }
/** UNSIGNED LONG to and from bytes */
/**
* UNSIGNED LONG to and from bytes
*/
public static final public static final
class ULong_ { class ULong_ {
private
ULong_() {
}
@SuppressWarnings("fallthrough") @SuppressWarnings("fallthrough")
public static public static
ULong from(byte[] bytes, int offset, int bytenum) { ULong from(byte[] bytes, int offset, int bytenum) {
long number = 0; long number = 0;
switch (bytenum) { switch (bytenum) {
case 8: number |= (long) (bytes[offset+7] & 0xFF) << 56; case 8:
case 7: number |= (long) (bytes[offset+6] & 0xFF) << 48; number |= (long) (bytes[offset + 7] & 0xFF) << 56;
case 6: number |= (long) (bytes[offset+5] & 0xFF) << 40; case 7:
case 5: number |= (long) (bytes[offset+4] & 0xFF) << 32; number |= (long) (bytes[offset + 6] & 0xFF) << 48;
case 4: number |= (long) (bytes[offset+3] & 0xFF) << 24; case 6:
case 3: number |= (long) (bytes[offset+2] & 0xFF) << 16; number |= (long) (bytes[offset + 5] & 0xFF) << 40;
case 2: number |= (long) (bytes[offset+1] & 0xFF) << 8; case 5:
case 1: number |= (long) (bytes[offset+0] & 0xFF) << 0; number |= (long) (bytes[offset + 4] & 0xFF) << 32;
case 4:
number |= (long) (bytes[offset + 3] & 0xFF) << 24;
case 3:
number |= (long) (bytes[offset + 2] & 0xFF) << 16;
case 2:
number |= (long) (bytes[offset + 1] & 0xFF) << 8;
case 1:
number |= (long) (bytes[offset + 0] & 0xFF) << 0;
} }
return ULong.valueOf(number); return ULong.valueOf(number);
@ -558,18 +605,20 @@ public class LittleEndian {
} }
public static public static
byte[] toBytes (ULong x) { byte[] toBytes(ULong x) {
byte[] bytes = new byte[8]; byte[] bytes = new byte[8];
int offset = 0; int offset = 0;
byte temp_byte[] = x.toBigInteger().toByteArray(); byte temp_byte[] = x.toBigInteger()
int array_count = temp_byte.length-1; .toByteArray();
int array_count = temp_byte.length - 1;
for (int i=7;i>=0;i--) { for (int i = 7; i >= 0; i--) {
if (array_count >= 0) { if (array_count >= 0) {
bytes[offset] = temp_byte[array_count]; bytes[offset] = temp_byte[array_count];
} else { }
bytes[offset] = (byte)00; else {
bytes[offset] = (byte) 00;
} }
offset++; offset++;
@ -593,6 +642,10 @@ public class LittleEndian {
return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]); return from(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
} }
private
ULong_() {
}
} }
} }

View File

@ -12,6 +12,25 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
* Copyright (c) 2008, Nathan Sweet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
package dorkbox.util.bytes; package dorkbox.util.bytes;

View File

@ -12,6 +12,25 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
* Copyright (c) 2008, Nathan Sweet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
package dorkbox.util.bytes; package dorkbox.util.bytes;

View File

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright 2011 See AUTHORS file. * Copyright 2010 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,10 +19,10 @@
package dorkbox.util.collections; package dorkbox.util.collections;
import java.util.Arrays;
import dorkbox.util.MathUtils; import dorkbox.util.MathUtils;
import java.util.Arrays;
/** A resizable, ordered or unordered int array. Avoids the boxing that occurs with ArrayList<Integer>. If unordered, this class /** A resizable, ordered or unordered int array. Avoids the boxing that occurs with ArrayList<Integer>. If unordered, this class
* avoids a memory copy when removing elements (the last element is moved to the removed element's position). * avoids a memory copy when removing elements (the last element is moved to the removed element's position).
* @author Nathan Sweet */ * @author Nathan Sweet */
@ -381,4 +381,4 @@ public class IntArray {
} }
return buffer.toString(); return buffer.toString();
} }
} }

View File

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright 2011 See AUTHORS file. * Copyright 2010 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,11 +19,11 @@
package dorkbox.util.collections; package dorkbox.util.collections;
import dorkbox.util.MathUtils;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import dorkbox.util.MathUtils;
/** An unordered map that uses int keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small stash /** An unordered map that uses int keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small stash
* for problematic keys. Null values are allowed. No allocation is done except when growing the table size. <br> * for problematic keys. Null values are allowed. No allocation is done except when growing the table size. <br>
* <br> * <br>
@ -867,4 +867,4 @@ public class IntMap<V> {
return array; return array;
} }
} }
} }

View File

@ -1,5 +1,5 @@
/******************************************************************************* /*******************************************************************************
* Copyright 2011 See AUTHORS file. * Copyright 2010 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@ -24,15 +24,19 @@ import org.bouncycastle.jcajce.provider.util.DigestFactory;
import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.bc.BcContentSignerBuilder; import org.bouncycastle.operator.bc.BcContentSignerBuilder;
public class BcECDSAContentSignerBuilder extends BcContentSignerBuilder { public
class BcECDSAContentSignerBuilder extends BcContentSignerBuilder {
public BcECDSAContentSignerBuilder(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId) { public
BcECDSAContentSignerBuilder(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId) {
super(sigAlgId, digAlgId); super(sigAlgId, digAlgId);
} }
@Override @Override
protected Signer createSigner(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId) throws OperatorCreationException { protected
Digest digest = DigestFactory.getDigest(digAlgId.getAlgorithm().getId()); // SHA1, SHA512, etc Signer createSigner(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId) throws OperatorCreationException {
Digest digest = DigestFactory.getDigest(digAlgId.getAlgorithm()
.getId()); // SHA1, SHA512, etc
return new DSADigestSigner(new ECDSASigner(), digest); return new DSADigestSigner(new ECDSASigner(), digest);
} }

View File

@ -15,8 +15,6 @@
*/ */
package dorkbox.util.crypto.signers; package dorkbox.util.crypto.signers;
import java.io.IOException;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.Digest;
@ -31,22 +29,29 @@ import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder;
import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.bc.BcContentVerifierProviderBuilder; import org.bouncycastle.operator.bc.BcContentVerifierProviderBuilder;
public class BcECDSAContentVerifierProviderBuilder extends BcContentVerifierProviderBuilder { import java.io.IOException;
public
class BcECDSAContentVerifierProviderBuilder extends BcContentVerifierProviderBuilder {
@SuppressWarnings("unused") @SuppressWarnings("unused")
public BcECDSAContentVerifierProviderBuilder(DigestAlgorithmIdentifierFinder digestAlgorithmFinder) { public
BcECDSAContentVerifierProviderBuilder(DigestAlgorithmIdentifierFinder digestAlgorithmFinder) {
} }
@Override @Override
protected Signer createSigner(AlgorithmIdentifier sigAlgId) throws OperatorCreationException { protected
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter extractKeyParameters(SubjectPublicKeyInfo publicKeyInfo) throws IOException {
Digest digest = DigestFactory.getDigest(digAlgId.getAlgorithm().getId()); // 1.2.23.4.5.6, etc
return new DSADigestSigner(new ECDSASigner(), digest);
}
@Override
protected AsymmetricKeyParameter extractKeyParameters(SubjectPublicKeyInfo publicKeyInfo) throws IOException {
return PublicKeyFactory.createKey(publicKeyInfo); return PublicKeyFactory.createKey(publicKeyInfo);
} }
}
@Override
protected
Signer createSigner(AlgorithmIdentifier sigAlgId) throws OperatorCreationException {
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
Digest digest = DigestFactory.getDigest(digAlgId.getAlgorithm()
.getId()); // 1.2.23.4.5.6, etc
return new DSADigestSigner(new ECDSASigner(), digest);
}
}

View File

@ -1,3 +1,18 @@
/*
* Copyright 2014 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.database; package dorkbox.util.database;
import dorkbox.util.bytes.ByteArrayWrapper; import dorkbox.util.bytes.ByteArrayWrapper;

View File

@ -28,6 +28,4 @@ class DatabaseStorage {
public static final ByteArrayWrapper ADMIN_HASH = ByteArrayWrapper.wrap("adminHash"); public static final ByteArrayWrapper ADMIN_HASH = ByteArrayWrapper.wrap("adminHash");
public static final ByteArrayWrapper FILES = ByteArrayWrapper.wrap("files"); public static final ByteArrayWrapper FILES = ByteArrayWrapper.wrap("files");
public static final ByteArrayWrapper GENERIC = ByteArrayWrapper.wrap("generic"); public static final ByteArrayWrapper GENERIC = ByteArrayWrapper.wrap("generic");
} }

View File

@ -15,7 +15,7 @@
*/ */
package dorkbox.util.entropy; package dorkbox.util.entropy;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.util.exceptions.InitializationException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@ -0,0 +1,22 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.entropy;
public
interface EntropyProvider {
byte[] get(String messageForUser) throws Exception;
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.entropy;
import java.security.SecureRandom;
public
class SimpleEntropy implements EntropyProvider {
public static
Object create() {
return new SimpleEntropy();
}
@Override
public
byte[] get(String ignored) throws Exception {
System.err.println("Using simple entropy (SecureRandom) without input mixing.");
SecureRandom secureRandom = new SecureRandom();
byte[] rand = new byte[256];
secureRandom.nextBytes(rand);
return rand;
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.exceptions;
public
class InitializationException extends Exception {
private static final long serialVersionUID = 3331031046821855954L;
public
InitializationException() {
super();
}
public
InitializationException(String message, Throwable cause) {
super(message, cause);
}
public
InitializationException(String message) {
super(message);
}
public
InitializationException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.exceptions;
public
class NetException extends RuntimeException {
private static final long serialVersionUID = -3499720814336253695L;
public
NetException() {
super();
}
public
NetException(String message, Throwable cause) {
super(message, cause);
}
public
NetException(String message) {
super(message);
}
public
NetException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.exceptions;
public
class SecurityException extends Exception {
private static final long serialVersionUID = -1031633076501715224L;
public
SecurityException() {
super();
}
public
SecurityException(String message, Throwable cause) {
super(message, cause);
}
public
SecurityException(String message) {
super(message);
}
public
SecurityException(Throwable cause) {
super(cause);
}
}

View File

@ -23,20 +23,23 @@ import java.io.InputStreamReader;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class GwtSymbolMapParser { public
class GwtSymbolMapParser {
private final Map<String, String> symbolMap; private final Map<String, String> symbolMap;
public GwtSymbolMapParser() { public
GwtSymbolMapParser() {
this.symbolMap = new HashMap<String, String>(); this.symbolMap = new HashMap<String, String>();
} }
/** /**
* Efficiently parses the inputstream for symbolmap information. * Efficiently parses the inputstream for symbolmap information.
* <p> * <p/>
* Automatically closes the input stream when finished. * Automatically closes the input stream when finished.
*/ */
public void parse(InputStream inputStream) { public
void parse(InputStream inputStream) {
if (inputStream == null) { if (inputStream == null) {
return; return;
} }
@ -54,7 +57,8 @@ public class GwtSymbolMapParser {
if (CHAR != '\r' && CHAR != '\n') { if (CHAR != '\r' && CHAR != '\n') {
builder.append(CHAR); builder.append(CHAR);
} else { }
else {
processLine(builder.toString()); processLine(builder.toString());
// new line! // new line!
builder.delete(0, builder.capacity()); builder.delete(0, builder.capacity());
@ -70,11 +74,13 @@ public class GwtSymbolMapParser {
} }
} }
public Map<String, String> getSymbolMap() { public
Map<String, String> getSymbolMap() {
return this.symbolMap; return this.symbolMap;
} }
public void processLine(String line) { public
void processLine(String line) {
if (line.charAt(0) == '#') { if (line.charAt(0) == '#') {
return; return;
} }
@ -124,7 +130,8 @@ public class GwtSymbolMapParser {
// System.err.println(jsName + " : " + memberName + " : " + className); // System.err.println(jsName + " : " + memberName + " : " + className);
this.symbolMap.put(jsName, className); this.symbolMap.put(jsName, className);
} }
} else { }
else {
// version 2 // version 2
// The list has already been pruned, so always put everything into the symbol map // The list has already been pruned, so always put everything into the symbol map
this.symbolMap.put(symbolInfo[0], symbolInfo[1]); this.symbolMap.put(symbolInfo[0], symbolInfo[1]);

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.jna.linux; package dorkbox.util.jna.linux;
import com.sun.jna.*; import com.sun.jna.*;

View File

@ -1,6 +1,20 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.jna.linux; package dorkbox.util.jna.linux;
import com.sun.jna.Library; import com.sun.jna.Library;
import com.sun.jna.Native; import com.sun.jna.Native;
import com.sun.jna.Pointer; import com.sun.jna.Pointer;

View File

@ -1,6 +1,20 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.jna.linux; package dorkbox.util.jna.linux;
import com.sun.jna.*; import com.sun.jna.*;
import dorkbox.util.Keep; import dorkbox.util.Keep;
import dorkbox.util.jna.linux.Gtk.GdkEventButton; import dorkbox.util.jna.linux.Gtk.GdkEventButton;

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.jna.linux; package dorkbox.util.jna.linux;
import com.sun.jna.Library; import com.sun.jna.Library;

View File

@ -1,8 +1,22 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.jna.linux; package dorkbox.util.jna.linux;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
public public
class GtkSupport { class GtkSupport {
public static final boolean isSupported; public static final boolean isSupported;

View File

@ -1,8 +1,20 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.parallel; package dorkbox.util.parallel;
/**
*
*/
public public
interface ParallelCollector<T extends ParallelTask> { interface ParallelCollector<T extends ParallelTask> {
/** /**

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.parallel; package dorkbox.util.parallel;
import dorkbox.util.messagebus.common.thread.NamedThreadFactory; import dorkbox.util.messagebus.common.thread.NamedThreadFactory;
@ -10,9 +25,6 @@ import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/**
*
*/
public public
class ParallelProcessor<T extends ParallelTask> { class ParallelProcessor<T extends ParallelTask> {

View File

@ -1,3 +1,18 @@
/*
* Copyright 2015 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.parallel; package dorkbox.util.parallel;
public abstract public abstract

View File

@ -15,76 +15,153 @@
*/ */
package dorkbox.util.process; package dorkbox.util.process;
import dorkbox.util.FileUtil;
import dorkbox.util.OS;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import dorkbox.util.FileUtil;
import dorkbox.util.OS;
/** /**
* This will FORK the java process initially used to start the currently running JVM. Changing the java executable will change this behaviors * This will FORK the java process initially used to start the currently running JVM. Changing the java executable will change this behaviors
*/ */
public class JavaProcessBuilder extends ShellProcessBuilder { public
class JavaProcessBuilder extends ShellProcessBuilder {
/**
* The directory into which a local VM installation should be unpacked.
*/
public static final String LOCAL_JAVA_DIR = "java_vm";
/**
* Reconstructs the path to the JVM used to launch this process.
*
* @param windebug if true we will use java.exe instead of javaw.exe on Windows.
*/
public static
String getJVMPath(File appdir, boolean windebug) {
// first look in our application directory for an installed VM
String vmpath = checkJvmPath(new File(appdir, LOCAL_JAVA_DIR).getPath(), windebug);
// then fall back to the VM in which we're already running
if (vmpath == null) {
vmpath = checkJvmPath(System.getProperty("java.home"), windebug);
}
// then throw up our hands and hope for the best
if (vmpath == null) {
System.err.println("Unable to find java [appdir=" + appdir + ", java.home=" + System.getProperty("java.home") + "]!");
vmpath = "java";
}
// Oddly, the Mac OS X specific java flag -Xdock:name will only work if java is launched
// from /usr/bin/java, and not if launched by directly referring to <java.home>/bin/java,
// even though the former is a symlink to the latter! To work around this, see if the
// desired jvm is in fact pointed to by /usr/bin/java and, if so, use that instead.
if (OS.isMacOsX()) {
String localVM = FileUtil.normalize(new File("/usr/bin/java").getAbsolutePath());
String vmCheck = FileUtil.normalize(new File(vmpath).getAbsolutePath());
if (localVM.equals(vmCheck)) {
vmpath = "/usr/bin/java";
}
}
return vmpath;
}
/**
* Checks whether a Java Virtual Machine can be located in the supplied path.
*/
private static
String checkJvmPath(String vmhome, boolean windebug) {
// linux does this...
String vmbase = vmhome + File.separator + "bin" + File.separator;
String vmpath = vmbase + "java";
if (new File(vmpath).exists()) {
return vmpath;
}
// windows does this
if (!windebug) {
vmpath = vmbase + "javaw.exe";
}
else {
vmpath = vmbase + "java.exe"; // open a console on windows
}
if (new File(vmpath).exists()) {
return vmpath;
}
return null;
}
// this is NOT related to JAVA_HOME, but is instead the location of the JRE that was used to launch java initially. // this is NOT related to JAVA_HOME, but is instead the location of the JRE that was used to launch java initially.
private String javaLocation = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; private String javaLocation = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
private String mainClass; private String mainClass;
private int startingHeapSizeInMegabytes = 40; private int startingHeapSizeInMegabytes = 40;
private int maximumHeapSizeInMegabytes = 128; private int maximumHeapSizeInMegabytes = 128;
private List<String> jvmOptions = new ArrayList<String>(); private List<String> jvmOptions = new ArrayList<String>();
private List<String> classpathEntries = new ArrayList<String>(); private List<String> classpathEntries = new ArrayList<String>();
private List<String> mainClassArguments = new ArrayList<String>();
private String jarFile;
public JavaProcessBuilder() {
super(null, null, null);
}
// what version of java?? // what version of java??
// so, this starts a NEW java, from an ALREADY existing java. // so, this starts a NEW java, from an ALREADY existing java.
private List<String> mainClassArguments = new ArrayList<String>();
private String jarFile;
public JavaProcessBuilder(InputStream in, PrintStream out, PrintStream err) { public
JavaProcessBuilder() {
super(null, null, null);
}
public
JavaProcessBuilder(InputStream in, PrintStream out, PrintStream err) {
super(in, out, err); super(in, out, err);
} }
public final void setMainClass(String mainClass) { public final
void setMainClass(String mainClass) {
this.mainClass = mainClass; this.mainClass = mainClass;
} }
public final void setStartingHeapSizeInMegabytes(int startingHeapSizeInMegabytes) { public final
void setStartingHeapSizeInMegabytes(int startingHeapSizeInMegabytes) {
this.startingHeapSizeInMegabytes = startingHeapSizeInMegabytes; this.startingHeapSizeInMegabytes = startingHeapSizeInMegabytes;
} }
public final void setMaximumHeapSizeInMegabytes(int maximumHeapSizeInMegabytes) { public final
void setMaximumHeapSizeInMegabytes(int maximumHeapSizeInMegabytes) {
this.maximumHeapSizeInMegabytes = maximumHeapSizeInMegabytes; this.maximumHeapSizeInMegabytes = maximumHeapSizeInMegabytes;
} }
public final void addJvmClasspath(String classpathEntry) { public final
void addJvmClasspath(String classpathEntry) {
this.classpathEntries.add(classpathEntry); this.classpathEntries.add(classpathEntry);
} }
public final void addJvmClasspaths(List<String> paths) { public final
void addJvmClasspaths(List<String> paths) {
this.classpathEntries.addAll(paths); this.classpathEntries.addAll(paths);
} }
public final void addJvmOption(String argument) { public final
void addJvmOption(String argument) {
this.jvmOptions.add(argument); this.jvmOptions.add(argument);
} }
public final void addJvmOptions(List<String> paths) { public final
void addJvmOptions(List<String> paths) {
this.jvmOptions.addAll(paths); this.jvmOptions.addAll(paths);
} }
public final void setJarFile(String jarFile) { public final
void setJarFile(String jarFile) {
this.jarFile = jarFile; this.jarFile = jarFile;
} }
private String getClasspath() { private
String getClasspath() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
int count = 0; int count = 0;
final int totalSize = this.classpathEntries.size(); final int totalSize = this.classpathEntries.size();
@ -116,12 +193,14 @@ public class JavaProcessBuilder extends ShellProcessBuilder {
* Specify the JAVA exectuable to launch this process. By default, this will use the same java exectuable * Specify the JAVA exectuable to launch this process. By default, this will use the same java exectuable
* as was used to start the current JVM. * as was used to start the current JVM.
*/ */
public void setJava(String javaLocation) { public
void setJava(String javaLocation) {
this.javaLocation = javaLocation; this.javaLocation = javaLocation;
} }
@Override @Override
public void start() { public
void start() {
setExecutable(this.javaLocation); setExecutable(this.javaLocation);
// save off the original arguments // save off the original arguments
@ -165,7 +244,8 @@ public class JavaProcessBuilder extends ShellProcessBuilder {
// main class must happen AFTER the classpath! // main class must happen AFTER the classpath!
this.arguments.add(this.mainClass); this.arguments.add(this.mainClass);
} else { }
else {
System.err.println("WHOOPS. You must specify a jar or main class when running java!"); System.err.println("WHOOPS. You must specify a jar or main class when running java!");
System.exit(1); System.exit(1);
} }
@ -179,7 +259,8 @@ public class JavaProcessBuilder extends ShellProcessBuilder {
for (String s : split) { for (String s : split) {
this.arguments.add(s); this.arguments.add(s);
} }
} else { }
else {
this.arguments.add(arg); this.arguments.add(arg);
} }
} }
@ -188,69 +269,4 @@ public class JavaProcessBuilder extends ShellProcessBuilder {
super.start(); super.start();
} }
}
/** The directory into which a local VM installation should be unpacked. */
public static final String LOCAL_JAVA_DIR = "java_vm";
/**
* Reconstructs the path to the JVM used to launch this process.
*
* @param windebug if true we will use java.exe instead of javaw.exe on Windows.
*/
public static String getJVMPath (File appdir, boolean windebug)
{
// first look in our application directory for an installed VM
String vmpath = checkJvmPath(new File(appdir, LOCAL_JAVA_DIR).getPath(), windebug);
// then fall back to the VM in which we're already running
if (vmpath == null) {
vmpath = checkJvmPath(System.getProperty("java.home"), windebug);
}
// then throw up our hands and hope for the best
if (vmpath == null) {
System.err.println("Unable to find java [appdir=" + appdir + ", java.home=" + System.getProperty("java.home") + "]!");
vmpath = "java";
}
// Oddly, the Mac OS X specific java flag -Xdock:name will only work if java is launched
// from /usr/bin/java, and not if launched by directly referring to <java.home>/bin/java,
// even though the former is a symlink to the latter! To work around this, see if the
// desired jvm is in fact pointed to by /usr/bin/java and, if so, use that instead.
if (OS.isMacOsX()) {
String localVM = FileUtil.normalize(new File("/usr/bin/java").getAbsolutePath());
String vmCheck = FileUtil.normalize(new File(vmpath).getAbsolutePath());
if (localVM.equals(vmCheck)) {
vmpath = "/usr/bin/java";
}
}
return vmpath;
}
/**
* Checks whether a Java Virtual Machine can be located in the supplied path.
*/
private static String checkJvmPath(String vmhome, boolean windebug) {
// linux does this...
String vmbase = vmhome + File.separator + "bin" + File.separator;
String vmpath = vmbase + "java";
if (new File(vmpath).exists()) {
return vmpath;
}
// windows does this
if (!windebug) {
vmpath = vmbase + "javaw.exe";
} else {
vmpath = vmbase + "java.exe"; // open a console on windows
}
if (new File(vmpath).exists()) {
return vmpath;
}
return null;
}
}

View File

@ -15,15 +15,16 @@
*/ */
package dorkbox.util.process; package dorkbox.util.process;
import dorkbox.util.OS;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import dorkbox.util.OS; public
class LauncherProcessBuilder extends ShellProcessBuilder {
public class LauncherProcessBuilder extends ShellProcessBuilder {
private String mainClass; private String mainClass;
@ -32,31 +33,38 @@ public class LauncherProcessBuilder extends ShellProcessBuilder {
private String jarFile; private String jarFile;
public LauncherProcessBuilder() { public
LauncherProcessBuilder() {
super(null, null, null); super(null, null, null);
} }
public LauncherProcessBuilder(InputStream in, PrintStream out, PrintStream err) { public
LauncherProcessBuilder(InputStream in, PrintStream out, PrintStream err) {
super(in, out, err); super(in, out, err);
} }
public final void setMainClass(String mainClass) { public final
void setMainClass(String mainClass) {
this.mainClass = mainClass; this.mainClass = mainClass;
} }
public final void addJvmClasspath(String classpathEntry) { public final
void addJvmClasspath(String classpathEntry) {
this.classpathEntries.add(classpathEntry); this.classpathEntries.add(classpathEntry);
} }
public final void addJvmClasspaths(List<String> paths) { public final
void addJvmClasspaths(List<String> paths) {
this.classpathEntries.addAll(paths); this.classpathEntries.addAll(paths);
} }
public final void setJarFile(String jarFile) { public final
void setJarFile(String jarFile) {
this.jarFile = jarFile; this.jarFile = jarFile;
} }
private String getClasspath() { private
String getClasspath() {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
int count = 0; int count = 0;
final int totalSize = this.classpathEntries.size(); final int totalSize = this.classpathEntries.size();
@ -75,10 +83,12 @@ public class LauncherProcessBuilder extends ShellProcessBuilder {
} }
@Override @Override
public void start() { public
void start() {
if (OS.isWindows()) { if (OS.isWindows()) {
setExecutable("dorkboxc.exe"); setExecutable("dorkboxc.exe");
} else { }
else {
setExecutable("dorkbox"); setExecutable("dorkbox");
} }
@ -120,7 +130,8 @@ public class LauncherProcessBuilder extends ShellProcessBuilder {
this.arguments.add("-classpath"); this.arguments.add("-classpath");
this.arguments.add(classpath); this.arguments.add(classpath);
} }
} else { }
else {
System.err.println("WHOOPS. You must specify a jar or main class when running java!"); System.err.println("WHOOPS. You must specify a jar or main class when running java!");
System.exit(1); System.exit(1);
} }
@ -134,7 +145,8 @@ public class LauncherProcessBuilder extends ShellProcessBuilder {
for (String s : split) { for (String s : split) {
this.arguments.add(s); this.arguments.add(s);
} }
} else { }
else {
this.arguments.add(arg); this.arguments.add(arg);
} }
} }
@ -143,4 +155,4 @@ public class LauncherProcessBuilder extends ShellProcessBuilder {
super.start(); super.start();
} }
} }

View File

@ -18,24 +18,29 @@ package dorkbox.util.process;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
public class NullOutputStream extends OutputStream { public
class NullOutputStream extends OutputStream {
@Override @Override
public void write(int i) throws IOException { public
void write(int i) throws IOException {
//do nothing //do nothing
} }
@Override @Override
public void write(byte[] b) throws IOException { public
void write(byte[] b) throws IOException {
//do nothing //do nothing
} }
@Override @Override
public void write(byte[] b, int off, int len) throws IOException { public
void write(byte[] b, int off, int len) throws IOException {
//do nothing //do nothing
} }
@Override @Override
public void flush() throws IOException { public
void flush() throws IOException {
//do nothing //do nothing
} }
} }

View File

@ -19,13 +19,15 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
public class ProcessProxy extends Thread { public
class ProcessProxy extends Thread {
private final InputStream is; private final InputStream is;
private final OutputStream os; private final OutputStream os;
// when reading from the stdin and outputting to the process // when reading from the stdin and outputting to the process
public ProcessProxy(String processName, InputStream inputStreamFromConsole, OutputStream outputStreamToProcess) { public
ProcessProxy(String processName, InputStream inputStreamFromConsole, OutputStream outputStreamToProcess) {
this.is = inputStreamFromConsole; this.is = inputStreamFromConsole;
this.os = outputStreamToProcess; this.os = outputStreamToProcess;
@ -33,7 +35,8 @@ public class ProcessProxy extends Thread {
setDaemon(true); setDaemon(true);
} }
public void close() { public
void close() {
try { try {
this.is.close(); this.is.close();
} catch (IOException e) { } catch (IOException e) {
@ -41,7 +44,8 @@ public class ProcessProxy extends Thread {
} }
@Override @Override
public void run() { public
void run() {
try { try {
// this thread will read until there is no more data to read. (this is generally what you want) // this thread will read until there is no more data to read. (this is generally what you want)
// the stream will be closed when the process closes it (usually on exit) // the stream will be closed when the process closes it (usually on exit)
@ -51,7 +55,8 @@ public class ProcessProxy extends Thread {
// just read so it won't block. // just read so it won't block.
while ((readInt = this.is.read()) != -1) { while ((readInt = this.is.read()) != -1) {
} }
} else { }
else {
while ((readInt = this.is.read()) != -1) { while ((readInt = this.is.read()) != -1) {
this.os.write(readInt); this.os.write(readInt);
// always flush // always flush
@ -70,4 +75,4 @@ public class ProcessProxy extends Thread {
} }
} }
} }
} }

View File

@ -15,6 +15,8 @@
*/ */
package dorkbox.util.process; package dorkbox.util.process;
import dorkbox.util.OS;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.io.PrintStream; import java.io.PrintStream;
@ -22,27 +24,23 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import dorkbox.util.OS;
/** /**
* If you want to save off the output from the process, set a PrintStream to the following: * If you want to save off the output from the process, set a PrintStream to the following:
* ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(8196); * ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(8196);
* PrintStream outputStream = new PrintStream(byteArrayOutputStream); * PrintStream outputStream = new PrintStream(byteArrayOutputStream);
* ... * ...
* String output = byteArrayOutputStream.toString(); * String output = byteArrayOutputStream.toString();
*/ */
public class ShellProcessBuilder { public
class ShellProcessBuilder {
private String workingDirectory = null;
private String executableName = null;
private String executableDirectory = null;
protected List<String> arguments = new ArrayList<String>();
private final PrintStream outputStream; private final PrintStream outputStream;
private final PrintStream errorStream; private final PrintStream errorStream;
private final InputStream inputStream; private final InputStream inputStream;
protected List<String> arguments = new ArrayList<String>();
private String workingDirectory = null;
private String executableName = null;
private String executableDirectory = null;
private Process process = null; private Process process = null;
// true if we want to save off (usually for debugging) the initial output from this // true if we want to save off (usually for debugging) the initial output from this
@ -51,19 +49,23 @@ public class ShellProcessBuilder {
/** /**
* This will cause the spawned process to pipe it's output to null. * This will cause the spawned process to pipe it's output to null.
*/ */
public ShellProcessBuilder() { public
ShellProcessBuilder() {
this(null, null, null); this(null, null, null);
} }
public ShellProcessBuilder(PrintStream out) { public
ShellProcessBuilder(PrintStream out) {
this(null, out, out); this(null, out, out);
} }
public ShellProcessBuilder(InputStream in, PrintStream out) { public
ShellProcessBuilder(InputStream in, PrintStream out) {
this(in, out, out); this(in, out, out);
} }
public ShellProcessBuilder(InputStream in, PrintStream out, PrintStream err) { public
ShellProcessBuilder(InputStream in, PrintStream out, PrintStream err) {
this.outputStream = out; this.outputStream = out;
this.errorStream = err; this.errorStream = err;
this.inputStream = in; this.inputStream = in;
@ -72,47 +74,55 @@ public class ShellProcessBuilder {
/** /**
* When launched from eclipse, the working directory is USUALLY the root of the project folder * When launched from eclipse, the working directory is USUALLY the root of the project folder
*/ */
public final ShellProcessBuilder setWorkingDirectory(String workingDirectory) { public final
ShellProcessBuilder setWorkingDirectory(String workingDirectory) {
// MUST be absolute path!! // MUST be absolute path!!
this.workingDirectory = new File(workingDirectory).getAbsolutePath(); this.workingDirectory = new File(workingDirectory).getAbsolutePath();
return this; return this;
} }
public final ShellProcessBuilder addArgument(String argument) { public final
ShellProcessBuilder addArgument(String argument) {
this.arguments.add(argument); this.arguments.add(argument);
return this; return this;
} }
public final ShellProcessBuilder addArguments(String... paths) { public final
ShellProcessBuilder addArguments(String... paths) {
for (String path : paths) { for (String path : paths) {
this.arguments.add(path); this.arguments.add(path);
} }
return this; return this;
} }
public final ShellProcessBuilder addArguments(List<String> paths) { public final
ShellProcessBuilder addArguments(List<String> paths) {
this.arguments.addAll(paths); this.arguments.addAll(paths);
return this; return this;
} }
public final ShellProcessBuilder setExecutable(String executableName) { public final
ShellProcessBuilder setExecutable(String executableName) {
this.executableName = executableName; this.executableName = executableName;
return this; return this;
} }
public ShellProcessBuilder setExecutableDirectory(String executableDirectory) { public
ShellProcessBuilder setExecutableDirectory(String executableDirectory) {
// MUST be absolute path!! // MUST be absolute path!!
this.executableDirectory = new File(executableDirectory).getAbsolutePath(); this.executableDirectory = new File(executableDirectory).getAbsolutePath();
return this; return this;
} }
public ShellProcessBuilder addDebugInfo() { public
ShellProcessBuilder addDebugInfo() {
this.debugInfo = true; this.debugInfo = true;
return this; return this;
} }
public void start() { public
void start() {
// if no executable, then use the command shell // if no executable, then use the command shell
if (this.executableName == null) { if (this.executableName == null) {
if (OS.isWindows()) { if (OS.isWindows()) {
@ -120,7 +130,8 @@ public class ShellProcessBuilder {
this.executableName = "cmd"; this.executableName = "cmd";
this.arguments.add(0, "/c"); this.arguments.add(0, "/c");
} else { }
else {
// *nix // *nix
this.executableName = "/bin/bash"; this.executableName = "/bin/bash";
File file = new File(this.executableName); File file = new File(this.executableName);
@ -129,7 +140,8 @@ public class ShellProcessBuilder {
} }
this.arguments.add(0, "-c"); this.arguments.add(0, "-c");
} }
} else if (this.workingDirectory != null) { }
else if (this.workingDirectory != null) {
if (!this.workingDirectory.endsWith("/") && !this.workingDirectory.endsWith("\\")) { if (!this.workingDirectory.endsWith("/") && !this.workingDirectory.endsWith("\\")) {
this.workingDirectory += File.separator; this.workingDirectory += File.separator;
} }
@ -154,7 +166,8 @@ public class ShellProcessBuilder {
for (String s : split) { for (String s : split) {
argumentsList.add(s); argumentsList.add(s);
} }
} else { }
else {
argumentsList.add(arg); argumentsList.add(arg);
} }
} }
@ -167,7 +180,8 @@ public class ShellProcessBuilder {
if (OS.isWindows()) { if (OS.isWindows()) {
// >NUL on windows // >NUL on windows
argumentsList.add(">NUL"); argumentsList.add(">NUL");
} else { }
else {
// we will "pipe" it to /dev/null on *nix // we will "pipe" it to /dev/null on *nix
argumentsList.add(">/dev/null 2>&1"); argumentsList.add(">/dev/null 2>&1");
} }
@ -226,7 +240,9 @@ public class ShellProcessBuilder {
// readers (read process -> write console) // readers (read process -> write console)
// have to keep the output buffers from filling in the target process. // have to keep the output buffers from filling in the target process.
readFromProcess_output = new ProcessProxy("Process Reader: " + this.executableName, this.process.getInputStream(), nullOutputStream); readFromProcess_output = new ProcessProxy("Process Reader: " + this.executableName,
this.process.getInputStream(),
nullOutputStream);
readFromProcess_error = null; readFromProcess_error = null;
} }
// we want to pipe our input/output from process to ourselves // we want to pipe our input/output from process to ourselves
@ -236,10 +252,15 @@ public class ShellProcessBuilder {
* to the user's window. This is important or the spawned process could block. * to the user's window. This is important or the spawned process could block.
*/ */
// readers (read process -> write console) // readers (read process -> write console)
readFromProcess_output = new ProcessProxy("Process Reader: " + this.executableName, this.process.getInputStream(), this.outputStream); readFromProcess_output = new ProcessProxy("Process Reader: " + this.executableName,
this.process.getInputStream(),
this.outputStream);
if (this.errorStream != this.outputStream) { if (this.errorStream != this.outputStream) {
readFromProcess_error = new ProcessProxy("Process Reader: " + this.executableName, this.process.getErrorStream(), this.errorStream); readFromProcess_error = new ProcessProxy("Process Reader: " + this.executableName,
} else { this.process.getErrorStream(),
this.errorStream);
}
else {
processBuilder.redirectErrorStream(true); processBuilder.redirectErrorStream(true);
readFromProcess_error = null; readFromProcess_error = null;
} }
@ -250,8 +271,11 @@ public class ShellProcessBuilder {
* Proxy System.in from the user's window to the spawned process * Proxy System.in from the user's window to the spawned process
*/ */
// writer (read console -> write process) // writer (read console -> write process)
writeToProcess_input = new ProcessProxy("Process Writer: " + this.executableName, this.inputStream, this.process.getOutputStream()); writeToProcess_input = new ProcessProxy("Process Writer: " + this.executableName,
} else { this.inputStream,
this.process.getOutputStream());
}
else {
writeToProcess_input = null; writeToProcess_input = null;
} }
@ -260,17 +284,18 @@ public class ShellProcessBuilder {
// If not in eclipse, by this shutdown hook. (clicking the red square to terminate a process will not run it's shutdown hooks) // If not in eclipse, by this shutdown hook. (clicking the red square to terminate a process will not run it's shutdown hooks)
// Typing "exit" will always terminate the process // Typing "exit" will always terminate the process
Thread hook = new Thread(new Runnable() { Thread hook = new Thread(new Runnable() {
@Override @Override
public void run() { public
if (ShellProcessBuilder.this.debugInfo) { void run() {
ShellProcessBuilder.this.errorStream.println("Terminating process: " + ShellProcessBuilder.this.executableName); if (ShellProcessBuilder.this.debugInfo) {
} ShellProcessBuilder.this.errorStream.println("Terminating process: " + ShellProcessBuilder.this.executableName);
ShellProcessBuilder.this.process.destroy();
} }
ShellProcessBuilder.this.process.destroy();
} }
); });
// add a shutdown hook to make sure that we properly terminate our spawned processes. // add a shutdown hook to make sure that we properly terminate our spawned processes.
Runtime.getRuntime().addShutdownHook(hook); Runtime.getRuntime()
.addShutdownHook(hook);
if (writeToProcess_input != null) { if (writeToProcess_input != null) {
writeToProcess_input.start(); writeToProcess_input.start();
@ -304,11 +329,13 @@ public class ShellProcessBuilder {
// this is for cleanup ONLY, not to actually do anything. // this is for cleanup ONLY, not to actually do anything.
this.process.destroy(); this.process.destroy();
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread()
.interrupt();
} }
// remove the shutdown hook now that we've shutdown. // remove the shutdown hook now that we've shutdown.
Runtime.getRuntime().removeShutdownHook(hook); Runtime.getRuntime()
.removeShutdownHook(hook);
} }
} }
} }

View File

@ -15,23 +15,19 @@
*/ */
package dorkbox.util.properties; package dorkbox.util.properties;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import dorkbox.util.FileUtil; import dorkbox.util.FileUtil;
import java.awt.*;
import java.io.*;
import java.util.Properties;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public public
class PropertiesProvider { class PropertiesProvider {
private String comments = "Settings and configuration file. Strings must be escape formatted!";
private final Properties properties = new SortedProperties(); private final Properties properties = new SortedProperties();
private final File propertiesFile; private final File propertiesFile;
private String comments = "Settings and configuration file. Strings must be escape formatted!";
public public
PropertiesProvider(String propertiesFile) { PropertiesProvider(String propertiesFile) {

View File

@ -15,28 +15,29 @@
*/ */
package dorkbox.util.properties; package dorkbox.util.properties;
import java.util.Collections; import java.util.*;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
public class SortedProperties extends Properties { public
class SortedProperties extends Properties {
private static final long serialVersionUID = 3988064683926999433L; private static final long serialVersionUID = 3988064683926999433L;
private final Comparator<Object> compare = new Comparator<Object>() { private final Comparator<Object> compare = new Comparator<Object>() {
@Override @Override
public int compare(Object o1, Object o2) { public
return o1.toString().compareTo(o2.toString()); int compare(Object o1, Object o2) {
}}; return o1.toString()
.compareTo(o2.toString());
}
};
@Override @Override
public synchronized Enumeration<Object> keys() { public synchronized
Enumeration<Object> keys() {
Enumeration<Object> keysEnum = super.keys(); Enumeration<Object> keysEnum = super.keys();
Vector<Object> vector = new Vector<Object>(size()); Vector<Object> vector = new Vector<Object>(size());
for (;keysEnum.hasMoreElements();) { for (; keysEnum.hasMoreElements(); ) {
vector.add(keysEnum.nextElement()); vector.add(keysEnum.nextElement());
} }

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
* *
*/ */
package dorkbox.util.serializers; package dorkbox.util.serialization;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.lang.reflect.Field; import java.lang.reflect.Field;

View File

@ -1,8 +1,24 @@
package dorkbox.util.crypto.serialization; /*
* Copyright 2010 dorkbox, llc
*
import java.math.BigInteger; * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.ec.CustomNamedCurves; import org.bouncycastle.crypto.ec.CustomNamedCurves;
@ -12,22 +28,16 @@ import org.bouncycastle.math.ec.ECAccessor;
import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.math.ec.ECPoint;
import com.esotericsoftware.kryo.Kryo; import java.math.BigInteger;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/** /**
* Only public keys are ever sent across the wire. * Only public keys are ever sent across the wire.
*/ */
public class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters> { public
class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters> {
@Override public static
public void write(Kryo kryo, Output output, ECPrivateKeyParameters key) { void write(Output output, ECPrivateKeyParameters key) {
write(output, key);
}
public static void write(Output output, ECPrivateKeyParameters key) {
byte[] bytes; byte[] bytes;
int length; int length;
@ -51,19 +61,15 @@ public class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters>
serializeECPoint(g, output); serializeECPoint(g, output);
///////////// /////////////
bytes = key.getD().toByteArray(); bytes = key.getD()
.toByteArray();
length = bytes.length; length = bytes.length;
output.writeInt(length, true); output.writeInt(length, true);
output.writeBytes(bytes, 0, length); output.writeBytes(bytes, 0, length);
} }
@SuppressWarnings("rawtypes") public static
@Override ECPrivateKeyParameters read(Input input) {
public ECPrivateKeyParameters read(Kryo kryo, Input input, Class type) {
return read(input);
}
public static ECPrivateKeyParameters read(Input input) {
byte[] bytes; byte[] bytes;
int length; int length;
@ -98,11 +104,13 @@ public class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters>
return new ECPrivateKeyParameters(D, ecDomainParameters); return new ECPrivateKeyParameters(D, ecDomainParameters);
} }
static void serializeCurve(Output output, ECCurve curve) { static
void serializeCurve(Output output, ECCurve curve) {
byte[] bytes; byte[] bytes;
int length; int length;
// save out if it's a NAMED curve, or a UN-NAMED curve. If it is named, we can do less work. // save out if it's a NAMED curve, or a UN-NAMED curve. If it is named, we can do less work.
String curveName = curve.getClass().getSimpleName(); String curveName = curve.getClass()
.getSimpleName();
if (curveName.endsWith("Curve")) { if (curveName.endsWith("Curve")) {
String cleanedName = curveName.substring(0, curveName.indexOf("Curve")); String cleanedName = curveName.substring(0, curveName.indexOf("Curve"));
@ -121,11 +129,14 @@ public class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters>
// we have to serialize the ENTIRE curve. // we have to serialize the ENTIRE curve.
if (curveName == null) { if (curveName == null) {
// save out the curve info // save out the curve info
BigInteger a = curve.getA().toBigInteger(); BigInteger a = curve.getA()
BigInteger b = curve.getB().toBigInteger(); .toBigInteger();
BigInteger b = curve.getB()
.toBigInteger();
BigInteger order = curve.getOrder(); BigInteger order = curve.getOrder();
BigInteger cofactor = curve.getCofactor(); BigInteger cofactor = curve.getCofactor();
BigInteger q = curve.getField().getCharacteristic(); BigInteger q = curve.getField()
.getCharacteristic();
///////////// /////////////
bytes = a.toByteArray(); bytes = a.toByteArray();
@ -166,7 +177,8 @@ public class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters>
} }
} }
static ECCurve deserializeCurve(Input input) { static
ECCurve deserializeCurve(Input input) {
byte[] bytes; byte[] bytes;
int length; int length;
@ -221,15 +233,18 @@ public class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters>
return curve; return curve;
} }
static void serializeECPoint(ECPoint point, Output output) { static
void serializeECPoint(ECPoint point, Output output) {
if (point.isInfinity()) { if (point.isInfinity()) {
return; return;
} }
ECPoint normed = point.normalize(); ECPoint normed = point.normalize();
byte[] X = normed.getXCoord().getEncoded(); byte[] X = normed.getXCoord()
byte[] Y = normed.getYCoord().getEncoded(); .getEncoded();
byte[] Y = normed.getYCoord()
.getEncoded();
int length = 1 + X.length + Y.length; int length = 1 + X.length + Y.length;
output.writeInt(length, true); output.writeInt(length, true);
@ -238,4 +253,17 @@ public class EccPrivateKeySerializer extends Serializer<ECPrivateKeyParameters>
output.write(X); output.write(X);
output.write(Y); output.write(Y);
} }
@Override
public
void write(Kryo kryo, Output output, ECPrivateKeyParameters key) {
write(output, key);
}
@SuppressWarnings("rawtypes")
@Override
public
ECPrivateKeyParameters read(Kryo kryo, Input input, Class type) {
return read(input);
}
} }

View File

@ -1,5 +1,19 @@
package dorkbox.util.crypto.serialization; /*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.Serializer;
@ -18,12 +32,6 @@ import java.math.BigInteger;
public public
class EccPublicKeySerializer extends Serializer<ECPublicKeyParameters> { class EccPublicKeySerializer extends Serializer<ECPublicKeyParameters> {
@Override
public
void write(Kryo kryo, Output output, ECPublicKeyParameters key) {
write(output, key);
}
public static public static
void write(Output output, ECPublicKeyParameters key) { void write(Output output, ECPublicKeyParameters key) {
byte[] bytes; byte[] bytes;
@ -50,13 +58,6 @@ class EccPublicKeySerializer extends Serializer<ECPublicKeyParameters> {
EccPrivateKeySerializer.serializeECPoint(key.getQ(), output); EccPrivateKeySerializer.serializeECPoint(key.getQ(), output);
} }
@SuppressWarnings("rawtypes")
@Override
public
ECPublicKeyParameters read(Kryo kryo, Input input, Class type) {
return read(input);
}
public static public static
ECPublicKeyParameters read(Input input) { ECPublicKeyParameters read(Input input) {
byte[] bytes; byte[] bytes;
@ -93,4 +94,17 @@ class EccPublicKeySerializer extends Serializer<ECPublicKeyParameters> {
return new ECPublicKeyParameters(Q, ecDomainParameters); return new ECPublicKeyParameters(Q, ecDomainParameters);
} }
@Override
public
void write(Kryo kryo, Output output, ECPublicKeyParameters key) {
write(output, key);
}
@SuppressWarnings("rawtypes")
@Override
public
ECPublicKeyParameters read(Kryo kryo, Input input, Class type) {
return read(input);
}
} }

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
* *
*/ */
package dorkbox.util.serializers; package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.Serializer;

View File

@ -1,11 +1,25 @@
package dorkbox.util.crypto.serialization; /*
* Copyright 2010 dorkbox, llc
import org.bouncycastle.crypto.params.IESParameters; *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.io.Output;
import org.bouncycastle.crypto.params.IESParameters;
/** /**
* Only public keys are ever sent across the wire. * Only public keys are ever sent across the wire.

View File

@ -1,11 +1,25 @@
package dorkbox.util.crypto.serialization; /*
* Copyright 2010 dorkbox, llc
import org.bouncycastle.crypto.params.IESWithCipherParameters; *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.io.Output;
import org.bouncycastle.crypto.params.IESWithCipherParameters;
/** /**
* Only public keys are ever sent across the wire. * Only public keys are ever sent across the wire.

View File

@ -0,0 +1,29 @@
/*
* Copyright 2010 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.serialization;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to identify fields that kryo should ignore when configured with the FieldAnnotationAwareSerializer
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public
@interface IgnoreSerialization {}

View File

@ -1,13 +1,27 @@
package dorkbox.util.crypto.serialization; /*
* Copyright 2010 dorkbox, llc
import java.math.BigInteger; *
* Licensed under the Apache License, Version 2.0 (the "License");
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.io.Output;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import java.math.BigInteger;
/** /**
* Only public keys are ever sent across the wire. * Only public keys are ever sent across the wire.

View File

@ -1,13 +1,27 @@
package dorkbox.util.crypto.serialization; /*
* Copyright 2010 dorkbox, llc
import java.math.BigInteger; *
* Licensed under the Apache License, Version 2.0 (the "License");
import org.bouncycastle.crypto.params.RSAKeyParameters; * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.io.Output;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import java.math.BigInteger;
/** /**
* Only public keys are ever sent across the wire. * Only public keys are ever sent across the wire.

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
* *
*/ */
package dorkbox.util.serializers; package dorkbox.util.serialization;
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.Serializer;

View File

@ -1,3 +1,18 @@
/*
* Copyright 2014 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.storage; package dorkbox.util.storage;
import dorkbox.util.bytes.ByteArrayWrapper; import dorkbox.util.bytes.ByteArrayWrapper;

View File

@ -1,3 +1,18 @@
/*
* Copyright 2014 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.storage; package dorkbox.util.storage;
import dorkbox.util.bytes.ByteArrayWrapper; import dorkbox.util.bytes.ByteArrayWrapper;

View File

@ -1,16 +1,30 @@
/*
* Copyright 2014 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.storage; package dorkbox.util.storage;
import dorkbox.util.SerializationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dorkbox.util.SerializationManager;
public public
class Store { class Store {
private static final Logger logger = LoggerFactory.getLogger(DiskStorage.class); private static final Logger logger = LoggerFactory.getLogger(DiskStorage.class);

View File

@ -38,10 +38,10 @@ import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.io.Output;
import dorkbox.util.crypto.serialization.EccPrivateKeySerializer; import dorkbox.util.serialization.EccPrivateKeySerializer;
import dorkbox.util.crypto.serialization.EccPublicKeySerializer; import dorkbox.util.serialization.EccPublicKeySerializer;
import dorkbox.util.crypto.serialization.IesParametersSerializer; import dorkbox.util.serialization.IesParametersSerializer;
import dorkbox.util.crypto.serialization.IesWithCipherParametersSerializer; import dorkbox.util.serialization.IesWithCipherParametersSerializer;
public class EccTest { public class EccTest {

View File

@ -26,8 +26,8 @@ import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.io.Output;
import dorkbox.util.crypto.serialization.RsaPrivateKeySerializer; import dorkbox.util.serialization.RsaPrivateKeySerializer;
import dorkbox.util.crypto.serialization.RsaPublicKeySerializer; import dorkbox.util.serialization.RsaPublicKeySerializer;
public class RsaTest { public class RsaTest {