repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
vbauer/caesar
src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try { final SimpleAsync proxy = createProxy(executor); Assert.assertEquals(SimpleSync.TIMEOUT_VALUE, proxy.timeout().get()); } finally { executor.shutdown(); } } @Test(expected = UnsupportedTimeoutException.class) public void testBadExecutorService() throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(1); try { final SimpleAsync proxy = createProxy(executor); Assert.fail(String.valueOf(proxy.timeout().get())); } finally { executor.shutdown(); } } private SimpleAsync createProxy(final ExecutorService executor) { final SimpleSync bean = new SimpleSync(1);
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/UnsupportedTimeoutException.java // @SuppressWarnings("serial") // public class UnsupportedTimeoutException extends AbstractCaesarException { // // private final Executor executor; // // // public UnsupportedTimeoutException(final Executor executor) { // this.executor = executor; // } // // // public Executor getExecutor() { // return executor; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "%s does not support timeouts. Use %s.", // getExecutor(), ScheduledExecutorService.class // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java // public final class AsyncProxyCreator { // // private AsyncProxyCreator() { // throw new UnsupportedOperationException(); // } // // // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor // ) { // return create(bean, asyncInterface, executor, true); // } // // @SuppressWarnings("unchecked") // public static <SYNC, ASYNC> ASYNC create( // final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate // ) { // final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); // final Class<?> beanClass = bean.getClass(); // final ClassLoader classLoader = beanClass.getClassLoader(); // final Class<?>[] interfaces = { // asyncInterface, // }; // // final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); // return validate ? validate(proxy, handler) : proxy; // } // // // private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { // final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); // final Method[] methods = targetClass.getDeclaredMethods(); // // for (final Method method : methods) { // final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); // if (runner == null) { // throw new MissedSyncMethodException(method); // } // } // // return proxy; // } // // } // Path: src/test/java/com/github/vbauer/caesar/annotation/TimeoutAnnotationTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.exception.UnsupportedTimeoutException; import com.github.vbauer.caesar.proxy.AsyncProxyCreator; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.annotation; /** * @author Vladislav Bauer */ public class TimeoutAnnotationTest extends BasicTest { @Test public void testGoodExecutorService() throws Exception { final ExecutorService executor = Executors.newScheduledThreadPool(1); try { final SimpleAsync proxy = createProxy(executor); Assert.assertEquals(SimpleSync.TIMEOUT_VALUE, proxy.timeout().get()); } finally { executor.shutdown(); } } @Test(expected = UnsupportedTimeoutException.class) public void testBadExecutorService() throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(1); try { final SimpleAsync proxy = createProxy(executor); Assert.fail(String.valueOf(proxy.timeout().get())); } finally { executor.shutdown(); } } private SimpleAsync createProxy(final ExecutorService executor) { final SimpleSync bean = new SimpleSync(1);
return AsyncProxyCreator.create(bean, SimpleAsync.class, executor);
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java // public class AsyncCallbackAdapter<T> implements AsyncCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable caught) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.callback.AsyncCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer;
package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ public class AsyncCallbackMethodRunnerTest extends BasicRunnerTest { @Test public void testTimeout() throws Throwable { check( callback -> getCallbackAsync().timeout(callback),
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java // public class AsyncCallbackAdapter<T> implements AsyncCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable caught) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.callback.AsyncCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ public class AsyncCallbackMethodRunnerTest extends BasicRunnerTest { @Test public void testTimeout() throws Throwable { check( callback -> getCallbackAsync().timeout(callback),
new AsyncCallback<Boolean>() {
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java // public class AsyncCallbackAdapter<T> implements AsyncCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable caught) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.callback.AsyncCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer;
); } @Test public void testWithoutResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().empty(callback), notNullResultCallback(), true ) ); } @Test public void test1ArgumentWithoutResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().emptyHello(callback, PARAMETER), notNullResultCallback(), true ) ); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().hello(callback, PARAMETER),
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java // public class AsyncCallbackAdapter<T> implements AsyncCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable caught) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.callback.AsyncCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; ); } @Test public void testWithoutResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().empty(callback), notNullResultCallback(), true ) ); } @Test public void test1ArgumentWithoutResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().emptyHello(callback, PARAMETER), notNullResultCallback(), true ) ); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().hello(callback, PARAMETER),
new AsyncCallbackAdapter<String>() {
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java // public class AsyncCallbackAdapter<T> implements AsyncCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable caught) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.callback.AsyncCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer;
); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().hello(callback, PARAMETER, PARAMETER), new AsyncCallbackAdapter<String>() { @Override public void onSuccess(final String result) { Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), result); } }, true ) ); } @Test(expected = UnsupportedOperationException.class) public void testException() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().exception(callback), new AsyncCallbackAdapter<Void>(), true ) ); }
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallback.java // public interface AsyncCallback<T> { // // /** // * Callback-method on success. // * // * @param result result of operation // */ // void onSuccess(T result); // // /** // * Callback-method on failure. // * // * @param caught exception // */ // void onFailure(Throwable caught); // // } // // Path: src/main/java/com/github/vbauer/caesar/callback/AsyncCallbackAdapter.java // public class AsyncCallbackAdapter<T> implements AsyncCallback<T> { // // /** // * {@inheritDoc} // */ // @Override // public void onSuccess(final T result) { // // Do nothing. // } // // /** // * {@inheritDoc} // */ // @Override // public void onFailure(final Throwable caught) { // // Do nothing. // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/AsyncCallbackMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.callback.AsyncCallback; import com.github.vbauer.caesar.callback.AsyncCallbackAdapter; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; ); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().hello(callback, PARAMETER, PARAMETER), new AsyncCallbackAdapter<String>() { @Override public void onSuccess(final String result) { Assert.assertEquals(getSync().hello(PARAMETER, PARAMETER), result); } }, true ) ); } @Test(expected = UnsupportedOperationException.class) public void testException() throws Throwable { Assert.assertTrue( check( callback -> getCallbackAsync().exception(callback), new AsyncCallbackAdapter<Void>(), true ) ); }
@Test(expected = MissedSyncMethodException.class)
vbauer/caesar
src/test/java/com/github/vbauer/caesar/runner/impl/ListenableFutureMethodRunnerTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.google.common.util.concurrent.ListenableFuture; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException;
public void test1ArgumentWithoutResult() throws Throwable { getSync().emptyHello(PARAMETER); final ListenableFuture<Void> future = getListenableFutureAsync().emptyHello(PARAMETER); Assert.assertNotNull(future); Assert.assertNull(future.get()); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertEquals( getSync().hello(PARAMETER), getListenableFutureAsync().hello(PARAMETER).get() ); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertEquals( getSync().hello(PARAMETER, PARAMETER), getListenableFutureAsync().hello(PARAMETER, PARAMETER).get() ); } @Test(expected = ExecutionException.class) public void testException() throws Throwable { getListenableFutureAsync().exception().get(); Assert.fail(); }
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicRunnerTest.java // public abstract class BasicRunnerTest extends BasicTest { // // protected static final String PARAMETER = "World"; // // private final ThreadLocal<ExecutorService> executorServiceHolder = new ThreadLocal<>(); // private final ThreadLocal<Sync> syncBeanHolder = new ThreadLocal<>(); // private final ThreadLocal<CallbackAsync> callbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureCallbackAsync> futureCallbackAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<FutureAsync> futureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ListenableFutureAsync> listenableFutureAsyncHolder = new ThreadLocal<>(); // private final ThreadLocal<ObservableAsync> observableAsyncHolder = new ThreadLocal<>(); // // @Before // public final void before() { // final ExecutorService executor = Executors.newScheduledThreadPool(5); // final Sync sync = new Sync(); // final CallbackAsync callbackAsync = AsyncProxyCreator.create(sync, CallbackAsync.class, executor, false); // final FutureCallbackAsync futureCallbackAsync = AsyncProxyCreator.create(sync, FutureCallbackAsync.class, executor, false); // final FutureAsync futureAsync = AsyncProxyCreator.create(sync, FutureAsync.class, executor, false); // final ListenableFutureAsync listenableFutureAsync = AsyncProxyCreator.create(sync, ListenableFutureAsync.class, executor, false); // final ObservableAsync observableAsync = AsyncProxyCreator.create(sync, ObservableAsync.class, executor, false); // // executorServiceHolder.set(executor); // syncBeanHolder.set(sync); // callbackAsyncHolder.set(callbackAsync); // futureCallbackAsyncHolder.set(futureCallbackAsync); // futureAsyncHolder.set(futureAsync); // listenableFutureAsyncHolder.set(listenableFutureAsync); // observableAsyncHolder.set(observableAsync); // } // // @After // public final void after() { // getExecutorService().shutdown(); // executorServiceHolder.remove(); // syncBeanHolder.remove(); // callbackAsyncHolder.remove(); // futureCallbackAsyncHolder.remove(); // futureAsyncHolder.remove(); // listenableFutureAsyncHolder.remove(); // observableAsyncHolder.remove(); // } // // // protected ExecutorService getExecutorService() { // return executorServiceHolder.get(); // } // // protected Sync getSync() { // return syncBeanHolder.get(); // } // // protected CallbackAsync getCallbackAsync() { // return callbackAsyncHolder.get(); // } // // protected FutureCallbackAsync getFutureCallbackAsync() { // return futureCallbackAsyncHolder.get(); // } // // protected FutureAsync getFutureAsync() { // return futureAsyncHolder.get(); // } // // protected ListenableFutureAsync getListenableFutureAsync() { // return listenableFutureAsyncHolder.get(); // } // // protected ObservableAsync getObservableAsync() { // return observableAsyncHolder.get(); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/runner/impl/ListenableFutureMethodRunnerTest.java import com.github.vbauer.caesar.basic.BasicRunnerTest; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.google.common.util.concurrent.ListenableFuture; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; public void test1ArgumentWithoutResult() throws Throwable { getSync().emptyHello(PARAMETER); final ListenableFuture<Void> future = getListenableFutureAsync().emptyHello(PARAMETER); Assert.assertNotNull(future); Assert.assertNull(future.get()); } @Test public void test1ArgumentWithResult() throws Throwable { Assert.assertEquals( getSync().hello(PARAMETER), getListenableFutureAsync().hello(PARAMETER).get() ); } @Test public void test2ArgumentsWithResult() throws Throwable { Assert.assertEquals( getSync().hello(PARAMETER, PARAMETER), getListenableFutureAsync().hello(PARAMETER, PARAMETER).get() ); } @Test(expected = ExecutionException.class) public void testException() throws Throwable { getListenableFutureAsync().exception().get(); Assert.fail(); }
@Test(expected = MissedSyncMethodException.class)
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractAsyncMethodRunner.java
// Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/SimpleInvokeTask.java // public class SimpleInvokeTask<T> implements Callable<T> { // // private final Method syncMethod; // private final Object[] args; // private final Object origin; // // // public SimpleInvokeTask(final Object origin, final Method syncMethod, final Object[] args) { // this.syncMethod = syncMethod; // this.args = args; // this.origin = origin; // } // // // @SuppressWarnings("unchecked") // public T call() throws Exception { // return (T) syncMethod.invoke(origin, args); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.runner.task.SimpleInvokeTask; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future;
package com.github.vbauer.caesar.runner.impl.base; /** * @author Vladislav Bauer */ public abstract class AbstractAsyncMethodRunner implements AsyncMethodRunner { /** * {@inheritDoc} */ @Override public final Method findSyncMethod(final Object origin, final Method asyncMethod) {
// Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/SimpleInvokeTask.java // public class SimpleInvokeTask<T> implements Callable<T> { // // private final Method syncMethod; // private final Object[] args; // private final Object origin; // // // public SimpleInvokeTask(final Object origin, final Method syncMethod, final Object[] args) { // this.syncMethod = syncMethod; // this.args = args; // this.origin = origin; // } // // // @SuppressWarnings("unchecked") // public T call() throws Exception { // return (T) syncMethod.invoke(origin, args); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractAsyncMethodRunner.java import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.runner.task.SimpleInvokeTask; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; package com.github.vbauer.caesar.runner.impl.base; /** * @author Vladislav Bauer */ public abstract class AbstractAsyncMethodRunner implements AsyncMethodRunner { /** * {@inheritDoc} */ @Override public final Method findSyncMethod(final Object origin, final Method asyncMethod) {
final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(origin);
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractAsyncMethodRunner.java
// Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/SimpleInvokeTask.java // public class SimpleInvokeTask<T> implements Callable<T> { // // private final Method syncMethod; // private final Object[] args; // private final Object origin; // // // public SimpleInvokeTask(final Object origin, final Method syncMethod, final Object[] args) { // this.syncMethod = syncMethod; // this.args = args; // this.origin = origin; // } // // // @SuppressWarnings("unchecked") // public T call() throws Exception { // return (T) syncMethod.invoke(origin, args); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.runner.task.SimpleInvokeTask; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future;
package com.github.vbauer.caesar.runner.impl.base; /** * @author Vladislav Bauer */ public abstract class AbstractAsyncMethodRunner implements AsyncMethodRunner { /** * {@inheritDoc} */ @Override public final Method findSyncMethod(final Object origin, final Method asyncMethod) { final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(origin); final String methodName = asyncMethod.getName(); final Class<?> returnType = asyncMethod.getReturnType(); final Class<?>[] parameterTypes = asyncMethod.getParameterTypes(); return findSyncMethod(targetClass, methodName, returnType, parameterTypes); } /** * {@inheritDoc} */ @Override public <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object[] args ) {
// Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/SimpleInvokeTask.java // public class SimpleInvokeTask<T> implements Callable<T> { // // private final Method syncMethod; // private final Object[] args; // private final Object origin; // // // public SimpleInvokeTask(final Object origin, final Method syncMethod, final Object[] args) { // this.syncMethod = syncMethod; // this.args = args; // this.origin = origin; // } // // // @SuppressWarnings("unchecked") // public T call() throws Exception { // return (T) syncMethod.invoke(origin, args); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractAsyncMethodRunner.java import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.runner.task.SimpleInvokeTask; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; package com.github.vbauer.caesar.runner.impl.base; /** * @author Vladislav Bauer */ public abstract class AbstractAsyncMethodRunner implements AsyncMethodRunner { /** * {@inheritDoc} */ @Override public final Method findSyncMethod(final Object origin, final Method asyncMethod) { final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(origin); final String methodName = asyncMethod.getName(); final Class<?> returnType = asyncMethod.getReturnType(); final Class<?>[] parameterTypes = asyncMethod.getParameterTypes(); return findSyncMethod(targetClass, methodName, returnType, parameterTypes); } /** * {@inheritDoc} */ @Override public <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object[] args ) {
return new SimpleInvokeTask<>(origin, syncMethod, args);
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunnerFactory.java
// Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.util.ReflectionUtils; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List;
package com.github.vbauer.caesar.runner; /** * @author Vladislav Bauer */ public final class AsyncMethodRunnerFactory { public static final String PACKAGE_NAME = "com.github.vbauer.caesar.runner.impl"; /** * Immutable list with class names of method runners. * * IMPORTANT: * This classes must be listed in the right order: from more-specific to less-specific classes. */ public static final List<String> CLASS_NAMES = Collections.unmodifiableList( Arrays.asList( "ObservableMethodRunner", "ListenableFutureMethodRunner", "FutureCallbackMethodRunner", "FutureMethodRunner", "AsyncCallbackMethodRunner", "SyncMethodRunner" ) ); private AsyncMethodRunnerFactory() { throw new UnsupportedOperationException(); } public static Collection<AsyncMethodRunner> createMethodRunners() { final Collection<String> classNames =
// Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunnerFactory.java import com.github.vbauer.caesar.util.ReflectionUtils; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; package com.github.vbauer.caesar.runner; /** * @author Vladislav Bauer */ public final class AsyncMethodRunnerFactory { public static final String PACKAGE_NAME = "com.github.vbauer.caesar.runner.impl"; /** * Immutable list with class names of method runners. * * IMPORTANT: * This classes must be listed in the right order: from more-specific to less-specific classes. */ public static final List<String> CLASS_NAMES = Collections.unmodifiableList( Arrays.asList( "ObservableMethodRunner", "ListenableFutureMethodRunner", "FutureCallbackMethodRunner", "FutureMethodRunner", "AsyncCallbackMethodRunner", "SyncMethodRunner" ) ); private AsyncMethodRunnerFactory() { throw new UnsupportedOperationException(); } public static Collection<AsyncMethodRunner> createMethodRunners() { final Collection<String> classNames =
ReflectionUtils.classNames(PACKAGE_NAME, CLASS_NAMES);
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java
// Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.Callable;
package com.github.vbauer.caesar.runner.impl.base; /** * @author Vladislav Bauer */ public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { /** * {@inheritDoc} */ @Override public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { final Object asyncCallback = args[0]; final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); return createCall(origin, syncMethod, asyncCallback, restArgs); } /** * {@inheritDoc} */ @Override protected Method findSyncMethod( final Class<?> targetClass, final String methodName, final Class<?> returnType, final Class<?>[] parameterTypes ) { if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { final Class<?> lastParam = parameterTypes[0]; final Class<?> callbackClass = getCallbackClass(); if (callbackClass.isAssignableFrom(lastParam)) { final Class<?>[] restParamTypes = Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length);
// Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.Callable; package com.github.vbauer.caesar.runner.impl.base; /** * @author Vladislav Bauer */ public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { /** * {@inheritDoc} */ @Override public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { final Object asyncCallback = args[0]; final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); return createCall(origin, syncMethod, asyncCallback, restArgs); } /** * {@inheritDoc} */ @Override protected Method findSyncMethod( final Class<?> targetClass, final String methodName, final Class<?> returnType, final Class<?>[] parameterTypes ) { if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { final Class<?> lastParam = parameterTypes[0]; final Class<?> callbackClass = getCallbackClass(); if (callbackClass.isAssignableFrom(lastParam)) { final Class<?>[] restParamTypes = Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length);
return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes);
vbauer/caesar
src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); }
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); }
@Test(expected = MissedSyncMethodException.class)
vbauer/caesar
src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() {
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() {
Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor())));
vbauer/caesar
src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() { Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor()))); } @Test(expected = MissedSyncMethodException.class) public void testBadProxy() { Assert.fail(String.valueOf(
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() { Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor()))); } @Test(expected = MissedSyncMethodException.class) public void testBadProxy() { Assert.fail(String.valueOf(
AsyncProxyCreator.create(new Sync(), CallbackAsync.class, executor())
vbauer/caesar
src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() { Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor()))); } @Test(expected = MissedSyncMethodException.class) public void testBadProxy() { Assert.fail(String.valueOf( AsyncProxyCreator.create(new Sync(), CallbackAsync.class, executor()) )); } @Test public void testCorrectProxy() throws Throwable {
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() { Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor()))); } @Test(expected = MissedSyncMethodException.class) public void testBadProxy() { Assert.fail(String.valueOf( AsyncProxyCreator.create(new Sync(), CallbackAsync.class, executor()) )); } @Test public void testCorrectProxy() throws Throwable {
final SimpleSync bean1 = new SimpleSync(1);
vbauer/caesar
src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // }
import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() { Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor()))); } @Test(expected = MissedSyncMethodException.class) public void testBadProxy() { Assert.fail(String.valueOf( AsyncProxyCreator.create(new Sync(), CallbackAsync.class, executor()) )); } @Test public void testCorrectProxy() throws Throwable { final SimpleSync bean1 = new SimpleSync(1);
// Path: src/test/java/com/github/vbauer/caesar/basic/BasicTest.java // @RunWith(BlockJUnit4ClassRunner.class) // public abstract class BasicTest { // // protected final boolean checkUtilConstructorContract(final Class<?>... utilClasses) { // Assert.assertTrue(utilClasses.length > 0); // // PrivateConstructorChecker // .forClasses(utilClasses) // .expectedTypeOfException(UnsupportedOperationException.class) // .check(); // // return true; // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/CallbackAsync.java // public interface CallbackAsync { // // void hello(AsyncCallback<String> callback, String name1, String name2); // // void hello(AsyncCallback<String> callback, String name); // // void emptyHello(AsyncCallback<Void> callback, String name); // // void empty(AsyncCallback<Void> callback); // // void exception(AsyncCallback<Void> callback); // // void methodWithoutSyncImpl(AsyncCallback<Boolean> callback); // // @Timeout(value = 1, unit = TimeUnit.MILLISECONDS) // void timeout(AsyncCallback<Boolean> callback); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleAsync.java // @Timeout(5) // public interface SimpleAsync { // // Future<Integer> getId(); // // Future<Boolean> timeout(); // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/SimpleSync.java // public class SimpleSync { // // public static final boolean TIMEOUT_VALUE = true; // private final int id; // // // public SimpleSync(final int id) { // this.id = id; // } // // // public int getId() { // return id; // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return TIMEOUT_VALUE; // } // // // @Override // public int hashCode() { // return id; // } // // @Override // public boolean equals(final Object obj) { // if (obj instanceof SimpleSync) { // final SimpleSync other = (SimpleSync) obj; // return other.getId() == getId(); // } // return false; // } // // @Override // public String toString() { // return String.valueOf(getId()); // } // // } // // Path: src/test/java/com/github/vbauer/caesar/bean/Sync.java // public class Sync { // // public String hello(final String name) { // return String.format("Hello, %s", name); // } // // public String hello(final String name1, final String name2) { // return String.format("Hello, %s and %s", name1, name2); // } // // public void empty() { // // Do nothing. // } // // public void emptyHello(@SuppressWarnings("unused") final String name) { // // Do nothing. // } // // public void exception() { // throw new UnsupportedOperationException(); // } // // public Boolean timeout() throws InterruptedException { // Thread.sleep(1000); // return true; // } // // } // // Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // Path: src/test/java/com/github/vbauer/caesar/proxy/AsyncProxyCreatorTest.java import com.github.vbauer.caesar.basic.BasicTest; import com.github.vbauer.caesar.bean.CallbackAsync; import com.github.vbauer.caesar.bean.SimpleAsync; import com.github.vbauer.caesar.bean.SimpleSync; import com.github.vbauer.caesar.bean.Sync; import com.github.vbauer.caesar.exception.MissedSyncMethodException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.vbauer.caesar.proxy; /** * @author Vladislav Bauer */ public class AsyncProxyCreatorTest extends BasicTest { private static final ThreadLocal<ExecutorService> EXECUTOR = new ThreadLocal<>(); @BeforeClass public static void setUp() { EXECUTOR.set(Executors.newScheduledThreadPool(5)); } @AfterClass public static void tearDown() { executor().shutdown(); } @Test public void testConstructorContract() { Assert.assertTrue(checkUtilConstructorContract(AsyncProxyCreator.class)); } @Test(expected = MissedSyncMethodException.class) public void testIncorrectProxy() { Assert.fail(String.valueOf(AsyncProxyCreator.create(new Sync(), List.class, executor()))); } @Test(expected = MissedSyncMethodException.class) public void testBadProxy() { Assert.fail(String.valueOf( AsyncProxyCreator.create(new Sync(), CallbackAsync.class, executor()) )); } @Test public void testCorrectProxy() throws Throwable { final SimpleSync bean1 = new SimpleSync(1);
final SimpleAsync proxy1 = AsyncProxyCreator.create(bean1, SimpleAsync.class, executor());
vbauer/caesar
src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java
// Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.ExecutorService;
package com.github.vbauer.caesar.proxy; /** * Proxy creator that makes asynchronous variant of bean. * * @author Vladislav Bauer */ public final class AsyncProxyCreator { private AsyncProxyCreator() { throw new UnsupportedOperationException(); } public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor ) { return create(bean, asyncInterface, executor, true); } @SuppressWarnings("unchecked") public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate ) { final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); final Class<?> beanClass = bean.getClass(); final ClassLoader classLoader = beanClass.getClassLoader(); final Class<?>[] interfaces = { asyncInterface, }; final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); return validate ? validate(proxy, handler) : proxy; } private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) {
// Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.ExecutorService; package com.github.vbauer.caesar.proxy; /** * Proxy creator that makes asynchronous variant of bean. * * @author Vladislav Bauer */ public final class AsyncProxyCreator { private AsyncProxyCreator() { throw new UnsupportedOperationException(); } public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor ) { return create(bean, asyncInterface, executor, true); } @SuppressWarnings("unchecked") public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate ) { final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); final Class<?> beanClass = bean.getClass(); final ClassLoader classLoader = beanClass.getClassLoader(); final Class<?>[] interfaces = { asyncInterface, }; final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); return validate ? validate(proxy, handler) : proxy; } private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) {
final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy);
vbauer/caesar
src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java
// Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.ExecutorService;
package com.github.vbauer.caesar.proxy; /** * Proxy creator that makes asynchronous variant of bean. * * @author Vladislav Bauer */ public final class AsyncProxyCreator { private AsyncProxyCreator() { throw new UnsupportedOperationException(); } public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor ) { return create(bean, asyncInterface, executor, true); } @SuppressWarnings("unchecked") public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate ) { final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); final Class<?> beanClass = bean.getClass(); final ClassLoader classLoader = beanClass.getClassLoader(); final Class<?>[] interfaces = { asyncInterface, }; final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); return validate ? validate(proxy, handler) : proxy; } private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); final Method[] methods = targetClass.getDeclaredMethods(); for (final Method method : methods) {
// Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.ExecutorService; package com.github.vbauer.caesar.proxy; /** * Proxy creator that makes asynchronous variant of bean. * * @author Vladislav Bauer */ public final class AsyncProxyCreator { private AsyncProxyCreator() { throw new UnsupportedOperationException(); } public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor ) { return create(bean, asyncInterface, executor, true); } @SuppressWarnings("unchecked") public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate ) { final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); final Class<?> beanClass = bean.getClass(); final ClassLoader classLoader = beanClass.getClassLoader(); final Class<?>[] interfaces = { asyncInterface, }; final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); return validate ? validate(proxy, handler) : proxy; } private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); final Method[] methods = targetClass.getDeclaredMethods(); for (final Method method : methods) {
final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method);
vbauer/caesar
src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java
// Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // }
import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.ExecutorService;
package com.github.vbauer.caesar.proxy; /** * Proxy creator that makes asynchronous variant of bean. * * @author Vladislav Bauer */ public final class AsyncProxyCreator { private AsyncProxyCreator() { throw new UnsupportedOperationException(); } public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor ) { return create(bean, asyncInterface, executor, true); } @SuppressWarnings("unchecked") public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate ) { final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); final Class<?> beanClass = bean.getClass(); final ClassLoader classLoader = beanClass.getClassLoader(); final Class<?>[] interfaces = { asyncInterface, }; final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); return validate ? validate(proxy, handler) : proxy; } private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); final Method[] methods = targetClass.getDeclaredMethods(); for (final Method method : methods) { final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); if (runner == null) {
// Path: src/main/java/com/github/vbauer/caesar/exception/MissedSyncMethodException.java // @SuppressWarnings("serial") // public class MissedSyncMethodException extends AbstractCaesarException { // // private final Method method; // private final Object[] arguments; // // // public MissedSyncMethodException(final Method method, final Object... arguments) { // this.method = method; // this.arguments = arguments; // } // // // public Method getMethod() { // return method; // } // // public Object[] getArguments() { // return arguments; // } // // // /** // * {@inheritDoc} // */ // @Override // public String getMessage() { // return String.format( // "Can not find appropriate sync-method \"%s\", parameters: %s", // getMethod(), Arrays.toString(getArguments()) // ); // } // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/AsyncMethodRunner.java // public interface AsyncMethodRunner { // // Method findSyncMethod(Object origin, Method asyncMethod); // // <T> Callable<T> createCall(Object origin, Method syncMethod, Object[] args); // // Object processResultFuture(Future<?> future, ExecutorService executor) throws Throwable; // // } // // Path: src/main/java/com/github/vbauer/caesar/util/ReflectionUtils.java // @SuppressWarnings("unchecked") // public final class ReflectionUtils { // // public static final String PACKAGE_SEPARATOR = "."; // // // private ReflectionUtils() { // throw new UnsupportedOperationException(); // } // // // public static <T> Class<T> getClassWithoutProxies(final Object object) { // try { // // XXX: Use HibernateProxyHelper to un-proxy object and get the original class. // return (Class<T>) Class.forName("org.hibernate.proxy.HibernateProxyHelper") // .getDeclaredMethod("getClassWithoutInitializingProxy", Object.class) // .invoke(null, object); // } catch (final Exception ex) { // return getClassSafe(object); // } // } // // public static <T> Class<T> getClassSafe(final Object object) { // return object != null ? (Class<T>) object.getClass() : null; // } // // public static <T> T createObject(final String className) { // try { // final Class<?> clazz = Class.forName(className); // return (T) clazz.newInstance(); // } catch (final Throwable ex) { // return null; // } // } // // public static <T> Collection<T> createObjects(final Collection<String> classNames) { // final List<T> objects = new ArrayList<>(); // for (final String className : classNames) { // final T object = createObject(className); // if (object != null) { // objects.add(object); // } // } // return objects; // } // // public static Collection<String> classNames(final String packageName, final Collection<String> classNames) { // final List<String> result = new ArrayList<>(); // for (final String className : classNames) { // result.add(packageName + PACKAGE_SEPARATOR + className); // } // return result; // } // // public static Method findDeclaredMethod( // final Class<?> objectClass, final String methodName, final Class<?>[] parameterTypes // ) { // try { // return objectClass.getDeclaredMethod(methodName, parameterTypes); // } catch (final Throwable ignored) { // return null; // } // } // // public static <T extends Annotation> T findAnnotationFromMethodOrClass( // final Method method, final Class<T> annotationClass // ) { // final T annotation = method.getAnnotation(annotationClass); // if (annotation != null) { // return annotation; // } // // final Class<?> originClass = method.getDeclaringClass(); // return originClass.getAnnotation(annotationClass); // } // // } // Path: src/main/java/com/github/vbauer/caesar/proxy/AsyncProxyCreator.java import com.github.vbauer.caesar.exception.MissedSyncMethodException; import com.github.vbauer.caesar.runner.AsyncMethodRunner; import com.github.vbauer.caesar.util.ReflectionUtils; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.concurrent.ExecutorService; package com.github.vbauer.caesar.proxy; /** * Proxy creator that makes asynchronous variant of bean. * * @author Vladislav Bauer */ public final class AsyncProxyCreator { private AsyncProxyCreator() { throw new UnsupportedOperationException(); } public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor ) { return create(bean, asyncInterface, executor, true); } @SuppressWarnings("unchecked") public static <SYNC, ASYNC> ASYNC create( final SYNC bean, final Class<ASYNC> asyncInterface, final ExecutorService executor, final boolean validate ) { final AsyncInvocationHandler handler = AsyncInvocationHandler.create(bean, executor); final Class<?> beanClass = bean.getClass(); final ClassLoader classLoader = beanClass.getClassLoader(); final Class<?>[] interfaces = { asyncInterface, }; final ASYNC proxy = (ASYNC) Proxy.newProxyInstance(classLoader, interfaces, handler); return validate ? validate(proxy, handler) : proxy; } private static <T> T validate(final T proxy, final AsyncInvocationHandler handler) { final Class<?> targetClass = ReflectionUtils.getClassWithoutProxies(proxy); final Method[] methods = targetClass.getDeclaredMethods(); for (final Method method : methods) { final AsyncMethodRunner runner = handler.findAsyncMethodRunner(method); if (runner == null) {
throw new MissedSyncMethodException(method);
vbauer/caesar
src/main/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunner.java
// Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java // public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { // // /** // * {@inheritDoc} // */ // @Override // public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { // final Object asyncCallback = args[0]; // final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); // // return createCall(origin, syncMethod, asyncCallback, restArgs); // } // // /** // * {@inheritDoc} // */ // @Override // protected Method findSyncMethod( // final Class<?> targetClass, final String methodName, // final Class<?> returnType, final Class<?>[] parameterTypes // ) { // if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { // final Class<?> lastParam = parameterTypes[0]; // final Class<?> callbackClass = getCallbackClass(); // // if (callbackClass.isAssignableFrom(lastParam)) { // final Class<?>[] restParamTypes = // Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length); // // return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes); // } // // } // return null; // } // // // protected abstract <T> Callable<T> createCall( // Object origin, Method syncMethod, Object callback, Object[] args // ); // // protected abstract Class<?> getCallbackClass(); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/FutureCallbackTask.java // public class FutureCallbackTask<T> implements Callable<T> { // // private final Object origin; // private final Object[] args; // private final Method syncMethod; // private final FutureCallback futureCallback; // // // public FutureCallbackTask( // final Object origin, final Method syncMethod, final Object[] args, // final FutureCallback futureCallback // ) { // this.origin = origin; // this.args = args; // this.syncMethod = syncMethod; // this.futureCallback = futureCallback; // } // // // @SuppressWarnings("unchecked") // public T call() { // final Object result; // // try { // result = syncMethod.invoke(origin, args); // } catch (final Throwable ex) { // futureCallback.onFailure(ex.getCause()); // return null; // } // // futureCallback.onSuccess(result); // // return (T) result; // } // // }
import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; import com.github.vbauer.caesar.runner.task.FutureCallbackTask; import com.google.common.util.concurrent.FutureCallback; import java.lang.reflect.Method; import java.util.concurrent.Callable;
package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ @SuppressWarnings("all") public class FutureCallbackMethodRunner extends AbstractCallbackMethodRunner { /** * {@inheritDoc} */ @Override protected <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object callback, final Object[] args ) {
// Path: src/main/java/com/github/vbauer/caesar/runner/impl/base/AbstractCallbackMethodRunner.java // public abstract class AbstractCallbackMethodRunner extends AbstractAsyncMethodRunner { // // /** // * {@inheritDoc} // */ // @Override // public <T> Callable<T> createCall(final Object origin, final Method syncMethod, final Object[] args) { // final Object asyncCallback = args[0]; // final Object[] restArgs = Arrays.copyOfRange(args, 1, args.length); // // return createCall(origin, syncMethod, asyncCallback, restArgs); // } // // /** // * {@inheritDoc} // */ // @Override // protected Method findSyncMethod( // final Class<?> targetClass, final String methodName, // final Class<?> returnType, final Class<?>[] parameterTypes // ) { // if (void.class == returnType && parameterTypes != null && parameterTypes.length > 0) { // final Class<?> lastParam = parameterTypes[0]; // final Class<?> callbackClass = getCallbackClass(); // // if (callbackClass.isAssignableFrom(lastParam)) { // final Class<?>[] restParamTypes = // Arrays.copyOfRange(parameterTypes, 1, parameterTypes.length); // // return ReflectionUtils.findDeclaredMethod(targetClass, methodName, restParamTypes); // } // // } // return null; // } // // // protected abstract <T> Callable<T> createCall( // Object origin, Method syncMethod, Object callback, Object[] args // ); // // protected abstract Class<?> getCallbackClass(); // // } // // Path: src/main/java/com/github/vbauer/caesar/runner/task/FutureCallbackTask.java // public class FutureCallbackTask<T> implements Callable<T> { // // private final Object origin; // private final Object[] args; // private final Method syncMethod; // private final FutureCallback futureCallback; // // // public FutureCallbackTask( // final Object origin, final Method syncMethod, final Object[] args, // final FutureCallback futureCallback // ) { // this.origin = origin; // this.args = args; // this.syncMethod = syncMethod; // this.futureCallback = futureCallback; // } // // // @SuppressWarnings("unchecked") // public T call() { // final Object result; // // try { // result = syncMethod.invoke(origin, args); // } catch (final Throwable ex) { // futureCallback.onFailure(ex.getCause()); // return null; // } // // futureCallback.onSuccess(result); // // return (T) result; // } // // } // Path: src/main/java/com/github/vbauer/caesar/runner/impl/FutureCallbackMethodRunner.java import com.github.vbauer.caesar.runner.impl.base.AbstractCallbackMethodRunner; import com.github.vbauer.caesar.runner.task.FutureCallbackTask; import com.google.common.util.concurrent.FutureCallback; import java.lang.reflect.Method; import java.util.concurrent.Callable; package com.github.vbauer.caesar.runner.impl; /** * @author Vladislav Bauer */ @SuppressWarnings("all") public class FutureCallbackMethodRunner extends AbstractCallbackMethodRunner { /** * {@inheritDoc} */ @Override protected <T> Callable<T> createCall( final Object origin, final Method syncMethod, final Object callback, final Object[] args ) {
return new FutureCallbackTask<T>(origin, syncMethod, args, (FutureCallback) callback);
CaMnter/Robotlegs4Android
app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Actor.java // public class Actor { // // /** // * private // */ // protected IEventDispatcher _eventDispatcher; // // /** // * private // */ // protected IEventMap _eventMap; // // // --------------------------------------------------------------------- // // Constructor // // --------------------------------------------------------------------- // // public Actor() { // // } // // // --------------------------------------------------------------------- // // API // // --------------------------------------------------------------------- // // /** // * @return <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // public IEventDispatcher getEventDispatcher() { // return this._eventDispatcher; // } // // /** // * @param value <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // @Inject // public void setEventDispatcher(IEventDispatcher value) { // this._eventDispatcher = value; // } // // // --------------------------------------------------------------------- // // Internal // // --------------------------------------------------------------------- // // /** // * Local EventMap // * // * @return The EventMap for this Actor // */ // public IEventMap getEventMap() { // if (this._eventMap == null) { // this._eventMap = new EventMap(this.getEventDispatcher()); // } // return this._eventMap; // } // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.getEventDispatcher().hasEventListener(event.getType())) // return this.getEventDispatcher().dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/bean/User.java // public class User implements Serializable { // // public String name; // // public String sign; // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // }
import com.camnter.robotlegs4android.mvcs.Actor; import com.camnter.robotlegs4android.test.bean.User; import com.camnter.robotlegs4android.test.event.LoginEvent;
/* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.model; /** * Description:UserModel * Created by:CaMnter * Time:2015-11-07 22:58 */ public class UserModel extends Actor { public void login(String name,String password) { // TODO Do you want to network requests
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Actor.java // public class Actor { // // /** // * private // */ // protected IEventDispatcher _eventDispatcher; // // /** // * private // */ // protected IEventMap _eventMap; // // // --------------------------------------------------------------------- // // Constructor // // --------------------------------------------------------------------- // // public Actor() { // // } // // // --------------------------------------------------------------------- // // API // // --------------------------------------------------------------------- // // /** // * @return <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // public IEventDispatcher getEventDispatcher() { // return this._eventDispatcher; // } // // /** // * @param value <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // @Inject // public void setEventDispatcher(IEventDispatcher value) { // this._eventDispatcher = value; // } // // // --------------------------------------------------------------------- // // Internal // // --------------------------------------------------------------------- // // /** // * Local EventMap // * // * @return The EventMap for this Actor // */ // public IEventMap getEventMap() { // if (this._eventMap == null) { // this._eventMap = new EventMap(this.getEventDispatcher()); // } // return this._eventMap; // } // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.getEventDispatcher().hasEventListener(event.getType())) // return this.getEventDispatcher().dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/bean/User.java // public class User implements Serializable { // // public String name; // // public String sign; // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // } // Path: app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java import com.camnter.robotlegs4android.mvcs.Actor; import com.camnter.robotlegs4android.test.bean.User; import com.camnter.robotlegs4android.test.event.LoginEvent; /* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.model; /** * Description:UserModel * Created by:CaMnter * Time:2015-11-07 22:58 */ public class UserModel extends Actor { public void login(String name,String password) { // TODO Do you want to network requests
User user = new User();
CaMnter/Robotlegs4Android
app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Actor.java // public class Actor { // // /** // * private // */ // protected IEventDispatcher _eventDispatcher; // // /** // * private // */ // protected IEventMap _eventMap; // // // --------------------------------------------------------------------- // // Constructor // // --------------------------------------------------------------------- // // public Actor() { // // } // // // --------------------------------------------------------------------- // // API // // --------------------------------------------------------------------- // // /** // * @return <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // public IEventDispatcher getEventDispatcher() { // return this._eventDispatcher; // } // // /** // * @param value <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // @Inject // public void setEventDispatcher(IEventDispatcher value) { // this._eventDispatcher = value; // } // // // --------------------------------------------------------------------- // // Internal // // --------------------------------------------------------------------- // // /** // * Local EventMap // * // * @return The EventMap for this Actor // */ // public IEventMap getEventMap() { // if (this._eventMap == null) { // this._eventMap = new EventMap(this.getEventDispatcher()); // } // return this._eventMap; // } // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.getEventDispatcher().hasEventListener(event.getType())) // return this.getEventDispatcher().dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/bean/User.java // public class User implements Serializable { // // public String name; // // public String sign; // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // }
import com.camnter.robotlegs4android.mvcs.Actor; import com.camnter.robotlegs4android.test.bean.User; import com.camnter.robotlegs4android.test.event.LoginEvent;
/* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.model; /** * Description:UserModel * Created by:CaMnter * Time:2015-11-07 22:58 */ public class UserModel extends Actor { public void login(String name,String password) { // TODO Do you want to network requests User user = new User(); user.name = "CaMnter"; user.sign = "Save you from anything"; /* * you can send a your custom event from Model layer to View layer * 你可以发送一个你自定义的事件从Model层到View层 */
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Actor.java // public class Actor { // // /** // * private // */ // protected IEventDispatcher _eventDispatcher; // // /** // * private // */ // protected IEventMap _eventMap; // // // --------------------------------------------------------------------- // // Constructor // // --------------------------------------------------------------------- // // public Actor() { // // } // // // --------------------------------------------------------------------- // // API // // --------------------------------------------------------------------- // // /** // * @return <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // public IEventDispatcher getEventDispatcher() { // return this._eventDispatcher; // } // // /** // * @param value <code>com.camnter.robotlegs4android.core.IEventDispatcher</code> // */ // @Inject // public void setEventDispatcher(IEventDispatcher value) { // this._eventDispatcher = value; // } // // // --------------------------------------------------------------------- // // Internal // // --------------------------------------------------------------------- // // /** // * Local EventMap // * // * @return The EventMap for this Actor // */ // public IEventMap getEventMap() { // if (this._eventMap == null) { // this._eventMap = new EventMap(this.getEventDispatcher()); // } // return this._eventMap; // } // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.getEventDispatcher().hasEventListener(event.getType())) // return this.getEventDispatcher().dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/bean/User.java // public class User implements Serializable { // // public String name; // // public String sign; // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // } // Path: app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java import com.camnter.robotlegs4android.mvcs.Actor; import com.camnter.robotlegs4android.test.bean.User; import com.camnter.robotlegs4android.test.event.LoginEvent; /* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.model; /** * Description:UserModel * Created by:CaMnter * Time:2015-11-07 22:58 */ public class UserModel extends Actor { public void login(String name,String password) { // TODO Do you want to network requests User user = new User(); user.name = "CaMnter"; user.sign = "Save you from anything"; /* * you can send a your custom event from Model layer to View layer * 你可以发送一个你自定义的事件从Model层到View层 */
LoginEvent loginEvent = new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW);
CaMnter/Robotlegs4Android
app/src/main/java/com/camnter/robotlegs4android/test/controller/Login.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Command.java // public abstract class Command { // // @Inject // public Object contextView; // // @Inject // public ICommandMap commandMap; // // @Inject // public IEventDispatcher eventDispatcher; // // @Inject // public IInjector injector; // // @Inject // public IMediatorMap mediatorMap; // // public Command() { // // } // // /** // * TODO - The Command subclass must inherit the execute method // * 备忘录 - Command子类必须继承execute方法 // */ // public abstract void execute(); // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.eventDispatcher.hasEventListener(event.getType())) // return this.eventDispatcher.dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java // public class UserModel extends Actor { // // public void login(String name,String password) { // // // TODO Do you want to network requests // // User user = new User(); // user.name = "CaMnter"; // user.sign = "Save you from anything"; // // /* // * you can send a your custom event from Model layer to View layer // * 你可以发送一个你自定义的事件从Model层到View层 // */ // LoginEvent loginEvent = new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW); // loginEvent.user = user; // this.dispatch(loginEvent); // this.dispatch(new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER)); // } // // public boolean logout(){ // // // TODO Do you want to network requests // // return true; // } // // // }
import android.util.Log; import com.camnter.robotlegs4android.base.Inject; import com.camnter.robotlegs4android.mvcs.Command; import com.camnter.robotlegs4android.test.event.LoginEvent; import com.camnter.robotlegs4android.test.model.UserModel;
/* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.controller; /** * Description:Login * Created by:CaMnter * Time:2015-11-07 22:58 */ public class Login extends Command { private static final String TAG = "Login"; @Inject
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Command.java // public abstract class Command { // // @Inject // public Object contextView; // // @Inject // public ICommandMap commandMap; // // @Inject // public IEventDispatcher eventDispatcher; // // @Inject // public IInjector injector; // // @Inject // public IMediatorMap mediatorMap; // // public Command() { // // } // // /** // * TODO - The Command subclass must inherit the execute method // * 备忘录 - Command子类必须继承execute方法 // */ // public abstract void execute(); // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.eventDispatcher.hasEventListener(event.getType())) // return this.eventDispatcher.dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java // public class UserModel extends Actor { // // public void login(String name,String password) { // // // TODO Do you want to network requests // // User user = new User(); // user.name = "CaMnter"; // user.sign = "Save you from anything"; // // /* // * you can send a your custom event from Model layer to View layer // * 你可以发送一个你自定义的事件从Model层到View层 // */ // LoginEvent loginEvent = new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW); // loginEvent.user = user; // this.dispatch(loginEvent); // this.dispatch(new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER)); // } // // public boolean logout(){ // // // TODO Do you want to network requests // // return true; // } // // // } // Path: app/src/main/java/com/camnter/robotlegs4android/test/controller/Login.java import android.util.Log; import com.camnter.robotlegs4android.base.Inject; import com.camnter.robotlegs4android.mvcs.Command; import com.camnter.robotlegs4android.test.event.LoginEvent; import com.camnter.robotlegs4android.test.model.UserModel; /* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.controller; /** * Description:Login * Created by:CaMnter * Time:2015-11-07 22:58 */ public class Login extends Command { private static final String TAG = "Login"; @Inject
public UserModel userModel;
CaMnter/Robotlegs4Android
app/src/main/java/com/camnter/robotlegs4android/test/controller/Login.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Command.java // public abstract class Command { // // @Inject // public Object contextView; // // @Inject // public ICommandMap commandMap; // // @Inject // public IEventDispatcher eventDispatcher; // // @Inject // public IInjector injector; // // @Inject // public IMediatorMap mediatorMap; // // public Command() { // // } // // /** // * TODO - The Command subclass must inherit the execute method // * 备忘录 - Command子类必须继承execute方法 // */ // public abstract void execute(); // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.eventDispatcher.hasEventListener(event.getType())) // return this.eventDispatcher.dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java // public class UserModel extends Actor { // // public void login(String name,String password) { // // // TODO Do you want to network requests // // User user = new User(); // user.name = "CaMnter"; // user.sign = "Save you from anything"; // // /* // * you can send a your custom event from Model layer to View layer // * 你可以发送一个你自定义的事件从Model层到View层 // */ // LoginEvent loginEvent = new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW); // loginEvent.user = user; // this.dispatch(loginEvent); // this.dispatch(new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER)); // } // // public boolean logout(){ // // // TODO Do you want to network requests // // return true; // } // // // }
import android.util.Log; import com.camnter.robotlegs4android.base.Inject; import com.camnter.robotlegs4android.mvcs.Command; import com.camnter.robotlegs4android.test.event.LoginEvent; import com.camnter.robotlegs4android.test.model.UserModel;
/* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.controller; /** * Description:Login * Created by:CaMnter * Time:2015-11-07 22:58 */ public class Login extends Command { private static final String TAG = "Login"; @Inject public UserModel userModel; @Inject
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/mvcs/Command.java // public abstract class Command { // // @Inject // public Object contextView; // // @Inject // public ICommandMap commandMap; // // @Inject // public IEventDispatcher eventDispatcher; // // @Inject // public IInjector injector; // // @Inject // public IMediatorMap mediatorMap; // // public Command() { // // } // // /** // * TODO - The Command subclass must inherit the execute method // * 备忘录 - Command子类必须继承execute方法 // */ // public abstract void execute(); // // /** // * Dispatch helper method // * 调度辅助方法 // * // * @param event The <code>Event</code> to dispatch on the // * <code>IContext</code>'s <code>IEventDispatcher</code> // * Event分派IContext的IEventDispatcher // * @return Boolean // */ // protected Boolean dispatch(Event event) { // if (this.eventDispatcher.hasEventListener(event.getType())) // return this.eventDispatcher.dispatchEvent(event); // // return false; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java // public class LoginEvent extends Event { // // public static final String USER_LOGIN = "user_login"; // public static final String USER_LOGOUT = "user_logout"; // // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; // public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; // public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; // // public String name; // public String password; // // public User user; // // public LoginEvent(String type) { // super(type); // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/model/UserModel.java // public class UserModel extends Actor { // // public void login(String name,String password) { // // // TODO Do you want to network requests // // User user = new User(); // user.name = "CaMnter"; // user.sign = "Save you from anything"; // // /* // * you can send a your custom event from Model layer to View layer // * 你可以发送一个你自定义的事件从Model层到View层 // */ // LoginEvent loginEvent = new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW); // loginEvent.user = user; // this.dispatch(loginEvent); // this.dispatch(new LoginEvent(LoginEvent.USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER)); // } // // public boolean logout(){ // // // TODO Do you want to network requests // // return true; // } // // // } // Path: app/src/main/java/com/camnter/robotlegs4android/test/controller/Login.java import android.util.Log; import com.camnter.robotlegs4android.base.Inject; import com.camnter.robotlegs4android.mvcs.Command; import com.camnter.robotlegs4android.test.event.LoginEvent; import com.camnter.robotlegs4android.test.model.UserModel; /* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.controller; /** * Description:Login * Created by:CaMnter * Time:2015-11-07 22:58 */ public class Login extends Command { private static final String TAG = "Login"; @Inject public UserModel userModel; @Inject
public LoginEvent event;
CaMnter/Robotlegs4Android
robotlegs4android/src/main/java/com/camnter/robotlegs4android/swiftsuspenders/InjectionConfig.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/swiftsuspenders/injectionresults/InjectionResult.java // public class InjectionResult { // // /******************************************************************************************* // * constructor * // *******************************************************************************************/ // public InjectionResult() { // // } // // /******************************************************************************************* // * public methods * // *******************************************************************************************/ // /** // * {@inheritDoc} // * Get the Response // * 获取响应 // * // * @param injector injector // * @return Object // */ // public Object getResponse(Injector injector) { // return null; // } // // }
import android.util.Log; import com.camnter.robotlegs4android.swiftsuspenders.injectionresults.InjectionResult;
/* * Copyright (C) 2015 CaMnter yuanyu.camnter@gmail.com * * 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 com.camnter.robotlegs4android.swiftsuspenders; /** * Description:InjectionConfig * Created by:CaMnter */ public class InjectionConfig { /******************************************************************************************* * public properties * *******************************************************************************************/ public Class<?> request; public String injectionName; /******************************************************************************************* * private properties * *******************************************************************************************/ private Injector m_injector;
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/swiftsuspenders/injectionresults/InjectionResult.java // public class InjectionResult { // // /******************************************************************************************* // * constructor * // *******************************************************************************************/ // public InjectionResult() { // // } // // /******************************************************************************************* // * public methods * // *******************************************************************************************/ // /** // * {@inheritDoc} // * Get the Response // * 获取响应 // * // * @param injector injector // * @return Object // */ // public Object getResponse(Injector injector) { // return null; // } // // } // Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/swiftsuspenders/InjectionConfig.java import android.util.Log; import com.camnter.robotlegs4android.swiftsuspenders.injectionresults.InjectionResult; /* * Copyright (C) 2015 CaMnter yuanyu.camnter@gmail.com * * 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 com.camnter.robotlegs4android.swiftsuspenders; /** * Description:InjectionConfig * Created by:CaMnter */ public class InjectionConfig { /******************************************************************************************* * public properties * *******************************************************************************************/ public Class<?> request; public String injectionName; /******************************************************************************************* * private properties * *******************************************************************************************/ private Injector m_injector;
private InjectionResult m_result;
CaMnter/Robotlegs4Android
robotlegs4android/src/main/java/com/camnter/robotlegs4android/expand/IFragmentActivity.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/core/IListener.java // public interface IListener { // /** // * {@inheritDoc} // * @return The name of the listener:listener的名称 // */ // String getName(); // // /** // * {@inheritDoc} // * @return The type of the listener:listener的类型 // */ // String getType(); // // /** // * {@inheritDoc} // * @param type // * set type of the listener 设置listener的类型 // */ // void setType(String type); // // /** // * {@inheritDoc} // * @param event // * <code>com.camnter.robotlegs4android.base.Event</code> // */ // void onHandle(Event event); // // }
import android.view.KeyEvent; import com.camnter.robotlegs4android.core.IListener;
/* * Copyright (C) 2015 CaMnter yuanyu.camnter@gmail.com * * 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 com.camnter.robotlegs4android.expand; /** * Description:IContextActivity * Created by:CaMnter */ public interface IFragmentActivity { /** * Through monitoring the back key, management robotlegs4android into fragments * 通过监听回退键,管理robotlegs4android注入的Fragment * * @param event event * @return boolean */ boolean goBack(KeyEvent event); /** * 获取robotlegs4android的回退键listener * Get the robotlegs4android's back click listener * * @return IListener */
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/core/IListener.java // public interface IListener { // /** // * {@inheritDoc} // * @return The name of the listener:listener的名称 // */ // String getName(); // // /** // * {@inheritDoc} // * @return The type of the listener:listener的类型 // */ // String getType(); // // /** // * {@inheritDoc} // * @param type // * set type of the listener 设置listener的类型 // */ // void setType(String type); // // /** // * {@inheritDoc} // * @param event // * <code>com.camnter.robotlegs4android.base.Event</code> // */ // void onHandle(Event event); // // } // Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/expand/IFragmentActivity.java import android.view.KeyEvent; import com.camnter.robotlegs4android.core.IListener; /* * Copyright (C) 2015 CaMnter yuanyu.camnter@gmail.com * * 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 com.camnter.robotlegs4android.expand; /** * Description:IContextActivity * Created by:CaMnter */ public interface IFragmentActivity { /** * Through monitoring the back key, management robotlegs4android into fragments * 通过监听回退键,管理robotlegs4android注入的Fragment * * @param event event * @return boolean */ boolean goBack(KeyEvent event); /** * 获取robotlegs4android的回退键listener * Get the robotlegs4android's back click listener * * @return IListener */
IListener getOnBackClickListener();
CaMnter/Robotlegs4Android
app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/base/Event.java // public class Event { // // public static final String ADDED_TO_STAGE = "added_to_stage"; // public static final String REMOVED_FROM_STAGE = "removed_from_stage"; // public static final String ENTER_FRAME = "enter_frame"; // // private String _type; // private Object _target = null; // public Object data; // // public Event(String type) { // this._type = type; // } // // public Event(String type, Boolean bubble, Boolean cancelable) { // } // // public String getType() { // return this._type; // } // // public Object getTarget() { // return this._target; // } // // public void setTarget(Object target) { // this._target = target; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/bean/User.java // public class User implements Serializable { // // public String name; // // public String sign; // // }
import com.camnter.robotlegs4android.base.Event; import com.camnter.robotlegs4android.test.bean.User;
/* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.event; /** * Description:LoginEvent * Created by:CaMnter * Time:2015-11-07 23:05 */ public class LoginEvent extends Event { public static final String USER_LOGIN = "user_login"; public static final String USER_LOGOUT = "user_logout"; public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; public String name; public String password;
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/base/Event.java // public class Event { // // public static final String ADDED_TO_STAGE = "added_to_stage"; // public static final String REMOVED_FROM_STAGE = "removed_from_stage"; // public static final String ENTER_FRAME = "enter_frame"; // // private String _type; // private Object _target = null; // public Object data; // // public Event(String type) { // this._type = type; // } // // public Event(String type, Boolean bubble, Boolean cancelable) { // } // // public String getType() { // return this._type; // } // // public Object getTarget() { // return this._target; // } // // public void setTarget(Object target) { // this._target = target; // } // // } // // Path: app/src/main/java/com/camnter/robotlegs4android/test/bean/User.java // public class User implements Serializable { // // public String name; // // public String sign; // // } // Path: app/src/main/java/com/camnter/robotlegs4android/test/event/LoginEvent.java import com.camnter.robotlegs4android.base.Event; import com.camnter.robotlegs4android.test.bean.User; /* * Copyright (C) 2015 CaMnter 421482590@qq.com * * 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 com.camnter.robotlegs4android.test.event; /** * Description:LoginEvent * Created by:CaMnter * Time:2015-11-07 23:05 */ public class LoginEvent extends Event { public static final String USER_LOGIN = "user_login"; public static final String USER_LOGOUT = "user_logout"; public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_CONTROLLER = "user_login_success_from_model_to_controller"; public static final String USER_LOGIN_SUCCESS_FROM_MODEL_TO_VIEW = "user_login_success_from_model_to_view"; public static final String USER_LOGIN_SUCCESS_FROM_CONTROLLER_TO_VIEW = "user_login_success_from_controller_to_view"; public String name; public String password;
public User user;
CaMnter/Robotlegs4Android
robotlegs4android/src/main/java/com/camnter/robotlegs4android/core/IListener.java
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/base/Event.java // public class Event { // // public static final String ADDED_TO_STAGE = "added_to_stage"; // public static final String REMOVED_FROM_STAGE = "removed_from_stage"; // public static final String ENTER_FRAME = "enter_frame"; // // private String _type; // private Object _target = null; // public Object data; // // public Event(String type) { // this._type = type; // } // // public Event(String type, Boolean bubble, Boolean cancelable) { // } // // public String getType() { // return this._type; // } // // public Object getTarget() { // return this._target; // } // // public void setTarget(Object target) { // this._target = target; // } // // }
import com.camnter.robotlegs4android.base.Event;
/* * Copyright (C) 2015 CaMnter yuanyu.camnter@gmail.com * * 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 com.camnter.robotlegs4android.core; /** * Description:IListener * Created by:CaMnter */ public interface IListener { /** * {@inheritDoc} * @return The name of the listener:listener的名称 */ String getName(); /** * {@inheritDoc} * @return The type of the listener:listener的类型 */ String getType(); /** * {@inheritDoc} * @param type * set type of the listener 设置listener的类型 */ void setType(String type); /** * {@inheritDoc} * @param event * <code>com.camnter.robotlegs4android.base.Event</code> */
// Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/base/Event.java // public class Event { // // public static final String ADDED_TO_STAGE = "added_to_stage"; // public static final String REMOVED_FROM_STAGE = "removed_from_stage"; // public static final String ENTER_FRAME = "enter_frame"; // // private String _type; // private Object _target = null; // public Object data; // // public Event(String type) { // this._type = type; // } // // public Event(String type, Boolean bubble, Boolean cancelable) { // } // // public String getType() { // return this._type; // } // // public Object getTarget() { // return this._target; // } // // public void setTarget(Object target) { // this._target = target; // } // // } // Path: robotlegs4android/src/main/java/com/camnter/robotlegs4android/core/IListener.java import com.camnter.robotlegs4android.base.Event; /* * Copyright (C) 2015 CaMnter yuanyu.camnter@gmail.com * * 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 com.camnter.robotlegs4android.core; /** * Description:IListener * Created by:CaMnter */ public interface IListener { /** * {@inheritDoc} * @return The name of the listener:listener的名称 */ String getName(); /** * {@inheritDoc} * @return The type of the listener:listener的类型 */ String getType(); /** * {@inheritDoc} * @param type * set type of the listener 设置listener的类型 */ void setType(String type); /** * {@inheritDoc} * @param event * <code>com.camnter.robotlegs4android.base.Event</code> */
void onHandle(Event event);
Roba1993/octo-chat
src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/AboutDialog.java
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // }
import com.teamdev.jxbrowser.chromium.ProductInfo; import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Calendar;
/* * Copyright (c) 2000-2015 TeamDev Ltd. All rights reserved. * TeamDev PROPRIETARY and CONFIDENTIAL. * Use is subject to license terms. */ package com.teamdev.jxbrowser.chromium.demo; /** * @author TeamDev Ltd. */ public class AboutDialog extends JDialog { public AboutDialog(Frame owner) { super(owner, "About JxBrowser Demo", true); initContent(); initKeyStroke(); setResizable(false); pack(); setSize(250, getHeight()); setLocationRelativeTo(owner); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } private void initContent() { JLabel icon = new JLabel();
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // } // Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/AboutDialog.java import com.teamdev.jxbrowser.chromium.ProductInfo; import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Calendar; /* * Copyright (c) 2000-2015 TeamDev Ltd. All rights reserved. * TeamDev PROPRIETARY and CONFIDENTIAL. * Use is subject to license terms. */ package com.teamdev.jxbrowser.chromium.demo; /** * @author TeamDev Ltd. */ public class AboutDialog extends JDialog { public AboutDialog(Frame owner) { super(owner, "About JxBrowser Demo", true); initContent(); initKeyStroke(); setResizable(false); pack(); setSize(250, getHeight()); setLocationRelativeTo(owner); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } private void initContent() { JLabel icon = new JLabel();
icon.setIcon(Resources.getIcon("jxbrowser32x32.png"));
Roba1993/octo-chat
src/main/java/de/robertschuette/octochat/chats/Chat.java
// Path: src/main/java/de/robertschuette/octochat/model/ChatSettings.java // public class ChatSettings { // // private String name; // private boolean notifications; // // // /** // * Constructor to create a setting object. // * // * @param name unique name of the chat // */ // public ChatSettings(String name) { // this.name = name; // notifications = true; // } // // // /******** Getter & Setter **************/ // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isNotifications() { // return notifications; // } // // public void setNotifications(boolean notifications) { // this.notifications = notifications; // } // } // // Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // }
import de.robertschuette.octochat.model.ChatSettings; import de.robertschuette.octochat.util.Util; import javafx.scene.layout.Region; import java.io.File;
package de.robertschuette.octochat.chats; /** * This class defines a Chat and every chat which should be * manageable over the chat handler must extend this class. * * @author Robert Schütte */ public abstract class Chat extends Region { /** * Returns a icon which indicates the chat. * * @return the icon path in a File object */ public File getIcon() {
// Path: src/main/java/de/robertschuette/octochat/model/ChatSettings.java // public class ChatSettings { // // private String name; // private boolean notifications; // // // /** // * Constructor to create a setting object. // * // * @param name unique name of the chat // */ // public ChatSettings(String name) { // this.name = name; // notifications = true; // } // // // /******** Getter & Setter **************/ // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isNotifications() { // return notifications; // } // // public void setNotifications(boolean notifications) { // this.notifications = notifications; // } // } // // Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // } // Path: src/main/java/de/robertschuette/octochat/chats/Chat.java import de.robertschuette.octochat.model.ChatSettings; import de.robertschuette.octochat.util.Util; import javafx.scene.layout.Region; import java.io.File; package de.robertschuette.octochat.chats; /** * This class defines a Chat and every chat which should be * manageable over the chat handler must extend this class. * * @author Robert Schütte */ public abstract class Chat extends Region { /** * Returns a icon which indicates the chat. * * @return the icon path in a File object */ public File getIcon() {
return new File(Util.getResourcesPath()+"/img/octo.png");
Roba1993/octo-chat
src/main/java/de/robertschuette/octochat/chats/Chat.java
// Path: src/main/java/de/robertschuette/octochat/model/ChatSettings.java // public class ChatSettings { // // private String name; // private boolean notifications; // // // /** // * Constructor to create a setting object. // * // * @param name unique name of the chat // */ // public ChatSettings(String name) { // this.name = name; // notifications = true; // } // // // /******** Getter & Setter **************/ // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isNotifications() { // return notifications; // } // // public void setNotifications(boolean notifications) { // this.notifications = notifications; // } // } // // Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // }
import de.robertschuette.octochat.model.ChatSettings; import de.robertschuette.octochat.util.Util; import javafx.scene.layout.Region; import java.io.File;
package de.robertschuette.octochat.chats; /** * This class defines a Chat and every chat which should be * manageable over the chat handler must extend this class. * * @author Robert Schütte */ public abstract class Chat extends Region { /** * Returns a icon which indicates the chat. * * @return the icon path in a File object */ public File getIcon() { return new File(Util.getResourcesPath()+"/img/octo.png"); } /** * Returns the actual settings of the chat. * * @return the chat settings */
// Path: src/main/java/de/robertschuette/octochat/model/ChatSettings.java // public class ChatSettings { // // private String name; // private boolean notifications; // // // /** // * Constructor to create a setting object. // * // * @param name unique name of the chat // */ // public ChatSettings(String name) { // this.name = name; // notifications = true; // } // // // /******** Getter & Setter **************/ // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isNotifications() { // return notifications; // } // // public void setNotifications(boolean notifications) { // this.notifications = notifications; // } // } // // Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // } // Path: src/main/java/de/robertschuette/octochat/chats/Chat.java import de.robertschuette.octochat.model.ChatSettings; import de.robertschuette.octochat.util.Util; import javafx.scene.layout.Region; import java.io.File; package de.robertschuette.octochat.chats; /** * This class defines a Chat and every chat which should be * manageable over the chat handler must extend this class. * * @author Robert Schütte */ public abstract class Chat extends Region { /** * Returns a icon which indicates the chat. * * @return the icon path in a File object */ public File getIcon() { return new File(Util.getResourcesPath()+"/img/octo.png"); } /** * Returns the actual settings of the chat. * * @return the chat settings */
abstract public ChatSettings getChatSettings();
Roba1993/octo-chat
src/main/java/de/robertschuette/octochat/chats/ChatWhatsapp.java
// Path: src/main/java/de/robertschuette/octochat/model/ChatData.java // public class ChatData { // private Chat chat; // private String userId; // private String userName; // private String lastMessage; // private String lastMessageTime; // private boolean lastMessageUnread; // private boolean isOnline; // // /** // * Constructor to create a new chat data object. // * // * @param chat set the chat // * @param userId id of the user // * @param userName name of the user // */ // public ChatData(Chat chat, String userId, String userName) { // this.chat = chat; // this.userId = userId; // this.userName = userName; // // lastMessage = ""; // lastMessageTime = ""; // } // // @Override // public String toString() { // return "> "+userId+" # "+userName+" : "+lastMessage+" - "+lastMessageTime // +" "+(lastMessageUnread ? "new" : "old")+" "+(isOnline ? "on" : "off") ; // } // // /*************** Getter & Setter *****************/ // public Chat getChat() { // return chat; // } // // public void setChat(Chat chat) { // this.chat = chat; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getLastMessage() { // return lastMessage; // } // // public void setLastMessage(String lastMessage) { // this.lastMessage = lastMessage; // } // // public String getLastMessageTime() { // return lastMessageTime; // } // // public void setLastMessageTime(String lastMessageTime) { // this.lastMessageTime = lastMessageTime; // } // // public boolean isLastMessageUnread() { // return lastMessageUnread; // } // // public void setLastMessageUnread(boolean lastMessageUnread) { // this.lastMessageUnread = lastMessageUnread; // } // // public boolean isOnline() { // return isOnline; // } // // public void setIsOnline(boolean isOnline) { // this.isOnline = isOnline; // } // } // // Path: src/main/java/de/robertschuette/octochat/model/ChatSettings.java // public class ChatSettings { // // private String name; // private boolean notifications; // // // /** // * Constructor to create a setting object. // * // * @param name unique name of the chat // */ // public ChatSettings(String name) { // this.name = name; // notifications = true; // } // // // /******** Getter & Setter **************/ // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isNotifications() { // return notifications; // } // // public void setNotifications(boolean notifications) { // this.notifications = notifications; // } // } // // Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // }
import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.BrowserContext; import com.teamdev.jxbrowser.chromium.LoggerProvider; import com.teamdev.jxbrowser.chromium.dom.By; import com.teamdev.jxbrowser.chromium.dom.DOMElement; import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent; import com.teamdev.jxbrowser.chromium.events.LoadAdapter; import com.teamdev.jxbrowser.chromium.javafx.BrowserView; import de.robertschuette.octochat.model.ChatData; import de.robertschuette.octochat.model.ChatSettings; import de.robertschuette.octochat.util.Util; import java.io.File; import java.util.List; import java.util.logging.Level;
package de.robertschuette.octochat.chats; /** * Create a new WhatsApp window to communicate with. * * @author Robert Schütte */ public class ChatWhatsapp extends Chat implements Runnable { private ChatHandler chatHandler; private Browser engine; private BrowserView browser;
// Path: src/main/java/de/robertschuette/octochat/model/ChatData.java // public class ChatData { // private Chat chat; // private String userId; // private String userName; // private String lastMessage; // private String lastMessageTime; // private boolean lastMessageUnread; // private boolean isOnline; // // /** // * Constructor to create a new chat data object. // * // * @param chat set the chat // * @param userId id of the user // * @param userName name of the user // */ // public ChatData(Chat chat, String userId, String userName) { // this.chat = chat; // this.userId = userId; // this.userName = userName; // // lastMessage = ""; // lastMessageTime = ""; // } // // @Override // public String toString() { // return "> "+userId+" # "+userName+" : "+lastMessage+" - "+lastMessageTime // +" "+(lastMessageUnread ? "new" : "old")+" "+(isOnline ? "on" : "off") ; // } // // /*************** Getter & Setter *****************/ // public Chat getChat() { // return chat; // } // // public void setChat(Chat chat) { // this.chat = chat; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getLastMessage() { // return lastMessage; // } // // public void setLastMessage(String lastMessage) { // this.lastMessage = lastMessage; // } // // public String getLastMessageTime() { // return lastMessageTime; // } // // public void setLastMessageTime(String lastMessageTime) { // this.lastMessageTime = lastMessageTime; // } // // public boolean isLastMessageUnread() { // return lastMessageUnread; // } // // public void setLastMessageUnread(boolean lastMessageUnread) { // this.lastMessageUnread = lastMessageUnread; // } // // public boolean isOnline() { // return isOnline; // } // // public void setIsOnline(boolean isOnline) { // this.isOnline = isOnline; // } // } // // Path: src/main/java/de/robertschuette/octochat/model/ChatSettings.java // public class ChatSettings { // // private String name; // private boolean notifications; // // // /** // * Constructor to create a setting object. // * // * @param name unique name of the chat // */ // public ChatSettings(String name) { // this.name = name; // notifications = true; // } // // // /******** Getter & Setter **************/ // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isNotifications() { // return notifications; // } // // public void setNotifications(boolean notifications) { // this.notifications = notifications; // } // } // // Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // } // Path: src/main/java/de/robertschuette/octochat/chats/ChatWhatsapp.java import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.BrowserContext; import com.teamdev.jxbrowser.chromium.LoggerProvider; import com.teamdev.jxbrowser.chromium.dom.By; import com.teamdev.jxbrowser.chromium.dom.DOMElement; import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent; import com.teamdev.jxbrowser.chromium.events.LoadAdapter; import com.teamdev.jxbrowser.chromium.javafx.BrowserView; import de.robertschuette.octochat.model.ChatData; import de.robertschuette.octochat.model.ChatSettings; import de.robertschuette.octochat.util.Util; import java.io.File; import java.util.List; import java.util.logging.Level; package de.robertschuette.octochat.chats; /** * Create a new WhatsApp window to communicate with. * * @author Robert Schütte */ public class ChatWhatsapp extends Chat implements Runnable { private ChatHandler chatHandler; private Browser engine; private BrowserView browser;
private ChatSettings chatSettings;
Roba1993/octo-chat
src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/JSConsole.java
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // }
import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.JSValue; import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
console = new JTextArea(); console.setFont(new Font("Consolas", Font.PLAIN, 12)); console.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); console.setEditable(false); console.setWrapStyleWord(true); console.setLineWrap(true); console.setText(""); JScrollPane scrollPane = new JScrollPane(console); scrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY)); return scrollPane; } private JComponent createTitle() { JPanel panel = new JPanel(new BorderLayout()); // panel.setBackground(new Color(182, 191, 207)); panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); panel.add(createTitleLabel(), BorderLayout.WEST); panel.add(createCloseButton(), BorderLayout.EAST); return panel; } private static JComponent createTitleLabel() { return new JLabel("JavaScript Console"); } private JComponent createCloseButton() { JButton closeButton = new JButton(); closeButton.setOpaque(false); closeButton.setToolTipText("Close JavaScript Console"); closeButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // } // Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/JSConsole.java import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.JSValue; import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; console = new JTextArea(); console.setFont(new Font("Consolas", Font.PLAIN, 12)); console.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); console.setEditable(false); console.setWrapStyleWord(true); console.setLineWrap(true); console.setText(""); JScrollPane scrollPane = new JScrollPane(console); scrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY)); return scrollPane; } private JComponent createTitle() { JPanel panel = new JPanel(new BorderLayout()); // panel.setBackground(new Color(182, 191, 207)); panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); panel.add(createTitleLabel(), BorderLayout.WEST); panel.add(createCloseButton(), BorderLayout.EAST); return panel; } private static JComponent createTitleLabel() { return new JLabel("JavaScript Console"); } private JComponent createCloseButton() { JButton closeButton = new JButton(); closeButton.setOpaque(false); closeButton.setToolTipText("Close JavaScript Console"); closeButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
closeButton.setPressedIcon(Resources.getIcon("close-pressed.png"));
Roba1993/octo-chat
src/main/java/de/robertschuette/octochat/os/MacSpecific.java
// Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // }
import com.apple.eawt.Application; import com.aquafx_project.AquaFx; import de.robertschuette.octochat.util.Util; import javafx.stage.Stage; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package de.robertschuette.octochat.os; /** * Class for Mac OS X specific operations. */ public class MacSpecific extends OsSpecific { /** * This functions styles the whole gui * in a mac os x specific view and set * the menu bar in the top menu. */ @Override public void setSpecificStyle(Stage stage) { // style the whole application AquaFx.style(); // set the mac os x dock icon
// Path: src/main/java/de/robertschuette/octochat/util/Util.java // public class Util { // private static String resourcesPath; // // /** // * This function returns the absolute path to the // * resources directory as String. // * // * @return resources dir path // */ // public static String getResourcesPath() { // if(resourcesPath != null) { // return resourcesPath; // } // // String jarDir = "."; // // // get the path of the .jar // try { // CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource(); // File jarFile = new File(codeSource.getLocation().toURI().getPath()); // jarDir = jarFile.getParentFile().getPath(); // } catch (URISyntaxException e) { // e.printStackTrace(); // } // // File f = new File(jarDir+"/data"); // if(f.exists() && f.isDirectory()) { // resourcesPath = jarDir+"/data/"; // } // else { // resourcesPath = jarDir+"/"; // } // // return resourcesPath; // } // // // /** // * Function to get the whole dom tree as String // * ONLY FOR DEV-ANALYSE!!! // * // * @param doc dom to parse // * @return dom as string // */ // public static String getStringFromDoc(Document doc) { // try { // DOMSource domSource = new DOMSource(doc); // StringWriter writer = new StringWriter(); // StreamResult result = new StreamResult(writer); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer transformer = tf.newTransformer(); // transformer.transform(domSource, result); // writer.flush(); // return writer.toString(); // } catch (TransformerException ex) { // ex.printStackTrace(); // return null; // } // } // } // Path: src/main/java/de/robertschuette/octochat/os/MacSpecific.java import com.apple.eawt.Application; import com.aquafx_project.AquaFx; import de.robertschuette.octochat.util.Util; import javafx.stage.Stage; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; package de.robertschuette.octochat.os; /** * Class for Mac OS X specific operations. */ public class MacSpecific extends OsSpecific { /** * This functions styles the whole gui * in a mac os x specific view and set * the menu bar in the top menu. */ @Override public void setSpecificStyle(Stage stage) { // style the whole application AquaFx.style(); // set the mac os x dock icon
Image image = new ImageIcon(Util.getResourcesPath()+"/img/octo.png").getImage();
Roba1993/octo-chat
src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/TabCaption.java
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // }
import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener;
defaultBackground = getBackground(); setLayout(new BorderLayout()); setOpaque(false); add(createLabel(), BorderLayout.CENTER); add(createCloseButton(), BorderLayout.EAST); } private JComponent createLabel() { label = new JLabel(); label.setOpaque(false); label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { firePropertyChange("TabClicked", false, true); } if (e.getButton() == MouseEvent.BUTTON2) { firePropertyChange("CloseButtonPressed", false, true); } } }); return label; } private JComponent createCloseButton() { JButton closeButton = new JButton(); closeButton.setOpaque(false); closeButton.setToolTipText("Close"); closeButton.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // } // Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/TabCaption.java import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; defaultBackground = getBackground(); setLayout(new BorderLayout()); setOpaque(false); add(createLabel(), BorderLayout.CENTER); add(createCloseButton(), BorderLayout.EAST); } private JComponent createLabel() { label = new JLabel(); label.setOpaque(false); label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { firePropertyChange("TabClicked", false, true); } if (e.getButton() == MouseEvent.BUTTON2) { firePropertyChange("CloseButtonPressed", false, true); } } }); return label; } private JComponent createCloseButton() { JButton closeButton = new JButton(); closeButton.setOpaque(false); closeButton.setToolTipText("Close"); closeButton.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
closeButton.setPressedIcon(Resources.getIcon("close-pressed.png"));
Roba1993/octo-chat
src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/ToolBar.java
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // }
import com.teamdev.jxbrowser.chromium.swing.BrowserView; import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.BrowserPreferences; import com.teamdev.jxbrowser.chromium.EditorCommand; import com.teamdev.jxbrowser.chromium.SavePageType; import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import com.teamdev.jxbrowser.chromium.events.*; import com.teamdev.jxbrowser.chromium.internal.Environment; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.*; import java.io.File;
}); } private static JButton createForwardButton(final Browser browser) { return createButton("Forward", new AbstractAction() { public void actionPerformed(ActionEvent e) { browser.goForward(); } }); } private static JButton createRefreshButton(final Browser browser) { return createButton("Refresh", new AbstractAction() { public void actionPerformed(ActionEvent e) { browser.reload(); } }); } private static JButton createStopButton(final Browser browser) { return createButton("Stop", new AbstractAction() { public void actionPerformed(ActionEvent e) { browser.stop(); } }); } private static JButton createButton(String caption, Action action) { ActionButton button = new ActionButton(caption, action); String imageName = caption.toLowerCase();
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // } // Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/ToolBar.java import com.teamdev.jxbrowser.chromium.swing.BrowserView; import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.BrowserPreferences; import com.teamdev.jxbrowser.chromium.EditorCommand; import com.teamdev.jxbrowser.chromium.SavePageType; import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import com.teamdev.jxbrowser.chromium.events.*; import com.teamdev.jxbrowser.chromium.internal.Environment; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.*; import java.io.File; }); } private static JButton createForwardButton(final Browser browser) { return createButton("Forward", new AbstractAction() { public void actionPerformed(ActionEvent e) { browser.goForward(); } }); } private static JButton createRefreshButton(final Browser browser) { return createButton("Refresh", new AbstractAction() { public void actionPerformed(ActionEvent e) { browser.reload(); } }); } private static JButton createStopButton(final Browser browser) { return createButton("Stop", new AbstractAction() { public void actionPerformed(ActionEvent e) { browser.stop(); } }); } private static JButton createButton(String caption, Action action) { ActionButton button = new ActionButton(caption, action); String imageName = caption.toLowerCase();
button.setIcon(Resources.getIcon(imageName + ".png"));
Roba1993/octo-chat
src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/JxBrowserDemo.java
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // }
import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent;
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "JxBrowser Demo"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JPopupMenu.setDefaultLightWeightPopupEnabled(false); } public static void main(String[] args) throws Exception { initEnvironment(); SwingUtilities.invokeLater(new Runnable() { public void run() { initAndDisplayUI(); } }); } private static void initAndDisplayUI() { final TabbedPane tabbedPane = new TabbedPane(); insertTab(tabbedPane, TabFactory.createFirstTab()); insertNewTabButton(tabbedPane); JFrame frame = new JFrame("JxBrowser Demo"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { tabbedPane.disposeAllTabs(); } }); frame.add(tabbedPane, BorderLayout.CENTER); frame.setSize(1024, 768); frame.setLocationRelativeTo(null);
// Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/resources/Resources.java // public class Resources { // // public static ImageIcon getIcon(String fileName) { // return new ImageIcon(Resources.class.getResource(fileName)); // } // } // Path: src/lib/jxbrowser-5/demo/src/com/teamdev/jxbrowser/chromium/demo/JxBrowserDemo.java import com.teamdev.jxbrowser.chromium.demo.resources.Resources; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; System.setProperty("com.apple.mrj.application.apple.menu.about.name", "JxBrowser Demo"); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JPopupMenu.setDefaultLightWeightPopupEnabled(false); } public static void main(String[] args) throws Exception { initEnvironment(); SwingUtilities.invokeLater(new Runnable() { public void run() { initAndDisplayUI(); } }); } private static void initAndDisplayUI() { final TabbedPane tabbedPane = new TabbedPane(); insertTab(tabbedPane, TabFactory.createFirstTab()); insertNewTabButton(tabbedPane); JFrame frame = new JFrame("JxBrowser Demo"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { tabbedPane.disposeAllTabs(); } }); frame.add(tabbedPane, BorderLayout.CENTER); frame.setSize(1024, 768); frame.setLocationRelativeTo(null);
frame.setIconImage(Resources.getIcon("jxbrowser16x16.png").getImage());
EsotericSoftware/clippy
src/com/esotericsoftware/clippy/AutoLock.java
// Path: src/com/esotericsoftware/clippy/Win.java // static public class LASTINPUTINFO extends Structure { // public int cbSize = size(); // public int dwTime; // // protected List getFieldOrder () { // return Arrays.asList(new String[] {"cbSize", "dwTime"}); // } // }
import java.util.Timer; import java.util.TimerTask; import com.esotericsoftware.clippy.Win.LASTINPUTINFO;
package com.esotericsoftware.clippy; public class AutoLock { static final Clippy clippy = Clippy.instance;
// Path: src/com/esotericsoftware/clippy/Win.java // static public class LASTINPUTINFO extends Structure { // public int cbSize = size(); // public int dwTime; // // protected List getFieldOrder () { // return Arrays.asList(new String[] {"cbSize", "dwTime"}); // } // } // Path: src/com/esotericsoftware/clippy/AutoLock.java import java.util.Timer; import java.util.TimerTask; import com.esotericsoftware.clippy.Win.LASTINPUTINFO; package com.esotericsoftware.clippy; public class AutoLock { static final Clippy clippy = Clippy.instance;
final LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
logful/logful-android
logful/src/main/java/com/getui/logful/entity/AttachmentFileMeta.java
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // }
import com.getui.logful.LoggerConstants;
package com.getui.logful.entity; public class AttachmentFileMeta { private long id; private String filename; private int location; private int sequence; private long createTime; private long deleteTime; private int status; private String fileMD5; public AttachmentFileMeta() { this.id = -1;
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // } // Path: logful/src/main/java/com/getui/logful/entity/AttachmentFileMeta.java import com.getui.logful.LoggerConstants; package com.getui.logful.entity; public class AttachmentFileMeta { private long id; private String filename; private int location; private int sequence; private long createTime; private long deleteTime; private int status; private String fileMD5; public AttachmentFileMeta() { this.id = -1;
this.status = LoggerConstants.STATE_NORMAL;
logful/logful-android
logful/src/main/java/com/getui/logful/util/SystemConfig.java
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // }
import com.getui.logful.LoggerConstants;
package com.getui.logful.util; public class SystemConfig { private String baseUrl; private String aliasName; private String appKeyString; private String appSecretString; private static class ClassHolder { static SystemConfig config = new SystemConfig(); } public static SystemConfig config() { return ClassHolder.config; } public static String baseUrl() { SystemConfig config = SystemConfig.config(); if (StringUtils.isEmpty(config.baseUrl)) {
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // } // Path: logful/src/main/java/com/getui/logful/util/SystemConfig.java import com.getui.logful.LoggerConstants; package com.getui.logful.util; public class SystemConfig { private String baseUrl; private String aliasName; private String appKeyString; private String appSecretString; private static class ClassHolder { static SystemConfig config = new SystemConfig(); } public static SystemConfig config() { return ClassHolder.config; } public static String baseUrl() { SystemConfig config = SystemConfig.config(); if (StringUtils.isEmpty(config.baseUrl)) {
return LoggerConstants.API_BASE_URL;
logful/logful-android
logful/src/main/java/com/getui/logful/appender/AbstractOutputStreamAppender.java
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil;
package com.getui.logful.appender; public abstract class AbstractOutputStreamAppender<M extends OutputStreamManager> extends AbstractAppender { protected final boolean immediateFlush; private final M manager; private final ReadWriteLock rwLock = new ReentrantReadWriteLock(); private final Lock readLock = rwLock.readLock(); private boolean isWriting;
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/appender/AbstractOutputStreamAppender.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil; package com.getui.logful.appender; public abstract class AbstractOutputStreamAppender<M extends OutputStreamManager> extends AbstractAppender { protected final boolean immediateFlush; private final M manager; private final ReadWriteLock rwLock = new ReentrantReadWriteLock(); private final Lock readLock = rwLock.readLock(); private boolean isWriting;
protected AbstractOutputStreamAppender(String loggerName, Layout layout, boolean ignoreExceptions,
logful/logful-android
logful/src/main/java/com/getui/logful/appender/AbstractOutputStreamAppender.java
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil;
@Override public void start() { super.start(); } @Override public void stop() { super.stop(); manager.release(); } @Override public boolean writing() { return isWriting; } @Override public synchronized void append(LogEvent logEvent) { readLock.lock(); isWriting = true; try { final byte[] bytes = getLayout().toBytes(logEvent); if (bytes.length > 0) { manager.write(bytes); if (this.immediateFlush) { manager.flush(); } } } catch (final AppenderLoggingException e) {
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/appender/AbstractOutputStreamAppender.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil; @Override public void start() { super.start(); } @Override public void stop() { super.stop(); manager.release(); } @Override public boolean writing() { return isWriting; } @Override public synchronized void append(LogEvent logEvent) { readLock.lock(); isWriting = true; try { final byte[] bytes = getLayout().toBytes(logEvent); if (bytes.length > 0) { manager.write(bytes); if (this.immediateFlush) { manager.flush(); } } } catch (final AppenderLoggingException e) {
LogUtil.e("AbstractOutputStreamAppender", "", e);
logful/logful-android
logful/src/main/java/com/getui/logful/appender/FileManager.java
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil;
package com.getui.logful.appender; public class FileManager extends OutputStreamManager { private static final FileManagerFactory FACTORY = new FileManagerFactory(); private final boolean append; private final boolean locking; private final int bufferSize; protected FileManager(final String filePath, final OutputStream os, final boolean append, final boolean locking,
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/appender/FileManager.java import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil; package com.getui.logful.appender; public class FileManager extends OutputStreamManager { private static final FileManagerFactory FACTORY = new FileManagerFactory(); private final boolean append; private final boolean locking; private final int bufferSize; protected FileManager(final String filePath, final OutputStream os, final boolean append, final boolean locking,
final Layout layout, final int bufferSize, final long fileSize) {
logful/logful-android
logful/src/main/java/com/getui/logful/appender/FileManager.java
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil;
this.locking = locking; this.bufferedIO = bufferedIO; this.bufferSize = bufferSize; this.layout = layout; } } private static class FileManagerFactory implements ManagerFactory<FileManager, FactoryData> { @Override public FileManager createManager(String filePath, FactoryData data) { final File file = new File(filePath); final File parent = file.getParentFile(); if (null != parent && !parent.exists()) { boolean result = parent.mkdirs(); } OutputStream outputStream; // Start file size. long fileSize = file.length(); try { outputStream = new FileOutputStream(filePath, data.append); int bufferSize = data.bufferSize; if (data.bufferedIO) { outputStream = new BufferedOutputStream(outputStream, bufferSize); } else { bufferSize = -1; } return new FileManager(filePath, outputStream, data.append, data.locking, data.layout, bufferSize, fileSize); } catch (final FileNotFoundException e) {
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/appender/FileManager.java import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil; this.locking = locking; this.bufferedIO = bufferedIO; this.bufferSize = bufferSize; this.layout = layout; } } private static class FileManagerFactory implements ManagerFactory<FileManager, FactoryData> { @Override public FileManager createManager(String filePath, FactoryData data) { final File file = new File(filePath); final File parent = file.getParentFile(); if (null != parent && !parent.exists()) { boolean result = parent.mkdirs(); } OutputStream outputStream; // Start file size. long fileSize = file.length(); try { outputStream = new FileOutputStream(filePath, data.append); int bufferSize = data.bufferSize; if (data.bufferedIO) { outputStream = new BufferedOutputStream(outputStream, bufferSize); } else { bufferSize = -1; } return new FileManager(filePath, outputStream, data.append, data.locking, data.layout, bufferSize, fileSize); } catch (final FileNotFoundException e) {
LogUtil.e("FileManagerFactory", "", e);
logful/logful-android
logful/src/main/java/com/getui/logful/appender/OutputStreamManager.java
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import java.io.IOException; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil;
package com.getui.logful.appender; public class OutputStreamManager extends AbstractManager { private static final String TAG = "OutputStreamManager"; private volatile OutputStream outputStream;
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/appender/OutputStreamManager.java import java.io.IOException; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil; package com.getui.logful.appender; public class OutputStreamManager extends AbstractManager { private static final String TAG = "OutputStreamManager"; private volatile OutputStream outputStream;
protected final Layout layout;
logful/logful-android
logful/src/main/java/com/getui/logful/appender/OutputStreamManager.java
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import java.io.IOException; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil;
this.fileSize = fileSize; } @Override protected void releaseSub() { close(); } protected OutputStream getOutputStream() { return outputStream; } protected void setOutputStream(final OutputStream outputStream) { this.outputStream = outputStream; } protected long getFileSize() { return fileSize; } protected void write(final byte[] bytes) { write(bytes, 0, bytes.length); } protected synchronized void write(final byte[] bytes, final int offset, final int length) { try { outputStream.write(bytes, offset, length); // 记录写入的字节长度 fileSize += length; } catch (final IOException e) {
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/appender/OutputStreamManager.java import java.io.IOException; import java.io.OutputStream; import com.getui.logful.layout.Layout; import com.getui.logful.util.LogUtil; this.fileSize = fileSize; } @Override protected void releaseSub() { close(); } protected OutputStream getOutputStream() { return outputStream; } protected void setOutputStream(final OutputStream outputStream) { this.outputStream = outputStream; } protected long getFileSize() { return fileSize; } protected void write(final byte[] bytes) { write(bytes, 0, bytes.length); } protected synchronized void write(final byte[] bytes, final int offset, final int length) { try { outputStream.write(bytes, offset, length); // 记录写入的字节长度 fileSize += length; } catch (final IOException e) {
LogUtil.e(TAG, "", e);
logful/logful-android
logful/src/main/java/com/getui/logful/LoggerConfigurator.java
// Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java // public class DefaultSecurityProvider implements SecurityProvider { // // private byte[] passwordData; // // private byte[] saltData; // // @Override // public byte[] password() { // if (passwordData == null) { // this.passwordData = SystemConfig.appKey().getBytes(); // } // return passwordData; // } // // @Override // public byte[] salt() { // if (saltData == null) { // this.saltData = UIDUtils.uid().getBytes(); // } // return saltData; // } // } // // Path: logful/src/main/java/com/getui/logful/security/SecurityProvider.java // public interface SecurityProvider { // // byte[] password(); // // byte[] salt(); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import com.getui.logful.security.DefaultSecurityProvider; import com.getui.logful.security.SecurityProvider; import com.getui.logful.util.LogUtil;
package com.getui.logful; public class LoggerConfigurator { /** * 单个日志文件最大字节数(单位:字节). */ private long logFileMaxSize; /** * 允许上传日志文件的网络环境. */ private int[] uploadNetworkType; /** * 需要上传的日志级别. */ private int[] uploadLogLevel; /** * 是否删除已经上传的日志文件. */ private boolean deleteUploadedLogFile; /** * 定时刷新日志系统(单位:秒). */ private long updateSystemFrequency; /** * 同时上传文件数量. */ private int activeUploadTask; /** * 同时写入日志文件数量. */ private int activeLogWriter; /** * 是否捕捉未捕捉的异常信息. */ private boolean caughtException; /** * 默认的 logger 名称. */ private String defaultLoggerName; /** * 默认的消息模板. */ private String defaultMsgLayout; /** * 截图文件压缩质量(1~100). */ private int screenshotQuality; /** * 截图文件缩放比例(0.1~1). */ private float screenshotScale; /** * 是否使用 jni 加密内容. */ private boolean useNativeCryptor;
// Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java // public class DefaultSecurityProvider implements SecurityProvider { // // private byte[] passwordData; // // private byte[] saltData; // // @Override // public byte[] password() { // if (passwordData == null) { // this.passwordData = SystemConfig.appKey().getBytes(); // } // return passwordData; // } // // @Override // public byte[] salt() { // if (saltData == null) { // this.saltData = UIDUtils.uid().getBytes(); // } // return saltData; // } // } // // Path: logful/src/main/java/com/getui/logful/security/SecurityProvider.java // public interface SecurityProvider { // // byte[] password(); // // byte[] salt(); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/LoggerConfigurator.java import com.getui.logful.security.DefaultSecurityProvider; import com.getui.logful.security.SecurityProvider; import com.getui.logful.util.LogUtil; package com.getui.logful; public class LoggerConfigurator { /** * 单个日志文件最大字节数(单位:字节). */ private long logFileMaxSize; /** * 允许上传日志文件的网络环境. */ private int[] uploadNetworkType; /** * 需要上传的日志级别. */ private int[] uploadLogLevel; /** * 是否删除已经上传的日志文件. */ private boolean deleteUploadedLogFile; /** * 定时刷新日志系统(单位:秒). */ private long updateSystemFrequency; /** * 同时上传文件数量. */ private int activeUploadTask; /** * 同时写入日志文件数量. */ private int activeLogWriter; /** * 是否捕捉未捕捉的异常信息. */ private boolean caughtException; /** * 默认的 logger 名称. */ private String defaultLoggerName; /** * 默认的消息模板. */ private String defaultMsgLayout; /** * 截图文件压缩质量(1~100). */ private int screenshotQuality; /** * 截图文件缩放比例(0.1~1). */ private float screenshotScale; /** * 是否使用 jni 加密内容. */ private boolean useNativeCryptor;
private SecurityProvider securityProvider;
logful/logful-android
logful/src/main/java/com/getui/logful/LoggerConfigurator.java
// Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java // public class DefaultSecurityProvider implements SecurityProvider { // // private byte[] passwordData; // // private byte[] saltData; // // @Override // public byte[] password() { // if (passwordData == null) { // this.passwordData = SystemConfig.appKey().getBytes(); // } // return passwordData; // } // // @Override // public byte[] salt() { // if (saltData == null) { // this.saltData = UIDUtils.uid().getBytes(); // } // return saltData; // } // } // // Path: logful/src/main/java/com/getui/logful/security/SecurityProvider.java // public interface SecurityProvider { // // byte[] password(); // // byte[] salt(); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import com.getui.logful.security.DefaultSecurityProvider; import com.getui.logful.security.SecurityProvider; import com.getui.logful.util.LogUtil;
*/ public boolean isUseNativeCryptor() { return useNativeCryptor; } /** * 获取设置的截图缩放比例. * * @return 缩放比例 */ public float getScreenshotScale() { return screenshotScale; } public static class Builder { private static final String TAG = "Builder"; private long logFileMaxSize = LoggerConstants.DEFAULT_LOG_FILE_MAX_SIZE; private int[] uploadNetworkType = LoggerConstants.DEFAULT_UPLOAD_NETWORK_TYPE; private int[] uploadLogLevel = LoggerConstants.DEFAULT_UPLOAD_LOG_LEVEL; private boolean deleteUploadedLogFile = LoggerConstants.DEFAULT_DELETE_UPLOADED_LOG_FILE; private long updateSystemFrequency = LoggerConstants.DEFAULT_UPDATE_SYSTEM_FREQUENCY; private int activeUploadTask = LoggerConstants.DEFAULT_ACTIVE_UPLOAD_TASK; private int activeLogWriter = LoggerConstants.DEFAULT_ACTIVE_LOG_WRITER; private boolean caughtException = LoggerConstants.DEFAULT_CAUGHT_EXCEPTION; private String defaultLoggerName = LoggerConstants.DEFAULT_LOGGER_NAME; private String defaultMsgLayout = LoggerConstants.DEFAULT_MSG_LAYOUT; private int screenshotQuality = LoggerConstants.DEFAULT_SCREENSHOT_QUALITY; private float screenshotScale = LoggerConstants.DEFAULT_SCREENSHOT_SCALE; private boolean useNativeCryptor = LoggerConstants.DEFAULT_USE_NATIVE_CRYPTOR;
// Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java // public class DefaultSecurityProvider implements SecurityProvider { // // private byte[] passwordData; // // private byte[] saltData; // // @Override // public byte[] password() { // if (passwordData == null) { // this.passwordData = SystemConfig.appKey().getBytes(); // } // return passwordData; // } // // @Override // public byte[] salt() { // if (saltData == null) { // this.saltData = UIDUtils.uid().getBytes(); // } // return saltData; // } // } // // Path: logful/src/main/java/com/getui/logful/security/SecurityProvider.java // public interface SecurityProvider { // // byte[] password(); // // byte[] salt(); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/LoggerConfigurator.java import com.getui.logful.security.DefaultSecurityProvider; import com.getui.logful.security.SecurityProvider; import com.getui.logful.util.LogUtil; */ public boolean isUseNativeCryptor() { return useNativeCryptor; } /** * 获取设置的截图缩放比例. * * @return 缩放比例 */ public float getScreenshotScale() { return screenshotScale; } public static class Builder { private static final String TAG = "Builder"; private long logFileMaxSize = LoggerConstants.DEFAULT_LOG_FILE_MAX_SIZE; private int[] uploadNetworkType = LoggerConstants.DEFAULT_UPLOAD_NETWORK_TYPE; private int[] uploadLogLevel = LoggerConstants.DEFAULT_UPLOAD_LOG_LEVEL; private boolean deleteUploadedLogFile = LoggerConstants.DEFAULT_DELETE_UPLOADED_LOG_FILE; private long updateSystemFrequency = LoggerConstants.DEFAULT_UPDATE_SYSTEM_FREQUENCY; private int activeUploadTask = LoggerConstants.DEFAULT_ACTIVE_UPLOAD_TASK; private int activeLogWriter = LoggerConstants.DEFAULT_ACTIVE_LOG_WRITER; private boolean caughtException = LoggerConstants.DEFAULT_CAUGHT_EXCEPTION; private String defaultLoggerName = LoggerConstants.DEFAULT_LOGGER_NAME; private String defaultMsgLayout = LoggerConstants.DEFAULT_MSG_LAYOUT; private int screenshotQuality = LoggerConstants.DEFAULT_SCREENSHOT_QUALITY; private float screenshotScale = LoggerConstants.DEFAULT_SCREENSHOT_SCALE; private boolean useNativeCryptor = LoggerConstants.DEFAULT_USE_NATIVE_CRYPTOR;
private SecurityProvider securityProvider = new DefaultSecurityProvider();
logful/logful-android
logful/src/main/java/com/getui/logful/LoggerConfigurator.java
// Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java // public class DefaultSecurityProvider implements SecurityProvider { // // private byte[] passwordData; // // private byte[] saltData; // // @Override // public byte[] password() { // if (passwordData == null) { // this.passwordData = SystemConfig.appKey().getBytes(); // } // return passwordData; // } // // @Override // public byte[] salt() { // if (saltData == null) { // this.saltData = UIDUtils.uid().getBytes(); // } // return saltData; // } // } // // Path: logful/src/main/java/com/getui/logful/security/SecurityProvider.java // public interface SecurityProvider { // // byte[] password(); // // byte[] salt(); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import com.getui.logful.security.DefaultSecurityProvider; import com.getui.logful.security.SecurityProvider; import com.getui.logful.util.LogUtil;
/** * 设置默认的消息模板. * * @param defaultMsgLayout 消息模板内容 */ public Builder setDefaultMsgLayout(String defaultMsgLayout) { this.defaultMsgLayout = defaultMsgLayout; return this; } /** * 设置默认的 logger 名称. * * @param defaultLoggerName Logger 名称 */ public Builder setDefaultLoggerName(String defaultLoggerName) { this.defaultLoggerName = defaultLoggerName; return this; } /** * 设置截图压缩质量. * * @param screenshotQuality 压缩数值 */ public Builder setScreenshotQuality(int screenshotQuality) { if (screenshotQuality >= 1 && screenshotQuality <= 100) { this.screenshotQuality = screenshotQuality; } else {
// Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java // public class DefaultSecurityProvider implements SecurityProvider { // // private byte[] passwordData; // // private byte[] saltData; // // @Override // public byte[] password() { // if (passwordData == null) { // this.passwordData = SystemConfig.appKey().getBytes(); // } // return passwordData; // } // // @Override // public byte[] salt() { // if (saltData == null) { // this.saltData = UIDUtils.uid().getBytes(); // } // return saltData; // } // } // // Path: logful/src/main/java/com/getui/logful/security/SecurityProvider.java // public interface SecurityProvider { // // byte[] password(); // // byte[] salt(); // // } // // Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/LoggerConfigurator.java import com.getui.logful.security.DefaultSecurityProvider; import com.getui.logful.security.SecurityProvider; import com.getui.logful.util.LogUtil; /** * 设置默认的消息模板. * * @param defaultMsgLayout 消息模板内容 */ public Builder setDefaultMsgLayout(String defaultMsgLayout) { this.defaultMsgLayout = defaultMsgLayout; return this; } /** * 设置默认的 logger 名称. * * @param defaultLoggerName Logger 名称 */ public Builder setDefaultLoggerName(String defaultLoggerName) { this.defaultLoggerName = defaultLoggerName; return this; } /** * 设置截图压缩质量. * * @param screenshotQuality 压缩数值 */ public Builder setScreenshotQuality(int screenshotQuality) { if (screenshotQuality >= 1 && screenshotQuality <= 100) { this.screenshotQuality = screenshotQuality; } else {
LogUtil.w(TAG, "Screenshot quality value must be set 1 ~ 100.");
logful/logful-android
logful/src/main/java/com/getui/logful/appender/AbstractManager.java
// Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import com.getui.logful.util.LogUtil; import java.util.concurrent.ConcurrentHashMap;
package com.getui.logful.appender; public abstract class AbstractManager { private static final String TAG = "AbstractManager"; private final String filePath; private static final ConcurrentHashMap<String, AbstractManager> MAP = new ConcurrentHashMap<String, AbstractManager>(); protected AbstractManager(final String filePath) { this.filePath = filePath; } public static <M extends AbstractManager, T> M getManager(final String filePath, final ManagerFactory<M, T> factory, final T data) { M manager = (M) MAP.get(filePath); if (manager == null) { manager = factory.createManager(filePath, data); if (manager == null) {
// Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/appender/AbstractManager.java import com.getui.logful.util.LogUtil; import java.util.concurrent.ConcurrentHashMap; package com.getui.logful.appender; public abstract class AbstractManager { private static final String TAG = "AbstractManager"; private final String filePath; private static final ConcurrentHashMap<String, AbstractManager> MAP = new ConcurrentHashMap<String, AbstractManager>(); protected AbstractManager(final String filePath) { this.filePath = filePath; } public static <M extends AbstractManager, T> M getManager(final String filePath, final ManagerFactory<M, T> factory, final T data) { M manager = (M) MAP.get(filePath); if (manager == null) { manager = factory.createManager(filePath, data); if (manager == null) {
LogUtil.e(TAG, "Unable to create a manager.");
logful/logful-android
logful/src/main/java/com/getui/logful/schedule/ScheduleReceiver.java
// Path: logful/src/main/java/com/getui/logful/net/TransferManager.java // public class TransferManager { // // private static final String TAG = "TransferManager"; // // private static ThreadPoolExecutor executor; // private final ConcurrentLinkedQueue<UploadEvent> queue; // // private static class ClassHolder { // static TransferManager manager = new TransferManager(); // } // // public static TransferManager manager() { // return ClassHolder.manager; // } // // public TransferManager() { // this.queue = new ConcurrentLinkedQueue<UploadEvent>(); // } // // private ThreadPoolExecutor getExecutor() { // if (executor == null || executor.isTerminated()) { // LoggerConfigurator config = LoggerFactory.config(); // int threadSize; // if (config != null) { // threadSize = config.getActiveUploadTask(); // } else { // threadSize = LoggerConstants.DEFAULT_ACTIVE_UPLOAD_TASK; // } // executor = // new ThreadPoolExecutor(threadSize, threadSize, 5, TimeUnit.SECONDS, // new ArrayBlockingQueue<Runnable>(1000)); // } // return executor; // } // // /** // * 上传指定 level 的日志文件. // */ // public static void uploadLogFile() { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // LoggerConfigurator config = LoggerFactory.config(); // if (config == null) { // return; // } // int[] levels = config.getUploadLogLevel(); // List<LogFileMeta> metaList = // DatabaseManager.findAllLogFileMetaByLevel(levels, LoggerConstants.STATE_WILL_UPLOAD); // // LogUtil.d(TAG, metaList.size() + " log files wait for upload."); // // manager.uploadLogFileFromMetaList(metaList); // } // // /** // * 上传指定 level 和时间的日志文件. // * // * @param startTime 开始时间 // * @param endTime 结束时间 // */ // public static void uploadLogFile(long startTime, long endTime) { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // LoggerConfigurator config = LoggerFactory.config(); // if (config == null) { // return; // } // int[] levels = config.getUploadLogLevel(); // List<LogFileMeta> metaList = // DatabaseManager.findAllLogFileMetaByLevelAndTime(levels, startTime, endTime, // LoggerConstants.STATE_WILL_UPLOAD); // // manager.uploadLogFileFromMetaList(metaList); // } // // /** // * 上传崩溃日志文件. // */ // public static void uploadCrashReport() { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // List<CrashReportFileMeta> metaList = DatabaseManager.findAllCrashFileMeta(LoggerConstants.STATE_NORMAL); // LogUtil.d(TAG, metaList.size() + " crash files wait for upload."); // for (CrashReportFileMeta meta : metaList) { // UploadCrashReportFileEvent event = new UploadCrashReportFileEvent(meta); // manager.addEvent(event); // } // } // // /** // * 上传附件文件. // */ // public static void uploadAttachment() { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // List<AttachmentFileMeta> metaList = DatabaseManager.findAllAttachmentFileMeta(LoggerConstants.STATE_NORMAL); // LogUtil.d(TAG, metaList.size() + " attachment files wait for upload."); // for (AttachmentFileMeta meta : metaList) { // UploadAttachmentFileEvent event = new UploadAttachmentFileEvent(meta); // manager.addEvent(event); // } // } // // private static boolean shouldUpload() { // if (!ClientUserInitService.granted()) { // LogUtil.w(TAG, "Client user not allow to upload file!"); // return false; // } // if (!ConnectivityState.shouldUpload()) { // LogUtil.w(TAG, "Not allow to upload file use current network type!"); // return false; // } // return true; // } // // private void uploadLogFileFromMetaList(List<LogFileMeta> metaList) { // String layoutJson = DatabaseManager.getLayoutJson(); // for (LogFileMeta meta : metaList) { // if (meta.isEof()) { // UploadLogFileEvent event = new UploadLogFileEvent(meta); // event.setLayouts(layoutJson); // addEvent(event); // } // } // } // // private void addEvent(UploadEvent event) { // boolean exist = false; // for (UploadEvent item : queue) { // if (item.identifier().equalsIgnoreCase(event.identifier())) { // exist = true; // } // } // // if (!exist) { // queue.add(event); // } // // if (queue.size() > 0) { // while (true) { // UploadEvent task = queue.poll(); // if (task != null) { // try { // getExecutor().submit(task); // } catch (RejectedExecutionException e) { // LogUtil.e(TAG, "", e); // } // } else { // break; // } // } // } // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.getui.logful.net.TransferManager;
package com.getui.logful.schedule; public class ScheduleReceiver extends BroadcastReceiver { private static final String TAG = "ScheduleReceiver"; @Override public void onReceive(Context context, Intent intent) { // TODO
// Path: logful/src/main/java/com/getui/logful/net/TransferManager.java // public class TransferManager { // // private static final String TAG = "TransferManager"; // // private static ThreadPoolExecutor executor; // private final ConcurrentLinkedQueue<UploadEvent> queue; // // private static class ClassHolder { // static TransferManager manager = new TransferManager(); // } // // public static TransferManager manager() { // return ClassHolder.manager; // } // // public TransferManager() { // this.queue = new ConcurrentLinkedQueue<UploadEvent>(); // } // // private ThreadPoolExecutor getExecutor() { // if (executor == null || executor.isTerminated()) { // LoggerConfigurator config = LoggerFactory.config(); // int threadSize; // if (config != null) { // threadSize = config.getActiveUploadTask(); // } else { // threadSize = LoggerConstants.DEFAULT_ACTIVE_UPLOAD_TASK; // } // executor = // new ThreadPoolExecutor(threadSize, threadSize, 5, TimeUnit.SECONDS, // new ArrayBlockingQueue<Runnable>(1000)); // } // return executor; // } // // /** // * 上传指定 level 的日志文件. // */ // public static void uploadLogFile() { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // LoggerConfigurator config = LoggerFactory.config(); // if (config == null) { // return; // } // int[] levels = config.getUploadLogLevel(); // List<LogFileMeta> metaList = // DatabaseManager.findAllLogFileMetaByLevel(levels, LoggerConstants.STATE_WILL_UPLOAD); // // LogUtil.d(TAG, metaList.size() + " log files wait for upload."); // // manager.uploadLogFileFromMetaList(metaList); // } // // /** // * 上传指定 level 和时间的日志文件. // * // * @param startTime 开始时间 // * @param endTime 结束时间 // */ // public static void uploadLogFile(long startTime, long endTime) { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // LoggerConfigurator config = LoggerFactory.config(); // if (config == null) { // return; // } // int[] levels = config.getUploadLogLevel(); // List<LogFileMeta> metaList = // DatabaseManager.findAllLogFileMetaByLevelAndTime(levels, startTime, endTime, // LoggerConstants.STATE_WILL_UPLOAD); // // manager.uploadLogFileFromMetaList(metaList); // } // // /** // * 上传崩溃日志文件. // */ // public static void uploadCrashReport() { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // List<CrashReportFileMeta> metaList = DatabaseManager.findAllCrashFileMeta(LoggerConstants.STATE_NORMAL); // LogUtil.d(TAG, metaList.size() + " crash files wait for upload."); // for (CrashReportFileMeta meta : metaList) { // UploadCrashReportFileEvent event = new UploadCrashReportFileEvent(meta); // manager.addEvent(event); // } // } // // /** // * 上传附件文件. // */ // public static void uploadAttachment() { // if (!shouldUpload()) { // return; // } // // TransferManager manager = manager(); // List<AttachmentFileMeta> metaList = DatabaseManager.findAllAttachmentFileMeta(LoggerConstants.STATE_NORMAL); // LogUtil.d(TAG, metaList.size() + " attachment files wait for upload."); // for (AttachmentFileMeta meta : metaList) { // UploadAttachmentFileEvent event = new UploadAttachmentFileEvent(meta); // manager.addEvent(event); // } // } // // private static boolean shouldUpload() { // if (!ClientUserInitService.granted()) { // LogUtil.w(TAG, "Client user not allow to upload file!"); // return false; // } // if (!ConnectivityState.shouldUpload()) { // LogUtil.w(TAG, "Not allow to upload file use current network type!"); // return false; // } // return true; // } // // private void uploadLogFileFromMetaList(List<LogFileMeta> metaList) { // String layoutJson = DatabaseManager.getLayoutJson(); // for (LogFileMeta meta : metaList) { // if (meta.isEof()) { // UploadLogFileEvent event = new UploadLogFileEvent(meta); // event.setLayouts(layoutJson); // addEvent(event); // } // } // } // // private void addEvent(UploadEvent event) { // boolean exist = false; // for (UploadEvent item : queue) { // if (item.identifier().equalsIgnoreCase(event.identifier())) { // exist = true; // } // } // // if (!exist) { // queue.add(event); // } // // if (queue.size() > 0) { // while (true) { // UploadEvent task = queue.poll(); // if (task != null) { // try { // getExecutor().submit(task); // } catch (RejectedExecutionException e) { // LogUtil.e(TAG, "", e); // } // } else { // break; // } // } // } // } // // } // Path: logful/src/main/java/com/getui/logful/schedule/ScheduleReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.getui.logful.net.TransferManager; package com.getui.logful.schedule; public class ScheduleReceiver extends BroadcastReceiver { private static final String TAG = "ScheduleReceiver"; @Override public void onReceive(Context context, Intent intent) { // TODO
TransferManager.uploadLogFile();
logful/logful-android
logful/src/main/java/com/getui/logful/net/UploadEvent.java
// Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // }
import com.getui.logful.util.LogUtil;
package com.getui.logful.net; public abstract class UploadEvent implements Runnable { private static final String TAG = "UploadEvent"; @Override public void run() { if (ClientUserInitService.granted()) { startRequest(ClientUserInitService.authorization()); } else {
// Path: logful/src/main/java/com/getui/logful/util/LogUtil.java // public class LogUtil { // // public static void d(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg); // } // } // // public static void d(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.d(tag, msg, tr); // } // } // // public static void e(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg); // } // } // // public static void e(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.e(tag, msg, tr); // } // } // // public static void i(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg); // } // } // // public static void i(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.i(tag, msg, tr); // } // } // // public static void v(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg, tr); // } // } // // public static void v(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.v(tag, msg); // } // } // // public static void w(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, tr); // } // } // // public static void w(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg, tr); // } // } // // public static void w(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.w(tag, msg); // } // } // // public static void wtf(String tag, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, tr); // } // } // // public static void wtf(String tag, String msg, Throwable tr) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg, tr); // } // } // // public static void wtf(String tag, String msg) { // if (LoggerFactory.isDebug()) { // Log.wtf(tag, msg); // } // } // } // Path: logful/src/main/java/com/getui/logful/net/UploadEvent.java import com.getui.logful.util.LogUtil; package com.getui.logful.net; public abstract class UploadEvent implements Runnable { private static final String TAG = "UploadEvent"; @Override public void run() { if (ClientUserInitService.granted()) { startRequest(ClientUserInitService.authorization()); } else {
LogUtil.w(TAG, "Client user not allow to upload file!");
logful/logful-android
logful/src/main/java/com/getui/logful/annotation/LogProperties.java
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // }
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import com.getui.logful.LoggerConstants;
package com.getui.logful.annotation; @Retention(RetentionPolicy.RUNTIME) public @interface LogProperties { /** * 默认的 logger 名称. * * @return Logger 名称 */
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // } // Path: logful/src/main/java/com/getui/logful/annotation/LogProperties.java import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import com.getui.logful.LoggerConstants; package com.getui.logful.annotation; @Retention(RetentionPolicy.RUNTIME) public @interface LogProperties { /** * 默认的 logger 名称. * * @return Logger 名称 */
String defaultLogger() default LoggerConstants.DEFAULT_LOGGER_NAME;
logful/logful-android
logful/src/main/java/com/getui/logful/appender/FileAppender.java
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // }
import com.getui.logful.layout.Layout;
package com.getui.logful.appender; public final class FileAppender extends AbstractOutputStreamAppender<FileManager> { private final long capacity; private final int fileFragment; /** * FileAppender. * * @param loggerName Logger name {@link com.getui.log.Logger} * @param layout Layout to format {@link LogEvent} * @param manager FileManager {@link FileManager} * @param ignoreExceptions Ignore exceptions * @param immediateFlush Immediate flush * @param capacity Capacity * @param fragment Fragment */
// Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // Path: logful/src/main/java/com/getui/logful/appender/FileAppender.java import com.getui.logful.layout.Layout; package com.getui.logful.appender; public final class FileAppender extends AbstractOutputStreamAppender<FileManager> { private final long capacity; private final int fileFragment; /** * FileAppender. * * @param loggerName Logger name {@link com.getui.log.Logger} * @param layout Layout to format {@link LogEvent} * @param manager FileManager {@link FileManager} * @param ignoreExceptions Ignore exceptions * @param immediateFlush Immediate flush * @param capacity Capacity * @param fragment Fragment */
private FileAppender(final String loggerName, final Layout layout, final FileManager manager,
logful/logful-android
logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java
// Path: logful/src/main/java/com/getui/logful/util/SystemConfig.java // public class SystemConfig { // // private String baseUrl; // // private String aliasName; // // private String appKeyString; // // private String appSecretString; // // private static class ClassHolder { // static SystemConfig config = new SystemConfig(); // } // // public static SystemConfig config() { // return ClassHolder.config; // } // // public static String baseUrl() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.baseUrl)) { // return LoggerConstants.API_BASE_URL; // } // return config.baseUrl; // } // // public static String alias() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.aliasName)) { // return ""; // } // return config.aliasName; // } // // // public static String apiUrl(String uri) { // return SystemConfig.baseUrl() + uri; // } // // public static String appKey() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appKeyString)) { // return ""; // } // return config.appKeyString; // } // // public static String appSecret() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appSecretString)) { // return ""; // } // return config.appSecretString; // } // // public static synchronized void saveAlias(String alias) { // SystemConfig config = SystemConfig.config(); // config.aliasName = alias; // } // // public static synchronized void saveBaseUrl(String baseUrl) { // SystemConfig config = SystemConfig.config(); // config.baseUrl = baseUrl; // } // // public static synchronized void saveAppKey(String appKey) { // SystemConfig config = SystemConfig.config(); // config.appKeyString = appKey; // } // // public static synchronized void saveAppSecret(String appSecret) { // SystemConfig config = SystemConfig.config(); // config.appSecretString = appSecret; // } // // } // // Path: logful/src/main/java/com/getui/logful/util/UIDUtils.java // public class UIDUtils { // private static final String TAG = "UIDUtils"; // // private static String uid; // private static final String UID_DIR = ".LogfulConfig"; // // public static String uid() { // Context context = LoggerFactory.context(); // if (context == null) { // return ""; // } // // if (!StringUtils.isEmpty(UIDUtils.uid)) { // return UIDUtils.uid; // } // // // Read exist uid. // String temp = UIDUtils.readUid(context); // if (!StringUtils.isEmpty(temp)) { // UIDUtils.set(temp); // return UIDUtils.uid; // } // // return UIDUtils.randomUid(); // } // // private static String generate(String original) { // String temp = UUID.nameUUIDFromBytes(original.getBytes()).toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static String randomUid() { // String temp = UUID.randomUUID().toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static void set(String string) { // UIDUtils.uid = string.replace("-", "").toLowerCase(); // } // // private static void saveUid(String uid) { // if (LogStorage.writable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (!dir.exists()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else if (dir.isDirectory()) { // File[] files = dir.listFiles(); // boolean successful = true; // for (File file : files) { // if (!file.delete()) { // successful = false; // } // } // if (successful) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else { // if (dir.delete()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } // } // } // } // // private static void createUidFile(String dirPath, String uid) { // File file = new File(dirPath + '/' + uid); // try { // boolean successful = file.createNewFile(); // } catch (IOException e) { // LogUtil.e(TAG, "Create uid file failed."); // } // } // // @TargetApi(value = 14) // private static String readUid(final Context context) { // if (context == null) { // return ""; // } // if (LogStorage.readable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (dir.exists() && dir.isDirectory()) { // File[] files = dir.listFiles(); // if (files.length == 1) { // String temp = files[0].getName(); // try { // if (UUID.fromString(temp).toString().equals(temp)) { // return temp; // } // } catch (Exception e) { // return ""; // } // } // } // } // return ""; // } // // }
import com.getui.logful.util.SystemConfig; import com.getui.logful.util.UIDUtils;
package com.getui.logful.security; public class DefaultSecurityProvider implements SecurityProvider { private byte[] passwordData; private byte[] saltData; @Override public byte[] password() { if (passwordData == null) {
// Path: logful/src/main/java/com/getui/logful/util/SystemConfig.java // public class SystemConfig { // // private String baseUrl; // // private String aliasName; // // private String appKeyString; // // private String appSecretString; // // private static class ClassHolder { // static SystemConfig config = new SystemConfig(); // } // // public static SystemConfig config() { // return ClassHolder.config; // } // // public static String baseUrl() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.baseUrl)) { // return LoggerConstants.API_BASE_URL; // } // return config.baseUrl; // } // // public static String alias() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.aliasName)) { // return ""; // } // return config.aliasName; // } // // // public static String apiUrl(String uri) { // return SystemConfig.baseUrl() + uri; // } // // public static String appKey() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appKeyString)) { // return ""; // } // return config.appKeyString; // } // // public static String appSecret() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appSecretString)) { // return ""; // } // return config.appSecretString; // } // // public static synchronized void saveAlias(String alias) { // SystemConfig config = SystemConfig.config(); // config.aliasName = alias; // } // // public static synchronized void saveBaseUrl(String baseUrl) { // SystemConfig config = SystemConfig.config(); // config.baseUrl = baseUrl; // } // // public static synchronized void saveAppKey(String appKey) { // SystemConfig config = SystemConfig.config(); // config.appKeyString = appKey; // } // // public static synchronized void saveAppSecret(String appSecret) { // SystemConfig config = SystemConfig.config(); // config.appSecretString = appSecret; // } // // } // // Path: logful/src/main/java/com/getui/logful/util/UIDUtils.java // public class UIDUtils { // private static final String TAG = "UIDUtils"; // // private static String uid; // private static final String UID_DIR = ".LogfulConfig"; // // public static String uid() { // Context context = LoggerFactory.context(); // if (context == null) { // return ""; // } // // if (!StringUtils.isEmpty(UIDUtils.uid)) { // return UIDUtils.uid; // } // // // Read exist uid. // String temp = UIDUtils.readUid(context); // if (!StringUtils.isEmpty(temp)) { // UIDUtils.set(temp); // return UIDUtils.uid; // } // // return UIDUtils.randomUid(); // } // // private static String generate(String original) { // String temp = UUID.nameUUIDFromBytes(original.getBytes()).toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static String randomUid() { // String temp = UUID.randomUUID().toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static void set(String string) { // UIDUtils.uid = string.replace("-", "").toLowerCase(); // } // // private static void saveUid(String uid) { // if (LogStorage.writable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (!dir.exists()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else if (dir.isDirectory()) { // File[] files = dir.listFiles(); // boolean successful = true; // for (File file : files) { // if (!file.delete()) { // successful = false; // } // } // if (successful) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else { // if (dir.delete()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } // } // } // } // // private static void createUidFile(String dirPath, String uid) { // File file = new File(dirPath + '/' + uid); // try { // boolean successful = file.createNewFile(); // } catch (IOException e) { // LogUtil.e(TAG, "Create uid file failed."); // } // } // // @TargetApi(value = 14) // private static String readUid(final Context context) { // if (context == null) { // return ""; // } // if (LogStorage.readable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (dir.exists() && dir.isDirectory()) { // File[] files = dir.listFiles(); // if (files.length == 1) { // String temp = files[0].getName(); // try { // if (UUID.fromString(temp).toString().equals(temp)) { // return temp; // } // } catch (Exception e) { // return ""; // } // } // } // } // return ""; // } // // } // Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java import com.getui.logful.util.SystemConfig; import com.getui.logful.util.UIDUtils; package com.getui.logful.security; public class DefaultSecurityProvider implements SecurityProvider { private byte[] passwordData; private byte[] saltData; @Override public byte[] password() { if (passwordData == null) {
this.passwordData = SystemConfig.appKey().getBytes();
logful/logful-android
logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java
// Path: logful/src/main/java/com/getui/logful/util/SystemConfig.java // public class SystemConfig { // // private String baseUrl; // // private String aliasName; // // private String appKeyString; // // private String appSecretString; // // private static class ClassHolder { // static SystemConfig config = new SystemConfig(); // } // // public static SystemConfig config() { // return ClassHolder.config; // } // // public static String baseUrl() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.baseUrl)) { // return LoggerConstants.API_BASE_URL; // } // return config.baseUrl; // } // // public static String alias() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.aliasName)) { // return ""; // } // return config.aliasName; // } // // // public static String apiUrl(String uri) { // return SystemConfig.baseUrl() + uri; // } // // public static String appKey() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appKeyString)) { // return ""; // } // return config.appKeyString; // } // // public static String appSecret() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appSecretString)) { // return ""; // } // return config.appSecretString; // } // // public static synchronized void saveAlias(String alias) { // SystemConfig config = SystemConfig.config(); // config.aliasName = alias; // } // // public static synchronized void saveBaseUrl(String baseUrl) { // SystemConfig config = SystemConfig.config(); // config.baseUrl = baseUrl; // } // // public static synchronized void saveAppKey(String appKey) { // SystemConfig config = SystemConfig.config(); // config.appKeyString = appKey; // } // // public static synchronized void saveAppSecret(String appSecret) { // SystemConfig config = SystemConfig.config(); // config.appSecretString = appSecret; // } // // } // // Path: logful/src/main/java/com/getui/logful/util/UIDUtils.java // public class UIDUtils { // private static final String TAG = "UIDUtils"; // // private static String uid; // private static final String UID_DIR = ".LogfulConfig"; // // public static String uid() { // Context context = LoggerFactory.context(); // if (context == null) { // return ""; // } // // if (!StringUtils.isEmpty(UIDUtils.uid)) { // return UIDUtils.uid; // } // // // Read exist uid. // String temp = UIDUtils.readUid(context); // if (!StringUtils.isEmpty(temp)) { // UIDUtils.set(temp); // return UIDUtils.uid; // } // // return UIDUtils.randomUid(); // } // // private static String generate(String original) { // String temp = UUID.nameUUIDFromBytes(original.getBytes()).toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static String randomUid() { // String temp = UUID.randomUUID().toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static void set(String string) { // UIDUtils.uid = string.replace("-", "").toLowerCase(); // } // // private static void saveUid(String uid) { // if (LogStorage.writable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (!dir.exists()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else if (dir.isDirectory()) { // File[] files = dir.listFiles(); // boolean successful = true; // for (File file : files) { // if (!file.delete()) { // successful = false; // } // } // if (successful) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else { // if (dir.delete()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } // } // } // } // // private static void createUidFile(String dirPath, String uid) { // File file = new File(dirPath + '/' + uid); // try { // boolean successful = file.createNewFile(); // } catch (IOException e) { // LogUtil.e(TAG, "Create uid file failed."); // } // } // // @TargetApi(value = 14) // private static String readUid(final Context context) { // if (context == null) { // return ""; // } // if (LogStorage.readable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (dir.exists() && dir.isDirectory()) { // File[] files = dir.listFiles(); // if (files.length == 1) { // String temp = files[0].getName(); // try { // if (UUID.fromString(temp).toString().equals(temp)) { // return temp; // } // } catch (Exception e) { // return ""; // } // } // } // } // return ""; // } // // }
import com.getui.logful.util.SystemConfig; import com.getui.logful.util.UIDUtils;
package com.getui.logful.security; public class DefaultSecurityProvider implements SecurityProvider { private byte[] passwordData; private byte[] saltData; @Override public byte[] password() { if (passwordData == null) { this.passwordData = SystemConfig.appKey().getBytes(); } return passwordData; } @Override public byte[] salt() { if (saltData == null) {
// Path: logful/src/main/java/com/getui/logful/util/SystemConfig.java // public class SystemConfig { // // private String baseUrl; // // private String aliasName; // // private String appKeyString; // // private String appSecretString; // // private static class ClassHolder { // static SystemConfig config = new SystemConfig(); // } // // public static SystemConfig config() { // return ClassHolder.config; // } // // public static String baseUrl() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.baseUrl)) { // return LoggerConstants.API_BASE_URL; // } // return config.baseUrl; // } // // public static String alias() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.aliasName)) { // return ""; // } // return config.aliasName; // } // // // public static String apiUrl(String uri) { // return SystemConfig.baseUrl() + uri; // } // // public static String appKey() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appKeyString)) { // return ""; // } // return config.appKeyString; // } // // public static String appSecret() { // SystemConfig config = SystemConfig.config(); // if (StringUtils.isEmpty(config.appSecretString)) { // return ""; // } // return config.appSecretString; // } // // public static synchronized void saveAlias(String alias) { // SystemConfig config = SystemConfig.config(); // config.aliasName = alias; // } // // public static synchronized void saveBaseUrl(String baseUrl) { // SystemConfig config = SystemConfig.config(); // config.baseUrl = baseUrl; // } // // public static synchronized void saveAppKey(String appKey) { // SystemConfig config = SystemConfig.config(); // config.appKeyString = appKey; // } // // public static synchronized void saveAppSecret(String appSecret) { // SystemConfig config = SystemConfig.config(); // config.appSecretString = appSecret; // } // // } // // Path: logful/src/main/java/com/getui/logful/util/UIDUtils.java // public class UIDUtils { // private static final String TAG = "UIDUtils"; // // private static String uid; // private static final String UID_DIR = ".LogfulConfig"; // // public static String uid() { // Context context = LoggerFactory.context(); // if (context == null) { // return ""; // } // // if (!StringUtils.isEmpty(UIDUtils.uid)) { // return UIDUtils.uid; // } // // // Read exist uid. // String temp = UIDUtils.readUid(context); // if (!StringUtils.isEmpty(temp)) { // UIDUtils.set(temp); // return UIDUtils.uid; // } // // return UIDUtils.randomUid(); // } // // private static String generate(String original) { // String temp = UUID.nameUUIDFromBytes(original.getBytes()).toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static String randomUid() { // String temp = UUID.randomUUID().toString(); // UIDUtils.saveUid(temp); // UIDUtils.set(temp); // return UIDUtils.uid; // } // // private static void set(String string) { // UIDUtils.uid = string.replace("-", "").toLowerCase(); // } // // private static void saveUid(String uid) { // if (LogStorage.writable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (!dir.exists()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else if (dir.isDirectory()) { // File[] files = dir.listFiles(); // boolean successful = true; // for (File file : files) { // if (!file.delete()) { // successful = false; // } // } // if (successful) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } else { // if (dir.delete()) { // if (dir.mkdirs()) { // UIDUtils.createUidFile(dir.getAbsolutePath(), uid); // } // } // } // } // } // // private static void createUidFile(String dirPath, String uid) { // File file = new File(dirPath + '/' + uid); // try { // boolean successful = file.createNewFile(); // } catch (IOException e) { // LogUtil.e(TAG, "Create uid file failed."); // } // } // // @TargetApi(value = 14) // private static String readUid(final Context context) { // if (context == null) { // return ""; // } // if (LogStorage.readable()) { // File dir = new File(Environment.getExternalStorageDirectory(), UID_DIR); // if (dir.exists() && dir.isDirectory()) { // File[] files = dir.listFiles(); // if (files.length == 1) { // String temp = files[0].getName(); // try { // if (UUID.fromString(temp).toString().equals(temp)) { // return temp; // } // } catch (Exception e) { // return ""; // } // } // } // } // return ""; // } // // } // Path: logful/src/main/java/com/getui/logful/security/DefaultSecurityProvider.java import com.getui.logful.util.SystemConfig; import com.getui.logful.util.UIDUtils; package com.getui.logful.security; public class DefaultSecurityProvider implements SecurityProvider { private byte[] passwordData; private byte[] saltData; @Override public byte[] password() { if (passwordData == null) { this.passwordData = SystemConfig.appKey().getBytes(); } return passwordData; } @Override public byte[] salt() { if (saltData == null) {
this.saltData = UIDUtils.uid().getBytes();
logful/logful-android
logful/src/main/java/com/getui/logful/entity/CrashReportFileMeta.java
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // }
import com.getui.logful.LoggerConstants;
package com.getui.logful.entity; public class CrashReportFileMeta { private long id; private String filename; private int location; private long createTime; private long deleteTime; private int status; private String fileMD5; public CrashReportFileMeta() { this.id = -1;
// Path: logful/src/main/java/com/getui/logful/LoggerConstants.java // public class LoggerConstants { // // public static final String DATABASE_NAME = "logful.db"; // // /** // * 日志文件存储文件夹名称. // */ // public static final String LOG_DIR_NAME = "log"; // // /** // * 崩溃日志文件存储文件夹. // */ // public static final String CRASH_REPORT_DIR_NAME = "crash"; // // /** // * 附件截图文件夹名称. // */ // public static final String ATTACHMENT_DIR_NAME = "attachment"; // // /** // * 本地配置文件名称. // */ // public static final String CONFIG_FILE_NAME = "logful.config"; // // public static final String VERBOSE_NAME = "verbose"; // // public static final String DEBUG_NAME = "debug"; // // public static final String INFO_NAME = "info"; // // public static final String WARN_NAME = "warn"; // // public static final String ERROR_NAME = "error"; // // public static final String EXCEPTION_NAME = "exception"; // // public static final String FATAL_NAME = "fatal"; // // public static String getLogLevelName(int level) { // switch (level) { // case Constants.VERBOSE: // return VERBOSE_NAME; // case Constants.DEBUG: // return DEBUG_NAME; // case Constants.INFO: // return INFO_NAME; // case Constants.WARN: // return WARN_NAME; // case Constants.ERROR: // return ERROR_NAME; // case Constants.EXCEPTION: // return EXCEPTION_NAME; // case Constants.FATAL: // return FATAL_NAME; // default: // return VERBOSE_NAME; // } // } // // public static final int DEFAULT_ACTIVE_UPLOAD_TASK = 2; // // public static final int DEFAULT_ACTIVE_LOG_WRITER = 2; // // public static final boolean DEFAULT_DELETE_UPLOADED_LOG_FILE = false; // // public static final boolean DEFAULT_CAUGHT_EXCEPTION = false; // // public static final int[] DEFAULT_UPLOAD_NETWORK_TYPE = {Constants.TYPE_WIFI, Constants.TYPE_MOBILE}; // // public static final int[] DEFAULT_UPLOAD_LOG_LEVEL = {Constants.VERBOSE, Constants.DEBUG, Constants.INFO, // Constants.WARN, Constants.ERROR, Constants.EXCEPTION, Constants.FATAL}; // // public static final long DEFAULT_LOG_FILE_MAX_SIZE = 524288; // // public static final long DEFAULT_UPDATE_SYSTEM_FREQUENCY = 3600; // // public static final String DEFAULT_LOGGER_NAME = "app"; // // public static final String DEFAULT_MSG_LAYOUT = ""; // // public static final String API_BASE_URL = "http://demo.logful.aoapp.com:9600"; // // public static final String CLIENT_AUTH_URI = "/oauth/token"; // // public static final String UPLOAD_USER_INFO_URI = "/log/info/upload"; // // public static final String BIND_DEVICE_ID_URI = "/log/bind"; // // public static final String UPLOAD_LOG_FILE_URI = "/log/file/upload"; // // public static final String UPLOAD_CRASH_REPORT_FILE_URI = "/log/crash/upload"; // // public static final String UPLOAD_ATTACHMENT_FILE_URI = "/log/attachment/upload"; // // public static final int DEFAULT_HTTP_REQUEST_TIMEOUT = 6000; // // public static final String CHARSET = "UTF-8"; // // public static final String VERSION = "0.3.0"; // // public static final int STATE_ALL = 0x00; // // public static final int STATE_NORMAL = 0x01; // // public static final int STATE_WILL_UPLOAD = 0x02; // // public static final int STATE_UPLOADED = 0x03; // // public static final int STATE_DELETED = 0x04; // // public static final int LOCATION_EXTERNAL = 0x01; // // public static final int LOCATION_INTERNAL = 0x02; // // public static final int DEFAULT_SCREENSHOT_QUALITY = 80; // // public static final float DEFAULT_SCREENSHOT_SCALE = 0.5f; // // public static final boolean DEFAULT_USE_NATIVE_CRYPTOR = true; // // public static final int PLATFORM_ANDROID = 1; // // public static final String QUERY_PARAM_SDK_VERSION = "sdk"; // // public static final String QUERY_PARAM_PLATFORM = "platform"; // // public static final String QUERY_PARAM_UID = "uid"; // } // Path: logful/src/main/java/com/getui/logful/entity/CrashReportFileMeta.java import com.getui.logful.LoggerConstants; package com.getui.logful.entity; public class CrashReportFileMeta { private long id; private String filename; private int location; private long createTime; private long deleteTime; private int status; private String fileMD5; public CrashReportFileMeta() { this.id = -1;
this.status = LoggerConstants.STATE_NORMAL;
logful/logful-android
logful/src/main/java/com/getui/logful/appender/Appender.java
// Path: logful/src/main/java/com/getui/logful/LifeCycle.java // public interface LifeCycle { // // public enum State { // /** // * Initialized but not yet started. // */ // INITIALIZED, // /** // * In the process of starting. // */ // STARTING, // /** // * Has started. // */ // STARTED, // /** // * Stopping is in progress. // */ // STOPPING, // /** // * Has stopped. // */ // STOPPED // } // // /** // * Gets the life-cycle state. // * // * @return the life-cycle state // */ // State getState(); // // void start(); // // void stop(); // // boolean isStarted(); // // boolean isStopped(); // } // // Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // }
import com.getui.logful.LifeCycle; import com.getui.logful.layout.Layout;
package com.getui.logful.appender; public interface Appender extends LifeCycle { void append(LogEvent event); ErrorHandler getHandler();
// Path: logful/src/main/java/com/getui/logful/LifeCycle.java // public interface LifeCycle { // // public enum State { // /** // * Initialized but not yet started. // */ // INITIALIZED, // /** // * In the process of starting. // */ // STARTING, // /** // * Has started. // */ // STARTED, // /** // * Stopping is in progress. // */ // STOPPING, // /** // * Has stopped. // */ // STOPPED // } // // /** // * Gets the life-cycle state. // * // * @return the life-cycle state // */ // State getState(); // // void start(); // // void stop(); // // boolean isStarted(); // // boolean isStopped(); // } // // Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // Path: logful/src/main/java/com/getui/logful/appender/Appender.java import com.getui.logful.LifeCycle; import com.getui.logful.layout.Layout; package com.getui.logful.appender; public interface Appender extends LifeCycle { void append(LogEvent event); ErrorHandler getHandler();
Layout getLayout();
logful/logful-android
logful/src/main/java/com/getui/logful/appender/AbstractAppender.java
// Path: logful/src/main/java/com/getui/logful/AbstractLifeCycle.java // public class AbstractLifeCycle implements LifeCycle, Serializable { // // private volatile LifeCycle.State state = LifeCycle.State.INITIALIZED; // // protected boolean equalsImpl(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final LifeCycle other = (LifeCycle) obj; // return state == other.getState(); // } // // protected int hashCodeImpl() { // final int prime = 31; // int result = 1; // result = prime * result + ((state == null) ? 0 : state.hashCode()); // return result; // } // // @Override // public State getState() { // return this.state; // } // // public boolean isInitialized() { // return this.state == LifeCycle.State.INITIALIZED; // } // // @Override // public boolean isStarted() { // return this.state == LifeCycle.State.STARTED; // } // // public boolean isStarting() { // return this.state == LifeCycle.State.STARTING; // } // // @Override // public boolean isStopped() { // return this.state == LifeCycle.State.STOPPED; // } // // public boolean isStopping() { // return this.state == LifeCycle.State.STOPPING; // } // // protected void setStarted() { // this.setState(LifeCycle.State.STARTED); // } // // protected void setStarting() { // this.setState(LifeCycle.State.STARTING); // } // // protected void setState(final LifeCycle.State newState) { // this.state = newState; // } // // protected void setStopped() { // this.setState(LifeCycle.State.STOPPED); // } // // protected void setStopping() { // this.setState(LifeCycle.State.STOPPING); // } // // @Override // public void start() { // this.setStarted(); // } // // @Override // public void stop() { // this.state = LifeCycle.State.STOPPED; // } // } // // Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // }
import com.getui.logful.AbstractLifeCycle; import com.getui.logful.layout.Layout;
package com.getui.logful.appender; public abstract class AbstractAppender extends AbstractLifeCycle implements Appender { private ErrorHandler handler = new DefaultErrorHandler(this); private final String loggerName;
// Path: logful/src/main/java/com/getui/logful/AbstractLifeCycle.java // public class AbstractLifeCycle implements LifeCycle, Serializable { // // private volatile LifeCycle.State state = LifeCycle.State.INITIALIZED; // // protected boolean equalsImpl(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final LifeCycle other = (LifeCycle) obj; // return state == other.getState(); // } // // protected int hashCodeImpl() { // final int prime = 31; // int result = 1; // result = prime * result + ((state == null) ? 0 : state.hashCode()); // return result; // } // // @Override // public State getState() { // return this.state; // } // // public boolean isInitialized() { // return this.state == LifeCycle.State.INITIALIZED; // } // // @Override // public boolean isStarted() { // return this.state == LifeCycle.State.STARTED; // } // // public boolean isStarting() { // return this.state == LifeCycle.State.STARTING; // } // // @Override // public boolean isStopped() { // return this.state == LifeCycle.State.STOPPED; // } // // public boolean isStopping() { // return this.state == LifeCycle.State.STOPPING; // } // // protected void setStarted() { // this.setState(LifeCycle.State.STARTED); // } // // protected void setStarting() { // this.setState(LifeCycle.State.STARTING); // } // // protected void setState(final LifeCycle.State newState) { // this.state = newState; // } // // protected void setStopped() { // this.setState(LifeCycle.State.STOPPED); // } // // protected void setStopping() { // this.setState(LifeCycle.State.STOPPING); // } // // @Override // public void start() { // this.setStarted(); // } // // @Override // public void stop() { // this.state = LifeCycle.State.STOPPED; // } // } // // Path: logful/src/main/java/com/getui/logful/layout/Layout.java // public interface Layout { // // byte[] toBytes(LogEvent event); // // } // Path: logful/src/main/java/com/getui/logful/appender/AbstractAppender.java import com.getui.logful.AbstractLifeCycle; import com.getui.logful.layout.Layout; package com.getui.logful.appender; public abstract class AbstractAppender extends AbstractLifeCycle implements Appender { private ErrorHandler handler = new DefaultErrorHandler(this); private final String loggerName;
private final Layout layout;
DavidGoldman/MinecraftScripting
scripting/gui/settings/SetCheckbox.java
// Path: scripting/wrapper/settings/SettingBoolean.java // public class SettingBoolean extends Setting { // // public boolean enabled; // // protected SettingBoolean() { } // // public SettingBoolean(String display, boolean enabled) { // super(display); // // this.enabled = enabled; // } // // public SettingBoolean(String display) { // this(display, false); // } // // @Override // public Object getValue() { // return enabled; // } // // @Override // protected void write(DataOutput out) throws IOException { // super.write(out); // out.writeBoolean(enabled); // } // // @Override // protected Setting read(DataInput in) throws IOException { // super.read(in); // enabled = in.readBoolean(); // return this; // } // // }
import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import scripting.wrapper.settings.SettingBoolean; import com.mcf.davidee.guilib.core.Checkbox; import com.mcf.davidee.guilib.core.Scrollbar.Shiftable;
package scripting.gui.settings; public class SetCheckbox extends Checkbox implements ISetting, Shiftable { private static final ResourceLocation TEXTURE = new ResourceLocation("guilib", "textures/gui/checkbox.png"); public static final int SIZE = 10;
// Path: scripting/wrapper/settings/SettingBoolean.java // public class SettingBoolean extends Setting { // // public boolean enabled; // // protected SettingBoolean() { } // // public SettingBoolean(String display, boolean enabled) { // super(display); // // this.enabled = enabled; // } // // public SettingBoolean(String display) { // this(display, false); // } // // @Override // public Object getValue() { // return enabled; // } // // @Override // protected void write(DataOutput out) throws IOException { // super.write(out); // out.writeBoolean(enabled); // } // // @Override // protected Setting read(DataInput in) throws IOException { // super.read(in); // enabled = in.readBoolean(); // return this; // } // // } // Path: scripting/gui/settings/SetCheckbox.java import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import scripting.wrapper.settings.SettingBoolean; import com.mcf.davidee.guilib.core.Checkbox; import com.mcf.davidee.guilib.core.Scrollbar.Shiftable; package scripting.gui.settings; public class SetCheckbox extends Checkbox implements ISetting, Shiftable { private static final ResourceLocation TEXTURE = new ResourceLocation("guilib", "textures/gui/checkbox.png"); public static final int SIZE = 10;
private final SettingBoolean setting;
DavidGoldman/MinecraftScripting
scripting/core/script/JSScript.java
// Path: scripting/core/ScriptException.java // public class ScriptException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public ScriptException(String message) { // super(message); // } // // public ScriptException(Throwable cause) { // super(cause); // } // }
import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import scripting.core.ScriptException;
package scripting.core.script; public abstract class JSScript { public final String name; public final String source; protected Script script; protected Scriptable scope; public JSScript(String name, String source) { this.name = name; this.source = source; } /** * Called after being executed for the first time to set up functions. * * @throws ScriptException If an error occurs (such as function not found). */
// Path: scripting/core/ScriptException.java // public class ScriptException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public ScriptException(String message) { // super(message); // } // // public ScriptException(Throwable cause) { // super(cause); // } // } // Path: scripting/core/script/JSScript.java import org.mozilla.javascript.Script; import org.mozilla.javascript.Scriptable; import scripting.core.ScriptException; package scripting.core.script; public abstract class JSScript { public final String name; public final String source; protected Script script; protected Scriptable scope; public JSScript(String name, String source) { this.name = name; this.source = source; } /** * Called after being executed for the first time to set up functions. * * @throws ScriptException If an error occurs (such as function not found). */
public abstract void postInit() throws ScriptException;
DavidGoldman/MinecraftScripting
scripting/packet/EntityNBTPacket.java
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import scripting.network.ScriptPacketHandler;
package scripting.packet; public class EntityNBTPacket extends ScriptPacket { public int entityID; public NBTTagCompound tag; @Override public ScriptPacket readData(Object... data) { entityID = (Integer) data[0]; tag = (NBTTagCompound) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { ByteBufOutputStream bos = new ByteBufOutputStream(to); bos.writeInt(entityID); writeNBT(tag, bos); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { ByteBufInputStream bis = new ByteBufInputStream(from); entityID = bis.readInt(); tag = readNBT(bis); } @Override
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // Path: scripting/packet/EntityNBTPacket.java import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import scripting.network.ScriptPacketHandler; package scripting.packet; public class EntityNBTPacket extends ScriptPacket { public int entityID; public NBTTagCompound tag; @Override public ScriptPacket readData(Object... data) { entityID = (Integer) data[0]; tag = (NBTTagCompound) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { ByteBufOutputStream bos = new ByteBufOutputStream(to); bos.writeInt(entityID); writeNBT(tag, bos); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { ByteBufInputStream bis = new ByteBufInputStream(from); entityID = bis.readInt(); tag = readNBT(bis); } @Override
public void execute(ScriptPacketHandler handler, EntityPlayer player) {
DavidGoldman/MinecraftScripting
scripting/forge/KeyListener.java
// Path: scripting/gui/MainScreen.java // public class MainScreen extends ScriptScreen { // // public static final int REFRESH_TICKS = 200; //Check every 10 seconds // // private Container container; // private Label title; // private Button close, client, server; // // public MainScreen() { // super(null); // } // // public void setServerScripts(boolean flag) { // server.setEnabled(flag); // } // // @Override // protected void revalidateGui() { // title.setPosition(width/2, height/4 - 20); // client.setPosition(width/2 - 50, height/4 + 18); // server.setPosition(width/2 - 50, height/4 + 43); // close.setPosition(width/2 - 75, height/4 + 90); // container.revalidate(0, 0, width, height); // } // // @Override // protected void createGui() { // container = new Container(); // title = new Label(ScriptingMod.NAME, new Tooltip("v" + ScriptingMod.VERSION)); // client = new ButtonVanilla(100, 20, "Client", this); // client.setEnabled(ScriptingMod.proxy.getClientCore().hasScripts()); // server = new ButtonVanilla(100, 20, "Server", this); // server.setEnabled(false); // close = new ButtonVanilla(150, 20, "Close", new CloseHandler()); // // container.addWidgets(title, close, client, server); // containers.add(container); // selectedContainer = container; // // ScriptingMod.DISPATCHER.sendToServer(ScriptPacket.getPacket(PacketType.HAS_SCRIPTS)); // } // // public void buttonClicked(Button button) { // if (button == client) // mc.displayGuiScreen(new ClientMenu(this)); // if (button == server) // ScriptingMod.DISPATCHER.sendToServer(ScriptPacket.getRequestPacket(PacketType.STATE)); // } // // @Override // public void reopenedGui() { // ScriptingMod.DISPATCHER.sendToServer(ScriptPacket.getPacket(PacketType.HAS_SCRIPTS)); // } // // }
import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; import scripting.gui.MainScreen; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent;
package scripting.forge; public class KeyListener { private final KeyBinding scriptGUI; public KeyListener() { scriptGUI = new KeyBinding("key.script.gui", Keyboard.KEY_F7, "key.categories.misc"); ClientRegistry.registerKeyBinding(scriptGUI); } @SubscribeEvent public void onKeyInput(KeyInputEvent event) { if (Minecraft.getMinecraft().currentScreen == null && scriptGUI.isPressed())
// Path: scripting/gui/MainScreen.java // public class MainScreen extends ScriptScreen { // // public static final int REFRESH_TICKS = 200; //Check every 10 seconds // // private Container container; // private Label title; // private Button close, client, server; // // public MainScreen() { // super(null); // } // // public void setServerScripts(boolean flag) { // server.setEnabled(flag); // } // // @Override // protected void revalidateGui() { // title.setPosition(width/2, height/4 - 20); // client.setPosition(width/2 - 50, height/4 + 18); // server.setPosition(width/2 - 50, height/4 + 43); // close.setPosition(width/2 - 75, height/4 + 90); // container.revalidate(0, 0, width, height); // } // // @Override // protected void createGui() { // container = new Container(); // title = new Label(ScriptingMod.NAME, new Tooltip("v" + ScriptingMod.VERSION)); // client = new ButtonVanilla(100, 20, "Client", this); // client.setEnabled(ScriptingMod.proxy.getClientCore().hasScripts()); // server = new ButtonVanilla(100, 20, "Server", this); // server.setEnabled(false); // close = new ButtonVanilla(150, 20, "Close", new CloseHandler()); // // container.addWidgets(title, close, client, server); // containers.add(container); // selectedContainer = container; // // ScriptingMod.DISPATCHER.sendToServer(ScriptPacket.getPacket(PacketType.HAS_SCRIPTS)); // } // // public void buttonClicked(Button button) { // if (button == client) // mc.displayGuiScreen(new ClientMenu(this)); // if (button == server) // ScriptingMod.DISPATCHER.sendToServer(ScriptPacket.getRequestPacket(PacketType.STATE)); // } // // @Override // public void reopenedGui() { // ScriptingMod.DISPATCHER.sendToServer(ScriptPacket.getPacket(PacketType.HAS_SCRIPTS)); // } // // } // Path: scripting/forge/KeyListener.java import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import org.lwjgl.input.Keyboard; import scripting.gui.MainScreen; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent; package scripting.forge; public class KeyListener { private final KeyBinding scriptGUI; public KeyListener() { scriptGUI = new KeyBinding("key.script.gui", Keyboard.KEY_F7, "key.categories.misc"); ClientRegistry.registerKeyBinding(scriptGUI); } @SubscribeEvent public void onKeyInput(KeyInputEvent event) { if (Minecraft.getMinecraft().currentScreen == null && scriptGUI.isPressed())
Minecraft.getMinecraft().displayGuiScreen(new MainScreen());
DavidGoldman/MinecraftScripting
scripting/packet/HasScriptsPacket.java
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler;
package scripting.packet; public class HasScriptsPacket extends ScriptPacket { public boolean hasScripts; @Override public ScriptPacket readData(Object... data) { if (data.length > 0) hasScripts = (Boolean) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeBoolean(hasScripts); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { hasScripts = from.readBoolean(); } @Override
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // Path: scripting/packet/HasScriptsPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; package scripting.packet; public class HasScriptsPacket extends ScriptPacket { public boolean hasScripts; @Override public ScriptPacket readData(Object... data) { if (data.length > 0) hasScripts = (Boolean) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeBoolean(hasScripts); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { hasScripts = from.readBoolean(); } @Override
public void execute(ScriptPacketHandler handler, EntityPlayer player) {
DavidGoldman/MinecraftScripting
scripting/packet/RequestPacket.java
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; import com.google.common.primitives.UnsignedBytes;
package scripting.packet; public class RequestPacket extends ScriptPacket { private byte request; private String info; @Override public ScriptPacket readData(Object... data) { request = (Byte) data[0]; if (data.length > 1) info = (String) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeByte(request); writeString(info != null ? info : "", to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { request = from.readByte(); info = readString(from); } @Override
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // Path: scripting/packet/RequestPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; import com.google.common.primitives.UnsignedBytes; package scripting.packet; public class RequestPacket extends ScriptPacket { private byte request; private String info; @Override public ScriptPacket readData(Object... data) { request = (Byte) data[0]; if (data.length > 1) info = (String) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeByte(request); writeString(info != null ? info : "", to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { request = from.readByte(); info = readString(from); } @Override
public void execute(ScriptPacketHandler handler, EntityPlayer player) {
DavidGoldman/MinecraftScripting
scripting/wrapper/entity/ScriptEntityLivingBase.java
// Path: scripting/wrapper/ScriptItemStack.java // public class ScriptItemStack { // // public final ItemStack stack; // // private ScriptItemStack(ItemStack is) { // this.stack = is; // } // // public ScriptItemStack(ScriptItem item, int size, int damage) { // this.stack = new ItemStack((item == null) ? null : item.item, size, damage); // } // // public ScriptItemStack(ScriptBlock block, int size, int damage) { // this.stack = new ItemStack((block == null) ? null : block.block, size, damage); // } // // public ScriptItem getItem() { // return (stack.getItem() == null) ? null : ScriptItem.fromItem(stack.getItem()); // } // // public int getStackSize() { // return stack.stackSize; // } // // public void setStackSize(int size) { // stack.stackSize = size; // } // // public int getItemDamage() { // return stack.getItemDamage(); // } // // public void setItemDamage(int damage) { // stack.setItemDamage(damage); // } // // public boolean hasTagCompound() { // return stack.hasTagCompound(); // } // // public TAG_Compound getTagCompound() { // return (hasTagCompound()) ? new TAG_Compound(stack.getTagCompound()) : null; // } // // public void setTagCompound(TAG_Compound tag) { // stack.setTagCompound((tag == null) ? null : tag.tag); // } // // public TAG_Compound writeToTag() { // return new TAG_Compound(stack.writeToNBT(new NBTTagCompound())); // } // // public void readFromTag(TAG_Compound tag) { // stack.readFromNBT(tag.tag); // } // // public static ScriptItemStack fromItemStack(ItemStack stack) { // return (stack == null) ? null : new ScriptItemStack(stack); // } // // } // // Path: scripting/wrapper/ScriptVec3.java // public class ScriptVec3 { // // public double x; // public double y; // public double z; // // public ScriptVec3(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public ScriptVec3() { // this(0, 0, 0); // } // // public void add(ScriptVec3 vec) { // this.x += vec.x; // this.y += vec.y; // this.z += vec.z; // } // // public void add(double x, double y, double z) { // this.x += x; // this.y += y; // this.z += z; // } // // public void multiply(ScriptVec3 vec) { // this.x *= vec.x; // this.y *= vec.y; // this.z *= vec.z; // } // // public void multiply(double x, double y, double z) { // this.x *= x; // this.y *= y; // this.z *= z; // } // // public void scale(double s) { // this.x *= s; // this.y *= s; // this.z *= s; // } // // public double length() { // return Math.sqrt(x*x + y*y + z*z); // } // // public void normalize() { // double l = length(); // if (l > 0) { // this.x /= l; // this.y /= l; // this.z /= l; // } // } // // public double distanceTo(ScriptVec3 vec) { // double dx = this.x - vec.x; // double dy = this.y - vec.y; // double dz = this.z - vec.z; // return Math.sqrt(dx*dx + dy*dy + dz*dz); // } // }
import java.util.Random; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import scripting.wrapper.ScriptItemStack; import scripting.wrapper.ScriptVec3;
package scripting.wrapper.entity; public class ScriptEntityLivingBase extends ScriptEntity { public final EntityLivingBase entityLivingBase; public ScriptEntityLivingBase(EntityLivingBase entityLivingBase) { super(entityLivingBase); this.entityLivingBase = entityLivingBase; } public void setHealth(float health) { entityLivingBase.setHealth(health); } public float getHealth() { return entityLivingBase.getHealth(); } public boolean isChild() { return entityLivingBase.isChild(); } public Random getRNG() { return entityLivingBase.getRNG(); } public void clearActivePotions() { entityLivingBase.clearActivePotions(); }
// Path: scripting/wrapper/ScriptItemStack.java // public class ScriptItemStack { // // public final ItemStack stack; // // private ScriptItemStack(ItemStack is) { // this.stack = is; // } // // public ScriptItemStack(ScriptItem item, int size, int damage) { // this.stack = new ItemStack((item == null) ? null : item.item, size, damage); // } // // public ScriptItemStack(ScriptBlock block, int size, int damage) { // this.stack = new ItemStack((block == null) ? null : block.block, size, damage); // } // // public ScriptItem getItem() { // return (stack.getItem() == null) ? null : ScriptItem.fromItem(stack.getItem()); // } // // public int getStackSize() { // return stack.stackSize; // } // // public void setStackSize(int size) { // stack.stackSize = size; // } // // public int getItemDamage() { // return stack.getItemDamage(); // } // // public void setItemDamage(int damage) { // stack.setItemDamage(damage); // } // // public boolean hasTagCompound() { // return stack.hasTagCompound(); // } // // public TAG_Compound getTagCompound() { // return (hasTagCompound()) ? new TAG_Compound(stack.getTagCompound()) : null; // } // // public void setTagCompound(TAG_Compound tag) { // stack.setTagCompound((tag == null) ? null : tag.tag); // } // // public TAG_Compound writeToTag() { // return new TAG_Compound(stack.writeToNBT(new NBTTagCompound())); // } // // public void readFromTag(TAG_Compound tag) { // stack.readFromNBT(tag.tag); // } // // public static ScriptItemStack fromItemStack(ItemStack stack) { // return (stack == null) ? null : new ScriptItemStack(stack); // } // // } // // Path: scripting/wrapper/ScriptVec3.java // public class ScriptVec3 { // // public double x; // public double y; // public double z; // // public ScriptVec3(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public ScriptVec3() { // this(0, 0, 0); // } // // public void add(ScriptVec3 vec) { // this.x += vec.x; // this.y += vec.y; // this.z += vec.z; // } // // public void add(double x, double y, double z) { // this.x += x; // this.y += y; // this.z += z; // } // // public void multiply(ScriptVec3 vec) { // this.x *= vec.x; // this.y *= vec.y; // this.z *= vec.z; // } // // public void multiply(double x, double y, double z) { // this.x *= x; // this.y *= y; // this.z *= z; // } // // public void scale(double s) { // this.x *= s; // this.y *= s; // this.z *= s; // } // // public double length() { // return Math.sqrt(x*x + y*y + z*z); // } // // public void normalize() { // double l = length(); // if (l > 0) { // this.x /= l; // this.y /= l; // this.z /= l; // } // } // // public double distanceTo(ScriptVec3 vec) { // double dx = this.x - vec.x; // double dy = this.y - vec.y; // double dz = this.z - vec.z; // return Math.sqrt(dx*dx + dy*dy + dz*dz); // } // } // Path: scripting/wrapper/entity/ScriptEntityLivingBase.java import java.util.Random; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import scripting.wrapper.ScriptItemStack; import scripting.wrapper.ScriptVec3; package scripting.wrapper.entity; public class ScriptEntityLivingBase extends ScriptEntity { public final EntityLivingBase entityLivingBase; public ScriptEntityLivingBase(EntityLivingBase entityLivingBase) { super(entityLivingBase); this.entityLivingBase = entityLivingBase; } public void setHealth(float health) { entityLivingBase.setHealth(health); } public float getHealth() { return entityLivingBase.getHealth(); } public boolean isChild() { return entityLivingBase.isChild(); } public Random getRNG() { return entityLivingBase.getRNG(); } public void clearActivePotions() { entityLivingBase.clearActivePotions(); }
public ScriptItemStack getHeldItem() {
DavidGoldman/MinecraftScripting
scripting/wrapper/entity/ScriptEntityLivingBase.java
// Path: scripting/wrapper/ScriptItemStack.java // public class ScriptItemStack { // // public final ItemStack stack; // // private ScriptItemStack(ItemStack is) { // this.stack = is; // } // // public ScriptItemStack(ScriptItem item, int size, int damage) { // this.stack = new ItemStack((item == null) ? null : item.item, size, damage); // } // // public ScriptItemStack(ScriptBlock block, int size, int damage) { // this.stack = new ItemStack((block == null) ? null : block.block, size, damage); // } // // public ScriptItem getItem() { // return (stack.getItem() == null) ? null : ScriptItem.fromItem(stack.getItem()); // } // // public int getStackSize() { // return stack.stackSize; // } // // public void setStackSize(int size) { // stack.stackSize = size; // } // // public int getItemDamage() { // return stack.getItemDamage(); // } // // public void setItemDamage(int damage) { // stack.setItemDamage(damage); // } // // public boolean hasTagCompound() { // return stack.hasTagCompound(); // } // // public TAG_Compound getTagCompound() { // return (hasTagCompound()) ? new TAG_Compound(stack.getTagCompound()) : null; // } // // public void setTagCompound(TAG_Compound tag) { // stack.setTagCompound((tag == null) ? null : tag.tag); // } // // public TAG_Compound writeToTag() { // return new TAG_Compound(stack.writeToNBT(new NBTTagCompound())); // } // // public void readFromTag(TAG_Compound tag) { // stack.readFromNBT(tag.tag); // } // // public static ScriptItemStack fromItemStack(ItemStack stack) { // return (stack == null) ? null : new ScriptItemStack(stack); // } // // } // // Path: scripting/wrapper/ScriptVec3.java // public class ScriptVec3 { // // public double x; // public double y; // public double z; // // public ScriptVec3(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public ScriptVec3() { // this(0, 0, 0); // } // // public void add(ScriptVec3 vec) { // this.x += vec.x; // this.y += vec.y; // this.z += vec.z; // } // // public void add(double x, double y, double z) { // this.x += x; // this.y += y; // this.z += z; // } // // public void multiply(ScriptVec3 vec) { // this.x *= vec.x; // this.y *= vec.y; // this.z *= vec.z; // } // // public void multiply(double x, double y, double z) { // this.x *= x; // this.y *= y; // this.z *= z; // } // // public void scale(double s) { // this.x *= s; // this.y *= s; // this.z *= s; // } // // public double length() { // return Math.sqrt(x*x + y*y + z*z); // } // // public void normalize() { // double l = length(); // if (l > 0) { // this.x /= l; // this.y /= l; // this.z /= l; // } // } // // public double distanceTo(ScriptVec3 vec) { // double dx = this.x - vec.x; // double dy = this.y - vec.y; // double dz = this.z - vec.z; // return Math.sqrt(dx*dx + dy*dy + dz*dz); // } // }
import java.util.Random; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import scripting.wrapper.ScriptItemStack; import scripting.wrapper.ScriptVec3;
public Random getRNG() { return entityLivingBase.getRNG(); } public void clearActivePotions() { entityLivingBase.clearActivePotions(); } public ScriptItemStack getHeldItem() { return ScriptItemStack.fromItemStack(entityLivingBase.getHeldItem()); } public ScriptItemStack getCurrentItemOrArmor(int slot) { return ScriptItemStack.fromItemStack(entityLivingBase.getEquipmentInSlot(slot)); } public void setCurrentItemOrArmor(int slot, ScriptItemStack is) { ItemStack stack = (is == null) ? null : is.stack; entityLivingBase.setCurrentItemOrArmor(slot, stack); } public void setSprinting(boolean sprint) { entityLivingBase.setSprinting(sprint); } public void setJumping(boolean jump) { entityLivingBase.setJumping(jump); }
// Path: scripting/wrapper/ScriptItemStack.java // public class ScriptItemStack { // // public final ItemStack stack; // // private ScriptItemStack(ItemStack is) { // this.stack = is; // } // // public ScriptItemStack(ScriptItem item, int size, int damage) { // this.stack = new ItemStack((item == null) ? null : item.item, size, damage); // } // // public ScriptItemStack(ScriptBlock block, int size, int damage) { // this.stack = new ItemStack((block == null) ? null : block.block, size, damage); // } // // public ScriptItem getItem() { // return (stack.getItem() == null) ? null : ScriptItem.fromItem(stack.getItem()); // } // // public int getStackSize() { // return stack.stackSize; // } // // public void setStackSize(int size) { // stack.stackSize = size; // } // // public int getItemDamage() { // return stack.getItemDamage(); // } // // public void setItemDamage(int damage) { // stack.setItemDamage(damage); // } // // public boolean hasTagCompound() { // return stack.hasTagCompound(); // } // // public TAG_Compound getTagCompound() { // return (hasTagCompound()) ? new TAG_Compound(stack.getTagCompound()) : null; // } // // public void setTagCompound(TAG_Compound tag) { // stack.setTagCompound((tag == null) ? null : tag.tag); // } // // public TAG_Compound writeToTag() { // return new TAG_Compound(stack.writeToNBT(new NBTTagCompound())); // } // // public void readFromTag(TAG_Compound tag) { // stack.readFromNBT(tag.tag); // } // // public static ScriptItemStack fromItemStack(ItemStack stack) { // return (stack == null) ? null : new ScriptItemStack(stack); // } // // } // // Path: scripting/wrapper/ScriptVec3.java // public class ScriptVec3 { // // public double x; // public double y; // public double z; // // public ScriptVec3(double x, double y, double z) { // this.x = x; // this.y = y; // this.z = z; // } // // public ScriptVec3() { // this(0, 0, 0); // } // // public void add(ScriptVec3 vec) { // this.x += vec.x; // this.y += vec.y; // this.z += vec.z; // } // // public void add(double x, double y, double z) { // this.x += x; // this.y += y; // this.z += z; // } // // public void multiply(ScriptVec3 vec) { // this.x *= vec.x; // this.y *= vec.y; // this.z *= vec.z; // } // // public void multiply(double x, double y, double z) { // this.x *= x; // this.y *= y; // this.z *= z; // } // // public void scale(double s) { // this.x *= s; // this.y *= s; // this.z *= s; // } // // public double length() { // return Math.sqrt(x*x + y*y + z*z); // } // // public void normalize() { // double l = length(); // if (l > 0) { // this.x /= l; // this.y /= l; // this.z /= l; // } // } // // public double distanceTo(ScriptVec3 vec) { // double dx = this.x - vec.x; // double dy = this.y - vec.y; // double dz = this.z - vec.z; // return Math.sqrt(dx*dx + dy*dy + dz*dz); // } // } // Path: scripting/wrapper/entity/ScriptEntityLivingBase.java import java.util.Random; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import scripting.wrapper.ScriptItemStack; import scripting.wrapper.ScriptVec3; public Random getRNG() { return entityLivingBase.getRNG(); } public void clearActivePotions() { entityLivingBase.clearActivePotions(); } public ScriptItemStack getHeldItem() { return ScriptItemStack.fromItemStack(entityLivingBase.getHeldItem()); } public ScriptItemStack getCurrentItemOrArmor(int slot) { return ScriptItemStack.fromItemStack(entityLivingBase.getEquipmentInSlot(slot)); } public void setCurrentItemOrArmor(int slot, ScriptItemStack is) { ItemStack stack = (is == null) ? null : is.stack; entityLivingBase.setCurrentItemOrArmor(slot, stack); } public void setSprinting(boolean sprint) { entityLivingBase.setSprinting(sprint); } public void setJumping(boolean jump) { entityLivingBase.setJumping(jump); }
public void setPositionAndUpdate(ScriptVec3 vec) {
DavidGoldman/MinecraftScripting
scripting/wrapper/settings/SettingBlock.java
// Path: scripting/wrapper/world/ScriptBlock.java // public class ScriptBlock { // // public final Block block; // public int blockData; // // private ScriptBlock(Block b) { // this(b, 0); // } // // private ScriptBlock(Block block, int blockData) { // this.block = block; // this.blockData = blockData; // } // // public String getBlockName() { // return Block.blockRegistry.getNameForObject(block); // } // // public boolean equalsIgnoreMetadata(ScriptBlock otherBlock) { // return otherBlock != null && this.block == otherBlock.block; // } // // public boolean equals(Object obj) { // if (!(obj instanceof ScriptBlock)) // return false; // ScriptBlock otherBlock = (ScriptBlock)obj; // return otherBlock != null && this.block == otherBlock.block && this.blockData == otherBlock.blockData; // } // // public static ScriptBlock atLocation(World world, int x, int y, int z) { // Block b = world.getBlock(x, y, z); // return (b == null) ? null : new ScriptBlock(b, world.getBlockMetadata(x, y, z)); // } // // public static ScriptBlock forName(String name) { // return fromBlock(Block.getBlockFromName(name)); // } // // public static ScriptBlock fromBlock(Block b) { // return (b == null) ? null : new ScriptBlock(b); // } // // public static ScriptBlock fromBlock(Block b, int data) { // return (b == null) ? null : new ScriptBlock(b, data); // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import net.minecraft.block.Block; import scripting.wrapper.world.ScriptBlock;
package scripting.wrapper.settings; public class SettingBlock extends Setting { public int blockID; public int blockData; protected SettingBlock() { } /** * * @param display Name of this setting * @deprecated As of v1.1.0, block IDs are deprecated. Do NOT rely on them. Use {@link SettingBlock#SettingBlock(String, ScriptBlock)} instead. */ @Deprecated public SettingBlock(String display) { this(display, 0, 0); } /** * * @param display Name of this setting * @deprecated As of v1.1.0, block IDs are deprecated. Do NOT rely on them. Use {@link SettingBlock#SettingBlock(String, ScriptBlock)} instead. */ @Deprecated public SettingBlock(String display, int blockID) { this(display, blockID, 0); } /** * * @param display Name of this setting * @deprecated As of v1.1.0, block IDs are deprecated. Do NOT rely on them. Use {@link SettingBlock#SettingBlock(String, ScriptBlock, int)} instead. */ @Deprecated public SettingBlock(String display, int blockID, int blockData) { super(display); this.blockID = blockID; this.blockData = blockData; }
// Path: scripting/wrapper/world/ScriptBlock.java // public class ScriptBlock { // // public final Block block; // public int blockData; // // private ScriptBlock(Block b) { // this(b, 0); // } // // private ScriptBlock(Block block, int blockData) { // this.block = block; // this.blockData = blockData; // } // // public String getBlockName() { // return Block.blockRegistry.getNameForObject(block); // } // // public boolean equalsIgnoreMetadata(ScriptBlock otherBlock) { // return otherBlock != null && this.block == otherBlock.block; // } // // public boolean equals(Object obj) { // if (!(obj instanceof ScriptBlock)) // return false; // ScriptBlock otherBlock = (ScriptBlock)obj; // return otherBlock != null && this.block == otherBlock.block && this.blockData == otherBlock.blockData; // } // // public static ScriptBlock atLocation(World world, int x, int y, int z) { // Block b = world.getBlock(x, y, z); // return (b == null) ? null : new ScriptBlock(b, world.getBlockMetadata(x, y, z)); // } // // public static ScriptBlock forName(String name) { // return fromBlock(Block.getBlockFromName(name)); // } // // public static ScriptBlock fromBlock(Block b) { // return (b == null) ? null : new ScriptBlock(b); // } // // public static ScriptBlock fromBlock(Block b, int data) { // return (b == null) ? null : new ScriptBlock(b, data); // } // } // Path: scripting/wrapper/settings/SettingBlock.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import net.minecraft.block.Block; import scripting.wrapper.world.ScriptBlock; package scripting.wrapper.settings; public class SettingBlock extends Setting { public int blockID; public int blockData; protected SettingBlock() { } /** * * @param display Name of this setting * @deprecated As of v1.1.0, block IDs are deprecated. Do NOT rely on them. Use {@link SettingBlock#SettingBlock(String, ScriptBlock)} instead. */ @Deprecated public SettingBlock(String display) { this(display, 0, 0); } /** * * @param display Name of this setting * @deprecated As of v1.1.0, block IDs are deprecated. Do NOT rely on them. Use {@link SettingBlock#SettingBlock(String, ScriptBlock)} instead. */ @Deprecated public SettingBlock(String display, int blockID) { this(display, blockID, 0); } /** * * @param display Name of this setting * @deprecated As of v1.1.0, block IDs are deprecated. Do NOT rely on them. Use {@link SettingBlock#SettingBlock(String, ScriptBlock, int)} instead. */ @Deprecated public SettingBlock(String display, int blockID, int blockData) { super(display); this.blockID = blockID; this.blockData = blockData; }
public SettingBlock(String display, ScriptBlock block) {
DavidGoldman/MinecraftScripting
scripting/packet/CloseGUIPacket.java
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler;
package scripting.packet; public class CloseGUIPacket extends ScriptPacket { @Override public ScriptPacket readData(Object... data) { return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { } @Override
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // Path: scripting/packet/CloseGUIPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; package scripting.packet; public class CloseGUIPacket extends ScriptPacket { @Override public ScriptPacket readData(Object... data) { return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { } @Override
public void execute(ScriptPacketHandler handler, EntityPlayer player) {
DavidGoldman/MinecraftScripting
scripting/wrapper/settings/SettingList.java
// Path: scripting/packet/ScriptPacket.java // public abstract class ScriptPacket extends AbstractPacket { // // public static final String PACKET_ID = "scripting"; // // public enum PacketType { // // SELECTION(SelectionPacket.class), // HAS_SCRIPTS(HasScriptsPacket.class), // STATE(StatePacket.class), // SETTINGS(SettingsPacket.class), // ENTITY_NBT(EntityNBTPacket.class), // TILE_NBT(TileNBTPacket.class), // CLOSE_GUI(CloseGUIPacket.class), // REQUEST(RequestPacket.class); // // private Class<? extends ScriptPacket> packetType; // // private PacketType(Class<? extends ScriptPacket> cls) { // this.packetType = cls; // } // // private ScriptPacket make() { // try { // return packetType.newInstance(); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static int ordinalForClass(Class<? extends ScriptPacket> cls) throws IllegalArgumentException { // PacketType[] values = PacketType.values(); // for (int i = 0; i < values.length; ++i) // if (values[i].packetType == cls) // return i; // throw new IllegalArgumentException("Unknown class " + cls); // } // } // // public abstract ScriptPacket readData(Object... data); // // //Packet creation // public static ScriptPacket getRequestPacket(PacketType type) { // return getPacket(PacketType.REQUEST, UnsignedBytes.checkedCast(type.ordinal())); // } // // public static ScriptPacket getRequestPacket(PacketType type, String data) { // return getPacket(PacketType.REQUEST, UnsignedBytes.checkedCast(type.ordinal()), data); // } // // public static ScriptPacket getPacket(PacketType type, Object... data) { // return type.make().readData(data); // } // // //Helper methods for the PacketPipeline // public static ScriptPacket readPacket(ChannelHandlerContext ctx, ByteBuf payload) throws IOException { // int type = UnsignedBytes.toInt(payload.readByte()); // PacketType pType = PacketType.values()[type]; // ScriptPacket packet = pType.make(); // packet.decodeFrom(ctx, payload.slice()); // return packet; // } // // public static void writePacket(ScriptPacket pkt, ChannelHandlerContext ctx, ByteBuf to) throws IOException { // to.writeByte(UnsignedBytes.checkedCast(PacketType.ordinalForClass(pkt.getClass()))); // pkt.encodeInto(ctx, to); // } // // // //String ByteBuf utility methods // public static void writeString(String str, ByteBuf buffer) { // ByteBufUtils.writeUTF8String(buffer, str); // } // // public static String readString(ByteBuf buffer) { // return ByteBufUtils.readUTF8String(buffer); // } // // public static void writeStringArray(String[] arr, ByteBuf to) { // to.writeInt(arr.length); // for (String s : arr) // writeString(s, to); // } // // public static String[] readStringArray(ByteBuf from) { // String[] arr = new String[from.readInt()]; // for (int i = 0; i < arr.length; ++i) // arr[i] = readString(from); // return arr; // } // // // //Data(In/Out)put utility methods // public static void writeNBT(NBTTagCompound compound, DataOutput out) throws IOException { // CompressedStreamTools.write(compound, out); // } // // public static NBTTagCompound readNBT(DataInput in) throws IOException { // return CompressedStreamTools.read(in); // } // // public static void writeItemStack(ItemStack stack, DataOutput out) throws IOException { // writeNBT(stack.writeToNBT(new NBTTagCompound()), out); // } // // public static ItemStack readItemStack(DataInput in) throws IOException { // return ItemStack.loadItemStackFromNBT(readNBT(in)); // } // // public static void writeStringArray(String[] arr, DataOutput out) throws IOException { // out.writeInt(arr.length); // for (String s : arr) // out.writeUTF(s); // } // // public static String[] readStringArray(DataInput in) throws IOException { // String[] arr = new String[in.readInt()]; // for (int i = 0; i < arr.length; ++i) // arr[i] = in.readUTF(); // return arr; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.commons.lang3.ArrayUtils; import scripting.packet.ScriptPacket;
package scripting.wrapper.settings; public class SettingList extends Setting { public String[] options; public String selected; protected SettingList() { } public SettingList(String display, String... options) throws IllegalArgumentException { super(display); this.options = options; if (options.length == 0) throw new IllegalArgumentException("Must have at least 1 option!"); selected = options[0]; } public SettingList(String display, String firstOption, String... options) { this(display, ArrayUtils.addAll(new String[] { firstOption }, options)); } @Override public Object getValue() { return selected; } @Override protected void write(DataOutput out) throws IOException { super.write(out);
// Path: scripting/packet/ScriptPacket.java // public abstract class ScriptPacket extends AbstractPacket { // // public static final String PACKET_ID = "scripting"; // // public enum PacketType { // // SELECTION(SelectionPacket.class), // HAS_SCRIPTS(HasScriptsPacket.class), // STATE(StatePacket.class), // SETTINGS(SettingsPacket.class), // ENTITY_NBT(EntityNBTPacket.class), // TILE_NBT(TileNBTPacket.class), // CLOSE_GUI(CloseGUIPacket.class), // REQUEST(RequestPacket.class); // // private Class<? extends ScriptPacket> packetType; // // private PacketType(Class<? extends ScriptPacket> cls) { // this.packetType = cls; // } // // private ScriptPacket make() { // try { // return packetType.newInstance(); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // public static int ordinalForClass(Class<? extends ScriptPacket> cls) throws IllegalArgumentException { // PacketType[] values = PacketType.values(); // for (int i = 0; i < values.length; ++i) // if (values[i].packetType == cls) // return i; // throw new IllegalArgumentException("Unknown class " + cls); // } // } // // public abstract ScriptPacket readData(Object... data); // // //Packet creation // public static ScriptPacket getRequestPacket(PacketType type) { // return getPacket(PacketType.REQUEST, UnsignedBytes.checkedCast(type.ordinal())); // } // // public static ScriptPacket getRequestPacket(PacketType type, String data) { // return getPacket(PacketType.REQUEST, UnsignedBytes.checkedCast(type.ordinal()), data); // } // // public static ScriptPacket getPacket(PacketType type, Object... data) { // return type.make().readData(data); // } // // //Helper methods for the PacketPipeline // public static ScriptPacket readPacket(ChannelHandlerContext ctx, ByteBuf payload) throws IOException { // int type = UnsignedBytes.toInt(payload.readByte()); // PacketType pType = PacketType.values()[type]; // ScriptPacket packet = pType.make(); // packet.decodeFrom(ctx, payload.slice()); // return packet; // } // // public static void writePacket(ScriptPacket pkt, ChannelHandlerContext ctx, ByteBuf to) throws IOException { // to.writeByte(UnsignedBytes.checkedCast(PacketType.ordinalForClass(pkt.getClass()))); // pkt.encodeInto(ctx, to); // } // // // //String ByteBuf utility methods // public static void writeString(String str, ByteBuf buffer) { // ByteBufUtils.writeUTF8String(buffer, str); // } // // public static String readString(ByteBuf buffer) { // return ByteBufUtils.readUTF8String(buffer); // } // // public static void writeStringArray(String[] arr, ByteBuf to) { // to.writeInt(arr.length); // for (String s : arr) // writeString(s, to); // } // // public static String[] readStringArray(ByteBuf from) { // String[] arr = new String[from.readInt()]; // for (int i = 0; i < arr.length; ++i) // arr[i] = readString(from); // return arr; // } // // // //Data(In/Out)put utility methods // public static void writeNBT(NBTTagCompound compound, DataOutput out) throws IOException { // CompressedStreamTools.write(compound, out); // } // // public static NBTTagCompound readNBT(DataInput in) throws IOException { // return CompressedStreamTools.read(in); // } // // public static void writeItemStack(ItemStack stack, DataOutput out) throws IOException { // writeNBT(stack.writeToNBT(new NBTTagCompound()), out); // } // // public static ItemStack readItemStack(DataInput in) throws IOException { // return ItemStack.loadItemStackFromNBT(readNBT(in)); // } // // public static void writeStringArray(String[] arr, DataOutput out) throws IOException { // out.writeInt(arr.length); // for (String s : arr) // out.writeUTF(s); // } // // public static String[] readStringArray(DataInput in) throws IOException { // String[] arr = new String[in.readInt()]; // for (int i = 0; i < arr.length; ++i) // arr[i] = in.readUTF(); // return arr; // } // } // Path: scripting/wrapper/settings/SettingList.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.commons.lang3.ArrayUtils; import scripting.packet.ScriptPacket; package scripting.wrapper.settings; public class SettingList extends Setting { public String[] options; public String selected; protected SettingList() { } public SettingList(String display, String... options) throws IllegalArgumentException { super(display); this.options = options; if (options.length == 0) throw new IllegalArgumentException("Must have at least 1 option!"); selected = options[0]; } public SettingList(String display, String firstOption, String... options) { this(display, ArrayUtils.addAll(new String[] { firstOption }, options)); } @Override public Object getValue() { return selected; } @Override protected void write(DataOutput out) throws IOException { super.write(out);
ScriptPacket.writeStringArray(options, out);
DavidGoldman/MinecraftScripting
scripting/packet/SettingsPacket.java
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // // Path: scripting/wrapper/settings/Setting.java // public abstract class Setting { // // public String display; // // protected Setting() { } // // public Setting(String display) { // this.display = display; // } // // public abstract Object getValue(); // // protected void write(DataOutput out) throws IOException { // out.writeUTF(display); // } // // protected Setting read(DataInput in) throws IOException { // display = in.readUTF(); // return this; // } // // public static Setting readSetting(DataInput in) throws IOException { // switch(in.readByte()) { // case 0: return new SettingBoolean().read(in); // case 1: return new SettingInt().read(in); // case 2: return new SettingFloat().read(in); // case 3: return new SettingString().read(in); // case 4: return new SettingList().read(in); // case 5: return new SettingBlock().read(in); // case 6: return new SettingItem().read(in); // default: return null; // } // } // // public static void write(Setting setting, DataOutput out) throws IOException { // if (setting == null) // return; // if (setting instanceof SettingBoolean) // out.write(0); // if (setting instanceof SettingInt) // out.write(1); // if (setting instanceof SettingFloat) // out.write(2); // if (setting instanceof SettingString) // out.write(3); // if (setting instanceof SettingList) // out.write(4); // if (setting instanceof SettingBlock) // out.write(5); // if (setting instanceof SettingItem) // out.write(6); // setting.write(out); // } // // /** // * Helper method for filters // */ // public static Setting[] toArray(Setting... settings) { // return settings; // } // // }
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; import scripting.wrapper.settings.Setting;
package scripting.packet; public class SettingsPacket extends ScriptPacket { public String script;
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // // Path: scripting/wrapper/settings/Setting.java // public abstract class Setting { // // public String display; // // protected Setting() { } // // public Setting(String display) { // this.display = display; // } // // public abstract Object getValue(); // // protected void write(DataOutput out) throws IOException { // out.writeUTF(display); // } // // protected Setting read(DataInput in) throws IOException { // display = in.readUTF(); // return this; // } // // public static Setting readSetting(DataInput in) throws IOException { // switch(in.readByte()) { // case 0: return new SettingBoolean().read(in); // case 1: return new SettingInt().read(in); // case 2: return new SettingFloat().read(in); // case 3: return new SettingString().read(in); // case 4: return new SettingList().read(in); // case 5: return new SettingBlock().read(in); // case 6: return new SettingItem().read(in); // default: return null; // } // } // // public static void write(Setting setting, DataOutput out) throws IOException { // if (setting == null) // return; // if (setting instanceof SettingBoolean) // out.write(0); // if (setting instanceof SettingInt) // out.write(1); // if (setting instanceof SettingFloat) // out.write(2); // if (setting instanceof SettingString) // out.write(3); // if (setting instanceof SettingList) // out.write(4); // if (setting instanceof SettingBlock) // out.write(5); // if (setting instanceof SettingItem) // out.write(6); // setting.write(out); // } // // /** // * Helper method for filters // */ // public static Setting[] toArray(Setting... settings) { // return settings; // } // // } // Path: scripting/packet/SettingsPacket.java import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; import scripting.wrapper.settings.Setting; package scripting.packet; public class SettingsPacket extends ScriptPacket { public String script;
public Setting[] settings;
DavidGoldman/MinecraftScripting
scripting/packet/SettingsPacket.java
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // // Path: scripting/wrapper/settings/Setting.java // public abstract class Setting { // // public String display; // // protected Setting() { } // // public Setting(String display) { // this.display = display; // } // // public abstract Object getValue(); // // protected void write(DataOutput out) throws IOException { // out.writeUTF(display); // } // // protected Setting read(DataInput in) throws IOException { // display = in.readUTF(); // return this; // } // // public static Setting readSetting(DataInput in) throws IOException { // switch(in.readByte()) { // case 0: return new SettingBoolean().read(in); // case 1: return new SettingInt().read(in); // case 2: return new SettingFloat().read(in); // case 3: return new SettingString().read(in); // case 4: return new SettingList().read(in); // case 5: return new SettingBlock().read(in); // case 6: return new SettingItem().read(in); // default: return null; // } // } // // public static void write(Setting setting, DataOutput out) throws IOException { // if (setting == null) // return; // if (setting instanceof SettingBoolean) // out.write(0); // if (setting instanceof SettingInt) // out.write(1); // if (setting instanceof SettingFloat) // out.write(2); // if (setting instanceof SettingString) // out.write(3); // if (setting instanceof SettingList) // out.write(4); // if (setting instanceof SettingBlock) // out.write(5); // if (setting instanceof SettingItem) // out.write(6); // setting.write(out); // } // // /** // * Helper method for filters // */ // public static Setting[] toArray(Setting... settings) { // return settings; // } // // }
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; import scripting.wrapper.settings.Setting;
package scripting.packet; public class SettingsPacket extends ScriptPacket { public String script; public Setting[] settings; @Override public ScriptPacket readData(Object... data) { script = (String) data[0]; settings = (Setting[]) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { ByteBufOutputStream bos = new ByteBufOutputStream(to); bos.writeUTF(script); bos.writeInt(settings.length); for (Setting s : settings) Setting.write(s, bos); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { ByteBufInputStream bis = new ByteBufInputStream(from); script = bis.readUTF(); settings = new Setting[bis.readInt()]; for (int i = 0; i < settings.length; ++i) settings[i] = Setting.readSetting(bis); } @Override
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // // Path: scripting/wrapper/settings/Setting.java // public abstract class Setting { // // public String display; // // protected Setting() { } // // public Setting(String display) { // this.display = display; // } // // public abstract Object getValue(); // // protected void write(DataOutput out) throws IOException { // out.writeUTF(display); // } // // protected Setting read(DataInput in) throws IOException { // display = in.readUTF(); // return this; // } // // public static Setting readSetting(DataInput in) throws IOException { // switch(in.readByte()) { // case 0: return new SettingBoolean().read(in); // case 1: return new SettingInt().read(in); // case 2: return new SettingFloat().read(in); // case 3: return new SettingString().read(in); // case 4: return new SettingList().read(in); // case 5: return new SettingBlock().read(in); // case 6: return new SettingItem().read(in); // default: return null; // } // } // // public static void write(Setting setting, DataOutput out) throws IOException { // if (setting == null) // return; // if (setting instanceof SettingBoolean) // out.write(0); // if (setting instanceof SettingInt) // out.write(1); // if (setting instanceof SettingFloat) // out.write(2); // if (setting instanceof SettingString) // out.write(3); // if (setting instanceof SettingList) // out.write(4); // if (setting instanceof SettingBlock) // out.write(5); // if (setting instanceof SettingItem) // out.write(6); // setting.write(out); // } // // /** // * Helper method for filters // */ // public static Setting[] toArray(Setting... settings) { // return settings; // } // // } // Path: scripting/packet/SettingsPacket.java import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.network.ScriptPacketHandler; import scripting.wrapper.settings.Setting; package scripting.packet; public class SettingsPacket extends ScriptPacket { public String script; public Setting[] settings; @Override public ScriptPacket readData(Object... data) { script = (String) data[0]; settings = (Setting[]) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { ByteBufOutputStream bos = new ByteBufOutputStream(to); bos.writeUTF(script); bos.writeInt(settings.length); for (Setting s : settings) Setting.write(s, bos); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { ByteBufInputStream bis = new ByteBufInputStream(from); script = bis.readUTF(); settings = new Setting[bis.readInt()]; for (int i = 0; i < settings.length; ++i) settings[i] = Setting.readSetting(bis); } @Override
public void execute(ScriptPacketHandler handler, EntityPlayer player) {
DavidGoldman/MinecraftScripting
scripting/packet/StatePacket.java
// Path: scripting/core/ScriptCore.java // public static final class State implements Comparable<State> { // public final String script; // public final boolean running; // // public State(String script, boolean running) { // this.script = script; // this.running = running; // } // // @Override // public int compareTo(State obj) { // return this.script.compareTo(obj.script); // } // } // // Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.core.ScriptCore.State; import scripting.network.ScriptPacketHandler;
package scripting.packet; public class StatePacket extends ScriptPacket { public State[] states; @Override public ScriptPacket readData(Object... data) { states = (State[]) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeInt(states.length); for (State s : states) { writeString(s.script, to); to.writeBoolean(s.running); } } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { states = new State[from.readInt()]; for (int i = 0; i < states.length; ++i) states[i] = new State(readString(from), from.readBoolean()); } @Override
// Path: scripting/core/ScriptCore.java // public static final class State implements Comparable<State> { // public final String script; // public final boolean running; // // public State(String script, boolean running) { // this.script = script; // this.running = running; // } // // @Override // public int compareTo(State obj) { // return this.script.compareTo(obj.script); // } // } // // Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // Path: scripting/packet/StatePacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import scripting.core.ScriptCore.State; import scripting.network.ScriptPacketHandler; package scripting.packet; public class StatePacket extends ScriptPacket { public State[] states; @Override public ScriptPacket readData(Object... data) { states = (State[]) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeInt(states.length); for (State s : states) { writeString(s.script, to); to.writeBoolean(s.running); } } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { states = new State[from.readInt()]; for (int i = 0; i < states.length; ++i) states[i] = new State(readString(from), from.readBoolean()); } @Override
public void execute(ScriptPacketHandler handler, EntityPlayer player) {
DavidGoldman/MinecraftScripting
scripting/Selection.java
// Path: scripting/utils/BlockCoord.java // public final class BlockCoord { // // public int x, y, z; // // public BlockCoord(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // public boolean equals(Object obj) { // if (obj == this) // return true; // if (! (obj instanceof BlockCoord)) // return false; // BlockCoord coord = (BlockCoord)obj; // return this.x == coord.x && this.y == coord.y && this.z == coord.z; // } // // public AxisAlignedBB getAABB() { // return AxisAlignedBB.getAABBPool().getAABB(x, y, z, x+1, y+1, z+1); // } // // public String toString() { // return "{" + x + ',' + y + ',' + z + '}'; // } // } // // Path: scripting/utils/Utils.java // public class Utils { // // public static final IEntitySelector NO_PLAYERS = new IEntitySelector(){ // @Override // public boolean isEntityApplicable(Entity entity) { // return !(entity instanceof EntityPlayer); // } // }; // // public static final RenderSetting[] RENDER_SETTINGS = new RenderSetting[] { // new RenderSetting(1f, 0f, 0f, .7f, GL11.GL_LEQUAL), // new RenderSetting(1f, 0f, 0f, .2f, GL11.GL_GREATER) // }; // // public static final RenderSetting[] CORNER1_SETTINGS = new RenderSetting[] { // new RenderSetting(0f, 1f, 0f, .7f, GL11.GL_LEQUAL), // new RenderSetting(0f, 1f, 0f, .2f, GL11.GL_GREATER) // }; // // public static final RenderSetting[] CORNER2_SETTINGS = new RenderSetting[] { // new RenderSetting(0f, 0f, 1f, .7f, GL11.GL_LEQUAL), // new RenderSetting(0f, 0f, 1f, .2f, GL11.GL_GREATER) // }; // // // public static void closeSilently(Closeable c) { // try { // if (c != null) // c.close(); // // } // catch(IOException e) { } // } // // /** // * Gets all tile entities within a Selection AABB. // * See {@link net.minecraft.world.WorldServer#getAllTileEntityInBox}. // */ // public static List<TileEntity> getTilesInSelectionAABB(World world, AxisAlignedBB selAABB) { // List<TileEntity> list = new ArrayList<TileEntity>(); // int minX = (int) selAABB.minX; // int minY = (int) selAABB.minY; // int minZ = (int) selAABB.minZ; // // int maxX = (int) selAABB.maxX - 1; // int maxY = (int) selAABB.maxY - 1; // int maxZ = (int) selAABB.maxZ - 1; // // for(int x = (minX >> 4); x <= (maxX >> 4); x++) // for(int z = (minZ >> 4); z <= (maxZ >> 4); z++) { // Chunk chunk = world.getChunkFromChunkCoords(x, z); // if (chunk != null) // for(Object obj : chunk.chunkTileEntityMap.values()) { // TileEntity entity = (TileEntity)obj; // if (!entity.isInvalid()) // if (entity.xCoord >= minX && entity.yCoord >= minY && entity.zCoord >= minZ && // entity.xCoord <= maxX && entity.yCoord <= maxY && entity.zCoord <= maxZ) // list.add(entity); // } // } // return list; // } // // public static int parseIntWithMinMax(String s, int min, int max) throws NumberFormatException { // int i = Integer.parseInt(s); // if (i < min) // return min; // if (i > max) // return max; // return i; // // } // // public static int parseIntWithDMinMax(String s, int _default, int min, int max) { // try { // return parseIntWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // public static float parseFloatWithMinMax(String s, float min, float max) throws NumberFormatException { // float f = Float.parseFloat(s); // if (f < min) // return min; // if (f > max) // return max; // return f; // } // // public static float parseFloatWithDMinMax(String s, float _default, float min, float max) { // try { // return parseFloatWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // // // // }
import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import scripting.utils.BlockCoord; import scripting.utils.Utils;
package scripting; public class Selection { private int dimension;
// Path: scripting/utils/BlockCoord.java // public final class BlockCoord { // // public int x, y, z; // // public BlockCoord(int x, int y, int z) { // this.x = x; // this.y = y; // this.z = z; // } // // public boolean equals(Object obj) { // if (obj == this) // return true; // if (! (obj instanceof BlockCoord)) // return false; // BlockCoord coord = (BlockCoord)obj; // return this.x == coord.x && this.y == coord.y && this.z == coord.z; // } // // public AxisAlignedBB getAABB() { // return AxisAlignedBB.getAABBPool().getAABB(x, y, z, x+1, y+1, z+1); // } // // public String toString() { // return "{" + x + ',' + y + ',' + z + '}'; // } // } // // Path: scripting/utils/Utils.java // public class Utils { // // public static final IEntitySelector NO_PLAYERS = new IEntitySelector(){ // @Override // public boolean isEntityApplicable(Entity entity) { // return !(entity instanceof EntityPlayer); // } // }; // // public static final RenderSetting[] RENDER_SETTINGS = new RenderSetting[] { // new RenderSetting(1f, 0f, 0f, .7f, GL11.GL_LEQUAL), // new RenderSetting(1f, 0f, 0f, .2f, GL11.GL_GREATER) // }; // // public static final RenderSetting[] CORNER1_SETTINGS = new RenderSetting[] { // new RenderSetting(0f, 1f, 0f, .7f, GL11.GL_LEQUAL), // new RenderSetting(0f, 1f, 0f, .2f, GL11.GL_GREATER) // }; // // public static final RenderSetting[] CORNER2_SETTINGS = new RenderSetting[] { // new RenderSetting(0f, 0f, 1f, .7f, GL11.GL_LEQUAL), // new RenderSetting(0f, 0f, 1f, .2f, GL11.GL_GREATER) // }; // // // public static void closeSilently(Closeable c) { // try { // if (c != null) // c.close(); // // } // catch(IOException e) { } // } // // /** // * Gets all tile entities within a Selection AABB. // * See {@link net.minecraft.world.WorldServer#getAllTileEntityInBox}. // */ // public static List<TileEntity> getTilesInSelectionAABB(World world, AxisAlignedBB selAABB) { // List<TileEntity> list = new ArrayList<TileEntity>(); // int minX = (int) selAABB.minX; // int minY = (int) selAABB.minY; // int minZ = (int) selAABB.minZ; // // int maxX = (int) selAABB.maxX - 1; // int maxY = (int) selAABB.maxY - 1; // int maxZ = (int) selAABB.maxZ - 1; // // for(int x = (minX >> 4); x <= (maxX >> 4); x++) // for(int z = (minZ >> 4); z <= (maxZ >> 4); z++) { // Chunk chunk = world.getChunkFromChunkCoords(x, z); // if (chunk != null) // for(Object obj : chunk.chunkTileEntityMap.values()) { // TileEntity entity = (TileEntity)obj; // if (!entity.isInvalid()) // if (entity.xCoord >= minX && entity.yCoord >= minY && entity.zCoord >= minZ && // entity.xCoord <= maxX && entity.yCoord <= maxY && entity.zCoord <= maxZ) // list.add(entity); // } // } // return list; // } // // public static int parseIntWithMinMax(String s, int min, int max) throws NumberFormatException { // int i = Integer.parseInt(s); // if (i < min) // return min; // if (i > max) // return max; // return i; // // } // // public static int parseIntWithDMinMax(String s, int _default, int min, int max) { // try { // return parseIntWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // public static float parseFloatWithMinMax(String s, float min, float max) throws NumberFormatException { // float f = Float.parseFloat(s); // if (f < min) // return min; // if (f > max) // return max; // return f; // } // // public static float parseFloatWithDMinMax(String s, float _default, float min, float max) { // try { // return parseFloatWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // // // // } // Path: scripting/Selection.java import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import scripting.utils.BlockCoord; import scripting.utils.Utils; package scripting; public class Selection { private int dimension;
private BlockCoord corner1, corner2;
DavidGoldman/MinecraftScripting
scripting/wrapper/js/TagItr.java
// Path: scripting/wrapper/nbt/TAG_Base.java // public abstract class TAG_Base { // // protected final NBTBase base; // // public TAG_Base(NBTBase base) { // this.base = base; // } // // public abstract TAG_Base copy(); // // public String toString() { // return base.toString(); // } // // public int hashCode() { // return base.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof TAG_Base) // return ((TAG_Base)obj).base.equals(base); // return false; // } // // /** // * Called to create a script visible NBT Tag. // */ // public static TAG_Base createFromNative(NBTBase base) { // if (base instanceof NBTTagByte) // return new TAG_Byte((NBTTagByte)base); // if (base instanceof NBTTagByteArray) // return new TAG_Byte_Array((NBTTagByteArray)base); // if (base instanceof NBTTagCompound) // return new TAG_Compound((NBTTagCompound)base); // if (base instanceof NBTTagDouble) // return new TAG_Double((NBTTagDouble)base); // if (base instanceof NBTTagFloat) // return new TAG_Float((NBTTagFloat)base); // if (base instanceof NBTTagInt) // return new TAG_Int((NBTTagInt)base); // if (base instanceof NBTTagIntArray) // return new TAG_Int_Array((NBTTagIntArray)base); // if (base instanceof NBTTagList) // return new TAG_List((NBTTagList)base); // if (base instanceof NBTTagLong) // return new TAG_Long((NBTTagLong)base); // if (base instanceof NBTTagShort) // return new TAG_Short((NBTTagShort)base); // if (base instanceof NBTTagString) // return new TAG_String((NBTTagString)base); // return null; // // } // } // // Path: scripting/wrapper/nbt/TAG_List.java // public class TAG_List extends TAG_Base { // // public final NBTTagList list; // // public TAG_List() { // super(new NBTTagList()); // // list = (NBTTagList)base; // } // // public TAG_List(NBTTagList list) { // super(list); // // this.list = list; // } // // public TAG_Base copy() { // return new TAG_List((NBTTagList)list.copy()); // } // // public void appendTag(TAG_Base tag) { // list.appendTag(tag.base); // } // // public TAG_Base removeTag(int index) { // return TAG_Base.createFromNative(list.removeTag(index)); // } // // //TODO Improve/cache field? // public TAG_Base tagAt(int index) { // List<NBTBase> tagList = ReflectionHelper.getPrivateValue(NBTTagList.class, list, 0); // return TAG_Base.createFromNative(tagList.get(index)); // } // // public int tagCount() { // return list.tagCount(); // } // // public static TAG_List newFloatList(float... list) { // NBTTagList tagList = new NBTTagList(); // for (float f : list) // tagList.appendTag(new NBTTagFloat(f)); // return new TAG_List(tagList); // } // // public static TAG_List newDoubleList(double... list) { // NBTTagList tagList = new NBTTagList(); // for (double d : list) // tagList.appendTag(new NBTTagDouble(d)); // return new TAG_List(tagList); // } // // // }
import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeIterator; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.annotations.JSConstructor; import org.mozilla.javascript.annotations.JSFunction; import scripting.wrapper.nbt.TAG_Base; import scripting.wrapper.nbt.TAG_List;
package scripting.wrapper.js; /** * Javascript TAG_List iterator. * * Usage: "for (var tag in new TagItr(tagList)) ..." * * See {@link scripting.wrapper.js.Range} for more information. * */ public class TagItr extends ScriptableObject { /** * */ private static final long serialVersionUID = 1L;
// Path: scripting/wrapper/nbt/TAG_Base.java // public abstract class TAG_Base { // // protected final NBTBase base; // // public TAG_Base(NBTBase base) { // this.base = base; // } // // public abstract TAG_Base copy(); // // public String toString() { // return base.toString(); // } // // public int hashCode() { // return base.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof TAG_Base) // return ((TAG_Base)obj).base.equals(base); // return false; // } // // /** // * Called to create a script visible NBT Tag. // */ // public static TAG_Base createFromNative(NBTBase base) { // if (base instanceof NBTTagByte) // return new TAG_Byte((NBTTagByte)base); // if (base instanceof NBTTagByteArray) // return new TAG_Byte_Array((NBTTagByteArray)base); // if (base instanceof NBTTagCompound) // return new TAG_Compound((NBTTagCompound)base); // if (base instanceof NBTTagDouble) // return new TAG_Double((NBTTagDouble)base); // if (base instanceof NBTTagFloat) // return new TAG_Float((NBTTagFloat)base); // if (base instanceof NBTTagInt) // return new TAG_Int((NBTTagInt)base); // if (base instanceof NBTTagIntArray) // return new TAG_Int_Array((NBTTagIntArray)base); // if (base instanceof NBTTagList) // return new TAG_List((NBTTagList)base); // if (base instanceof NBTTagLong) // return new TAG_Long((NBTTagLong)base); // if (base instanceof NBTTagShort) // return new TAG_Short((NBTTagShort)base); // if (base instanceof NBTTagString) // return new TAG_String((NBTTagString)base); // return null; // // } // } // // Path: scripting/wrapper/nbt/TAG_List.java // public class TAG_List extends TAG_Base { // // public final NBTTagList list; // // public TAG_List() { // super(new NBTTagList()); // // list = (NBTTagList)base; // } // // public TAG_List(NBTTagList list) { // super(list); // // this.list = list; // } // // public TAG_Base copy() { // return new TAG_List((NBTTagList)list.copy()); // } // // public void appendTag(TAG_Base tag) { // list.appendTag(tag.base); // } // // public TAG_Base removeTag(int index) { // return TAG_Base.createFromNative(list.removeTag(index)); // } // // //TODO Improve/cache field? // public TAG_Base tagAt(int index) { // List<NBTBase> tagList = ReflectionHelper.getPrivateValue(NBTTagList.class, list, 0); // return TAG_Base.createFromNative(tagList.get(index)); // } // // public int tagCount() { // return list.tagCount(); // } // // public static TAG_List newFloatList(float... list) { // NBTTagList tagList = new NBTTagList(); // for (float f : list) // tagList.appendTag(new NBTTagFloat(f)); // return new TAG_List(tagList); // } // // public static TAG_List newDoubleList(double... list) { // NBTTagList tagList = new NBTTagList(); // for (double d : list) // tagList.appendTag(new NBTTagDouble(d)); // return new TAG_List(tagList); // } // // // } // Path: scripting/wrapper/js/TagItr.java import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeIterator; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.annotations.JSConstructor; import org.mozilla.javascript.annotations.JSFunction; import scripting.wrapper.nbt.TAG_Base; import scripting.wrapper.nbt.TAG_List; package scripting.wrapper.js; /** * Javascript TAG_List iterator. * * Usage: "for (var tag in new TagItr(tagList)) ..." * * See {@link scripting.wrapper.js.Range} for more information. * */ public class TagItr extends ScriptableObject { /** * */ private static final long serialVersionUID = 1L;
TAG_List list;
DavidGoldman/MinecraftScripting
scripting/wrapper/js/TagItr.java
// Path: scripting/wrapper/nbt/TAG_Base.java // public abstract class TAG_Base { // // protected final NBTBase base; // // public TAG_Base(NBTBase base) { // this.base = base; // } // // public abstract TAG_Base copy(); // // public String toString() { // return base.toString(); // } // // public int hashCode() { // return base.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof TAG_Base) // return ((TAG_Base)obj).base.equals(base); // return false; // } // // /** // * Called to create a script visible NBT Tag. // */ // public static TAG_Base createFromNative(NBTBase base) { // if (base instanceof NBTTagByte) // return new TAG_Byte((NBTTagByte)base); // if (base instanceof NBTTagByteArray) // return new TAG_Byte_Array((NBTTagByteArray)base); // if (base instanceof NBTTagCompound) // return new TAG_Compound((NBTTagCompound)base); // if (base instanceof NBTTagDouble) // return new TAG_Double((NBTTagDouble)base); // if (base instanceof NBTTagFloat) // return new TAG_Float((NBTTagFloat)base); // if (base instanceof NBTTagInt) // return new TAG_Int((NBTTagInt)base); // if (base instanceof NBTTagIntArray) // return new TAG_Int_Array((NBTTagIntArray)base); // if (base instanceof NBTTagList) // return new TAG_List((NBTTagList)base); // if (base instanceof NBTTagLong) // return new TAG_Long((NBTTagLong)base); // if (base instanceof NBTTagShort) // return new TAG_Short((NBTTagShort)base); // if (base instanceof NBTTagString) // return new TAG_String((NBTTagString)base); // return null; // // } // } // // Path: scripting/wrapper/nbt/TAG_List.java // public class TAG_List extends TAG_Base { // // public final NBTTagList list; // // public TAG_List() { // super(new NBTTagList()); // // list = (NBTTagList)base; // } // // public TAG_List(NBTTagList list) { // super(list); // // this.list = list; // } // // public TAG_Base copy() { // return new TAG_List((NBTTagList)list.copy()); // } // // public void appendTag(TAG_Base tag) { // list.appendTag(tag.base); // } // // public TAG_Base removeTag(int index) { // return TAG_Base.createFromNative(list.removeTag(index)); // } // // //TODO Improve/cache field? // public TAG_Base tagAt(int index) { // List<NBTBase> tagList = ReflectionHelper.getPrivateValue(NBTTagList.class, list, 0); // return TAG_Base.createFromNative(tagList.get(index)); // } // // public int tagCount() { // return list.tagCount(); // } // // public static TAG_List newFloatList(float... list) { // NBTTagList tagList = new NBTTagList(); // for (float f : list) // tagList.appendTag(new NBTTagFloat(f)); // return new TAG_List(tagList); // } // // public static TAG_List newDoubleList(double... list) { // NBTTagList tagList = new NBTTagList(); // for (double d : list) // tagList.appendTag(new NBTTagDouble(d)); // return new TAG_List(tagList); // } // // // }
import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeIterator; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.annotations.JSConstructor; import org.mozilla.javascript.annotations.JSFunction; import scripting.wrapper.nbt.TAG_Base; import scripting.wrapper.nbt.TAG_List;
package scripting.wrapper.js; /** * Javascript TAG_List iterator. * * Usage: "for (var tag in new TagItr(tagList)) ..." * * See {@link scripting.wrapper.js.Range} for more information. * */ public class TagItr extends ScriptableObject { /** * */ private static final long serialVersionUID = 1L; TAG_List list; int index; public TagItr() { } public TagItr(TAG_List list) { this.list = list; } @JSConstructor public static Object constructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) { if (!inNewExpr) throw ScriptRuntime.constructError("TagItr Error", "Call constructor using the \"new\" keyword."); if (args.length == 1) return new TagItr((TAG_List)Context.jsToJava(args[0], TAG_List.class)); throw ScriptRuntime.constructError("TagItr Error", "Call constructor with a single TAG_List."); } @JSFunction
// Path: scripting/wrapper/nbt/TAG_Base.java // public abstract class TAG_Base { // // protected final NBTBase base; // // public TAG_Base(NBTBase base) { // this.base = base; // } // // public abstract TAG_Base copy(); // // public String toString() { // return base.toString(); // } // // public int hashCode() { // return base.hashCode(); // } // // public boolean equals(Object obj) { // if (obj instanceof TAG_Base) // return ((TAG_Base)obj).base.equals(base); // return false; // } // // /** // * Called to create a script visible NBT Tag. // */ // public static TAG_Base createFromNative(NBTBase base) { // if (base instanceof NBTTagByte) // return new TAG_Byte((NBTTagByte)base); // if (base instanceof NBTTagByteArray) // return new TAG_Byte_Array((NBTTagByteArray)base); // if (base instanceof NBTTagCompound) // return new TAG_Compound((NBTTagCompound)base); // if (base instanceof NBTTagDouble) // return new TAG_Double((NBTTagDouble)base); // if (base instanceof NBTTagFloat) // return new TAG_Float((NBTTagFloat)base); // if (base instanceof NBTTagInt) // return new TAG_Int((NBTTagInt)base); // if (base instanceof NBTTagIntArray) // return new TAG_Int_Array((NBTTagIntArray)base); // if (base instanceof NBTTagList) // return new TAG_List((NBTTagList)base); // if (base instanceof NBTTagLong) // return new TAG_Long((NBTTagLong)base); // if (base instanceof NBTTagShort) // return new TAG_Short((NBTTagShort)base); // if (base instanceof NBTTagString) // return new TAG_String((NBTTagString)base); // return null; // // } // } // // Path: scripting/wrapper/nbt/TAG_List.java // public class TAG_List extends TAG_Base { // // public final NBTTagList list; // // public TAG_List() { // super(new NBTTagList()); // // list = (NBTTagList)base; // } // // public TAG_List(NBTTagList list) { // super(list); // // this.list = list; // } // // public TAG_Base copy() { // return new TAG_List((NBTTagList)list.copy()); // } // // public void appendTag(TAG_Base tag) { // list.appendTag(tag.base); // } // // public TAG_Base removeTag(int index) { // return TAG_Base.createFromNative(list.removeTag(index)); // } // // //TODO Improve/cache field? // public TAG_Base tagAt(int index) { // List<NBTBase> tagList = ReflectionHelper.getPrivateValue(NBTTagList.class, list, 0); // return TAG_Base.createFromNative(tagList.get(index)); // } // // public int tagCount() { // return list.tagCount(); // } // // public static TAG_List newFloatList(float... list) { // NBTTagList tagList = new NBTTagList(); // for (float f : list) // tagList.appendTag(new NBTTagFloat(f)); // return new TAG_List(tagList); // } // // public static TAG_List newDoubleList(double... list) { // NBTTagList tagList = new NBTTagList(); // for (double d : list) // tagList.appendTag(new NBTTagDouble(d)); // return new TAG_List(tagList); // } // // // } // Path: scripting/wrapper/js/TagItr.java import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeIterator; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.annotations.JSConstructor; import org.mozilla.javascript.annotations.JSFunction; import scripting.wrapper.nbt.TAG_Base; import scripting.wrapper.nbt.TAG_List; package scripting.wrapper.js; /** * Javascript TAG_List iterator. * * Usage: "for (var tag in new TagItr(tagList)) ..." * * See {@link scripting.wrapper.js.Range} for more information. * */ public class TagItr extends ScriptableObject { /** * */ private static final long serialVersionUID = 1L; TAG_List list; int index; public TagItr() { } public TagItr(TAG_List list) { this.list = list; } @JSConstructor public static Object constructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) { if (!inNewExpr) throw ScriptRuntime.constructError("TagItr Error", "Call constructor using the \"new\" keyword."); if (args.length == 1) return new TagItr((TAG_List)Context.jsToJava(args[0], TAG_List.class)); throw ScriptRuntime.constructError("TagItr Error", "Call constructor with a single TAG_List."); } @JSFunction
public TAG_Base next() {
DavidGoldman/MinecraftScripting
scripting/core/script/BasicScript.java
// Path: scripting/core/ScriptException.java // public class ScriptException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public ScriptException(String message) { // super(message); // } // // public ScriptException(Throwable cause) { // super(cause); // } // }
import org.mozilla.javascript.Function; import scripting.core.ScriptException;
package scripting.core.script; public final class BasicScript extends JSScript { private Function main; private Function onExit; public BasicScript(String name, String source) { super(name, source); } /** * Initialize our main+onExit function reference here. * @throws ScriptException If no main function exists. */ @Override
// Path: scripting/core/ScriptException.java // public class ScriptException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public ScriptException(String message) { // super(message); // } // // public ScriptException(Throwable cause) { // super(cause); // } // } // Path: scripting/core/script/BasicScript.java import org.mozilla.javascript.Function; import scripting.core.ScriptException; package scripting.core.script; public final class BasicScript extends JSScript { private Function main; private Function onExit; public BasicScript(String name, String source) { super(name, source); } /** * Initialize our main+onExit function reference here. * @throws ScriptException If no main function exists. */ @Override
public void postInit() throws ScriptException {
DavidGoldman/MinecraftScripting
scripting/packet/TileNBTPacket.java
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import scripting.network.ScriptPacketHandler;
package scripting.packet; public class TileNBTPacket extends ScriptPacket { public int x, y, z; public NBTTagCompound tag; @Override public ScriptPacket readData(Object... data) { x = (Integer) data[0]; y = (Integer) data[1]; x = (Integer) data[2]; tag = (NBTTagCompound) data[3]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { ByteBufOutputStream bos = new ByteBufOutputStream(to); bos.writeInt(x); bos.writeInt(y); bos.writeInt(z); writeNBT(tag, bos); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { ByteBufInputStream bis = new ByteBufInputStream(from); x = bis.readInt(); y = bis.readInt(); z = bis.readInt(); tag = readNBT(bis); } @Override
// Path: scripting/network/ScriptPacketHandler.java // public abstract class ScriptPacketHandler { // // public abstract void handleSelection(SelectionPacket pkt, EntityPlayer player); // public abstract void handleHasScripts(HasScriptsPacket pkt, EntityPlayer player); // public abstract void handleState(StatePacket pkt, EntityPlayer player); // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // // public abstract void handleEntityNBT(EntityNBTPacket pkt, EntityPlayer player); // public abstract void handleTileNBT(TileNBTPacket pkt, EntityPlayer player); // // public abstract void handleCloseGUI(CloseGUIPacket pkt, EntityPlayer player); // public abstract void handleRequest(PacketType type, String info, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(ScriptPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // } // } // Path: scripting/packet/TileNBTPacket.java import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import scripting.network.ScriptPacketHandler; package scripting.packet; public class TileNBTPacket extends ScriptPacket { public int x, y, z; public NBTTagCompound tag; @Override public ScriptPacket readData(Object... data) { x = (Integer) data[0]; y = (Integer) data[1]; x = (Integer) data[2]; tag = (NBTTagCompound) data[3]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { ByteBufOutputStream bos = new ByteBufOutputStream(to); bos.writeInt(x); bos.writeInt(y); bos.writeInt(z); writeNBT(tag, bos); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { ByteBufInputStream bis = new ByteBufInputStream(from); x = bis.readInt(); y = bis.readInt(); z = bis.readInt(); tag = readNBT(bis); } @Override
public void execute(ScriptPacketHandler handler, EntityPlayer player) {
DavidGoldman/MinecraftScripting
scripting/core/script/FilterScript.java
// Path: scripting/core/ScriptException.java // public class ScriptException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public ScriptException(String message) { // super(message); // } // // public ScriptException(Throwable cause) { // super(cause); // } // } // // Path: scripting/wrapper/settings/Setting.java // public abstract class Setting { // // public String display; // // protected Setting() { } // // public Setting(String display) { // this.display = display; // } // // public abstract Object getValue(); // // protected void write(DataOutput out) throws IOException { // out.writeUTF(display); // } // // protected Setting read(DataInput in) throws IOException { // display = in.readUTF(); // return this; // } // // public static Setting readSetting(DataInput in) throws IOException { // switch(in.readByte()) { // case 0: return new SettingBoolean().read(in); // case 1: return new SettingInt().read(in); // case 2: return new SettingFloat().read(in); // case 3: return new SettingString().read(in); // case 4: return new SettingList().read(in); // case 5: return new SettingBlock().read(in); // case 6: return new SettingItem().read(in); // default: return null; // } // } // // public static void write(Setting setting, DataOutput out) throws IOException { // if (setting == null) // return; // if (setting instanceof SettingBoolean) // out.write(0); // if (setting instanceof SettingInt) // out.write(1); // if (setting instanceof SettingFloat) // out.write(2); // if (setting instanceof SettingString) // out.write(3); // if (setting instanceof SettingList) // out.write(4); // if (setting instanceof SettingBlock) // out.write(5); // if (setting instanceof SettingItem) // out.write(6); // setting.write(out); // } // // /** // * Helper method for filters // */ // public static Setting[] toArray(Setting... settings) { // return settings; // } // // }
import org.mozilla.javascript.Function; import org.mozilla.javascript.NativeJavaArray; import scripting.core.ScriptException; import scripting.wrapper.settings.Setting;
package scripting.core.script; public final class FilterScript extends JSScript { /* function run(player, world, sel, options) */ private Function run; /* var inputs = Setting.toArray(...); */ private Setting[] inputs; public FilterScript(String name, String source) { super(name, source); } /** * We initialize our run and options functions here. * @throws ScriptException If no run function exists. */ @Override
// Path: scripting/core/ScriptException.java // public class ScriptException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public ScriptException(String message) { // super(message); // } // // public ScriptException(Throwable cause) { // super(cause); // } // } // // Path: scripting/wrapper/settings/Setting.java // public abstract class Setting { // // public String display; // // protected Setting() { } // // public Setting(String display) { // this.display = display; // } // // public abstract Object getValue(); // // protected void write(DataOutput out) throws IOException { // out.writeUTF(display); // } // // protected Setting read(DataInput in) throws IOException { // display = in.readUTF(); // return this; // } // // public static Setting readSetting(DataInput in) throws IOException { // switch(in.readByte()) { // case 0: return new SettingBoolean().read(in); // case 1: return new SettingInt().read(in); // case 2: return new SettingFloat().read(in); // case 3: return new SettingString().read(in); // case 4: return new SettingList().read(in); // case 5: return new SettingBlock().read(in); // case 6: return new SettingItem().read(in); // default: return null; // } // } // // public static void write(Setting setting, DataOutput out) throws IOException { // if (setting == null) // return; // if (setting instanceof SettingBoolean) // out.write(0); // if (setting instanceof SettingInt) // out.write(1); // if (setting instanceof SettingFloat) // out.write(2); // if (setting instanceof SettingString) // out.write(3); // if (setting instanceof SettingList) // out.write(4); // if (setting instanceof SettingBlock) // out.write(5); // if (setting instanceof SettingItem) // out.write(6); // setting.write(out); // } // // /** // * Helper method for filters // */ // public static Setting[] toArray(Setting... settings) { // return settings; // } // // } // Path: scripting/core/script/FilterScript.java import org.mozilla.javascript.Function; import org.mozilla.javascript.NativeJavaArray; import scripting.core.ScriptException; import scripting.wrapper.settings.Setting; package scripting.core.script; public final class FilterScript extends JSScript { /* function run(player, world, sel, options) */ private Function run; /* var inputs = Setting.toArray(...); */ private Setting[] inputs; public FilterScript(String name, String source) { super(name, source); } /** * We initialize our run and options functions here. * @throws ScriptException If no run function exists. */ @Override
public void postInit() throws ScriptException {
DavidGoldman/MinecraftScripting
scripting/wrapper/entity/ScriptDataWatcher.java
// Path: scripting/wrapper/ScriptItemStack.java // public class ScriptItemStack { // // public final ItemStack stack; // // private ScriptItemStack(ItemStack is) { // this.stack = is; // } // // public ScriptItemStack(ScriptItem item, int size, int damage) { // this.stack = new ItemStack((item == null) ? null : item.item, size, damage); // } // // public ScriptItemStack(ScriptBlock block, int size, int damage) { // this.stack = new ItemStack((block == null) ? null : block.block, size, damage); // } // // public ScriptItem getItem() { // return (stack.getItem() == null) ? null : ScriptItem.fromItem(stack.getItem()); // } // // public int getStackSize() { // return stack.stackSize; // } // // public void setStackSize(int size) { // stack.stackSize = size; // } // // public int getItemDamage() { // return stack.getItemDamage(); // } // // public void setItemDamage(int damage) { // stack.setItemDamage(damage); // } // // public boolean hasTagCompound() { // return stack.hasTagCompound(); // } // // public TAG_Compound getTagCompound() { // return (hasTagCompound()) ? new TAG_Compound(stack.getTagCompound()) : null; // } // // public void setTagCompound(TAG_Compound tag) { // stack.setTagCompound((tag == null) ? null : tag.tag); // } // // public TAG_Compound writeToTag() { // return new TAG_Compound(stack.writeToNBT(new NBTTagCompound())); // } // // public void readFromTag(TAG_Compound tag) { // stack.readFromNBT(tag.tag); // } // // public static ScriptItemStack fromItemStack(ItemStack stack) { // return (stack == null) ? null : new ScriptItemStack(stack); // } // // }
import net.minecraft.entity.DataWatcher; import scripting.wrapper.ScriptItemStack;
package scripting.wrapper.entity; public class ScriptDataWatcher { public final DataWatcher watcher; public ScriptDataWatcher(DataWatcher watcher) { this.watcher = watcher; } public void addObject(int id, Object obj) { watcher.addObject(id, obj); } public void addObjectByDataType(int id, int type) { watcher.addObjectByDataType(id, type); } public byte getWatchableObjectByte(int id) { return watcher.getWatchableObjectByte(id); } public short getWatchableObjectShort(int id) { return watcher.getWatchableObjectShort(id); } public int getWatchableObjectInt(int id) { return watcher.getWatchableObjectInt(id); } public float getWatchableObjectFloat(int id) { return watcher.getWatchableObjectFloat(id); } public String getWatchableObjectString(int id) { return watcher.getWatchableObjectString(id); }
// Path: scripting/wrapper/ScriptItemStack.java // public class ScriptItemStack { // // public final ItemStack stack; // // private ScriptItemStack(ItemStack is) { // this.stack = is; // } // // public ScriptItemStack(ScriptItem item, int size, int damage) { // this.stack = new ItemStack((item == null) ? null : item.item, size, damage); // } // // public ScriptItemStack(ScriptBlock block, int size, int damage) { // this.stack = new ItemStack((block == null) ? null : block.block, size, damage); // } // // public ScriptItem getItem() { // return (stack.getItem() == null) ? null : ScriptItem.fromItem(stack.getItem()); // } // // public int getStackSize() { // return stack.stackSize; // } // // public void setStackSize(int size) { // stack.stackSize = size; // } // // public int getItemDamage() { // return stack.getItemDamage(); // } // // public void setItemDamage(int damage) { // stack.setItemDamage(damage); // } // // public boolean hasTagCompound() { // return stack.hasTagCompound(); // } // // public TAG_Compound getTagCompound() { // return (hasTagCompound()) ? new TAG_Compound(stack.getTagCompound()) : null; // } // // public void setTagCompound(TAG_Compound tag) { // stack.setTagCompound((tag == null) ? null : tag.tag); // } // // public TAG_Compound writeToTag() { // return new TAG_Compound(stack.writeToNBT(new NBTTagCompound())); // } // // public void readFromTag(TAG_Compound tag) { // stack.readFromNBT(tag.tag); // } // // public static ScriptItemStack fromItemStack(ItemStack stack) { // return (stack == null) ? null : new ScriptItemStack(stack); // } // // } // Path: scripting/wrapper/entity/ScriptDataWatcher.java import net.minecraft.entity.DataWatcher; import scripting.wrapper.ScriptItemStack; package scripting.wrapper.entity; public class ScriptDataWatcher { public final DataWatcher watcher; public ScriptDataWatcher(DataWatcher watcher) { this.watcher = watcher; } public void addObject(int id, Object obj) { watcher.addObject(id, obj); } public void addObjectByDataType(int id, int type) { watcher.addObjectByDataType(id, type); } public byte getWatchableObjectByte(int id) { return watcher.getWatchableObjectByte(id); } public short getWatchableObjectShort(int id) { return watcher.getWatchableObjectShort(id); } public int getWatchableObjectInt(int id) { return watcher.getWatchableObjectInt(id); } public float getWatchableObjectFloat(int id) { return watcher.getWatchableObjectFloat(id); } public String getWatchableObjectString(int id) { return watcher.getWatchableObjectString(id); }
public ScriptItemStack getWatchableObjectItemStack(int id) {
cqjjjzr/Laplacian
Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avfilter6/AVFilterGraph.java
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avfilter6/Avfilter6Library.java // public interface avfilter_execute_func extends Callback { // int apply(AVFilterContext ctx, avfilter_action_func func, Pointer arg, IntByReference ret, int nb_jobs); // };
import com.sun.jna.Pointer; import com.sun.jna.Structure; import org.ffmpeg.avfilter6.Avfilter6Library.avfilter_execute_func; import java.util.Arrays; import java.util.List;
package org.ffmpeg.avfilter6; /** * <i>native declaration : libavfilter\avfilter.h:394</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVFilterGraph extends Structure { /** C type : const AVClass* */ public Pointer av_class; /** C type : AVFilterContext** */ public org.ffmpeg.avfilter6.AVFilterContext.ByReference[] filters; public int nb_filters; /** * < sws options to use for the auto-inserted scale filters<br> * C type : char* */ public Pointer scale_sws_opts; /** * < libavresample options to use for the auto-inserted resample filters<br> * C type : char* */ public Pointer resample_lavr_opts; public int thread_type; public int nb_threads; /** C type : AVFilterGraphInternal* */ public org.ffmpeg.avfilter6.AVFilterGraphInternal.ByReference internal; /** C type : void* */ public Pointer opaque; /** C type : avfilter_execute_func* */
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avfilter6/Avfilter6Library.java // public interface avfilter_execute_func extends Callback { // int apply(AVFilterContext ctx, avfilter_action_func func, Pointer arg, IntByReference ret, int nb_jobs); // }; // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avfilter6/AVFilterGraph.java import com.sun.jna.Pointer; import com.sun.jna.Structure; import org.ffmpeg.avfilter6.Avfilter6Library.avfilter_execute_func; import java.util.Arrays; import java.util.List; package org.ffmpeg.avfilter6; /** * <i>native declaration : libavfilter\avfilter.h:394</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVFilterGraph extends Structure { /** C type : const AVClass* */ public Pointer av_class; /** C type : AVFilterContext** */ public org.ffmpeg.avfilter6.AVFilterContext.ByReference[] filters; public int nb_filters; /** * < sws options to use for the auto-inserted scale filters<br> * C type : char* */ public Pointer scale_sws_opts; /** * < libavresample options to use for the auto-inserted resample filters<br> * C type : char* */ public Pointer resample_lavr_opts; public int thread_type; public int nb_threads; /** C type : AVFilterGraphInternal* */ public org.ffmpeg.avfilter6.AVFilterGraphInternal.ByReference internal; /** C type : void* */ public Pointer opaque; /** C type : avfilter_execute_func* */
public avfilter_execute_func execute;
cqjjjzr/Laplacian
Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/Avutil55Library.java
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class AVBPrint extends PointerType { // public AVBPrint(Pointer address) { // super(address); // } // public AVBPrint() { // super(); // } // }; // // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class FILE extends PointerType { // public FILE(Pointer address) { // super(address); // } // public FILE() { // super(); // } // };
import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.sun.jna.*; import com.sun.jna.ptr.*; import org.ffmpeg.avformat57.Avformat57Library.AVBPrint; import org.ffmpeg.avformat57.Avformat57Library.FILE; import java.nio.*;
/** * Original signature : <code>int av_log_get_flags()</code><br> * <i>native declaration : libavutil\log.h:154</i> */ int av_log_get_flags(); /** * Return x default pointer in case p is NULL.<br> * Original signature : <code>void* av_x_if_null(const void*, const void*)</code><br> * <i>native declaration : libavutil\avutil.h:6</i> */ Pointer av_x_if_null(Pointer p, Pointer x); /** * Compute the length of an integer list.<br> * @param elsize size in bytes of each list element (only 1, 2, 4 or 8)<br> * @param term list terminator (usually 0 or -1)<br> * @param list pointer to the list<br> * @return length of the list, in elements, not counting the terminator<br> * Original signature : <code>int av_int_list_length_for_size(unsigned, const void*, uint64_t)</code><br> * <i>native declaration : libavutil\avutil.h:15</i> */ int av_int_list_length_for_size(int elsize, Pointer list, long term); /** * Open a file using a UTF-8 filename.<br> * The API of this function matches POSIX fopen(), errors are returned through<br> * errno.<br> * Original signature : <code>FILE* av_fopen_utf8(const char*, const char*)</code><br> * <i>native declaration : libavutil\avutil.h:22</i><br> * @deprecated use the safer methods {@link #av_fopen_utf8(String, String)} and {@link #av_fopen_utf8(Pointer, Pointer)} instead */ @Deprecated
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class AVBPrint extends PointerType { // public AVBPrint(Pointer address) { // super(address); // } // public AVBPrint() { // super(); // } // }; // // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class FILE extends PointerType { // public FILE(Pointer address) { // super(address); // } // public FILE() { // super(); // } // }; // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/Avutil55Library.java import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.sun.jna.*; import com.sun.jna.ptr.*; import org.ffmpeg.avformat57.Avformat57Library.AVBPrint; import org.ffmpeg.avformat57.Avformat57Library.FILE; import java.nio.*; /** * Original signature : <code>int av_log_get_flags()</code><br> * <i>native declaration : libavutil\log.h:154</i> */ int av_log_get_flags(); /** * Return x default pointer in case p is NULL.<br> * Original signature : <code>void* av_x_if_null(const void*, const void*)</code><br> * <i>native declaration : libavutil\avutil.h:6</i> */ Pointer av_x_if_null(Pointer p, Pointer x); /** * Compute the length of an integer list.<br> * @param elsize size in bytes of each list element (only 1, 2, 4 or 8)<br> * @param term list terminator (usually 0 or -1)<br> * @param list pointer to the list<br> * @return length of the list, in elements, not counting the terminator<br> * Original signature : <code>int av_int_list_length_for_size(unsigned, const void*, uint64_t)</code><br> * <i>native declaration : libavutil\avutil.h:15</i> */ int av_int_list_length_for_size(int elsize, Pointer list, long term); /** * Open a file using a UTF-8 filename.<br> * The API of this function matches POSIX fopen(), errors are returned through<br> * errno.<br> * Original signature : <code>FILE* av_fopen_utf8(const char*, const char*)</code><br> * <i>native declaration : libavutil\avutil.h:22</i><br> * @deprecated use the safer methods {@link #av_fopen_utf8(String, String)} and {@link #av_fopen_utf8(Pointer, Pointer)} instead */ @Deprecated
FILE av_fopen_utf8(Pointer path, Pointer mode);
cqjjjzr/Laplacian
Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/Avutil55Library.java
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class AVBPrint extends PointerType { // public AVBPrint(Pointer address) { // super(address); // } // public AVBPrint() { // super(); // } // }; // // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class FILE extends PointerType { // public FILE(Pointer address) { // super(address); // } // public FILE() { // super(); // } // };
import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.sun.jna.*; import com.sun.jna.ptr.*; import org.ffmpeg.avformat57.Avformat57Library.AVBPrint; import org.ffmpeg.avformat57.Avformat57Library.FILE; import java.nio.*;
* @return 0 on success, AVERROR(EINVAL) if the parsing fails.<br> * Original signature : <code>int av_get_extended_channel_layout(const char*, uint64_t*, int*)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:42</i> */ int av_get_extended_channel_layout(String name, LongBuffer channel_layout, IntBuffer nb_channels); /** * Return a description of a channel layout.<br> * If nb_channels is <= 0, it is guessed from the channel_layout.<br> * @param buf put here the string containing the channel layout<br> * @param buf_size size in bytes of the buffer<br> * Original signature : <code>void av_get_channel_layout_string(char*, int, int, uint64_t)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:50</i><br> * @deprecated use the safer methods {@link #av_get_channel_layout_string(ByteBuffer, int, int, long)} and {@link #av_get_channel_layout_string(Pointer, int, int, long)} instead */ @Deprecated void av_get_channel_layout_string(Pointer buf, int buf_size, int nb_channels, long channel_layout); /** * Return a description of a channel layout.<br> * If nb_channels is <= 0, it is guessed from the channel_layout.<br> * @param buf put here the string containing the channel layout<br> * @param buf_size size in bytes of the buffer<br> * Original signature : <code>void av_get_channel_layout_string(char*, int, int, uint64_t)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:50</i> */ void av_get_channel_layout_string(ByteBuffer buf, int buf_size, int nb_channels, long channel_layout); /** * Append a description of a channel layout to a bprint buffer.<br> * Original signature : <code>void av_bprint_channel_layout(AVBPrint*, int, uint64_t)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:56</i> */
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class AVBPrint extends PointerType { // public AVBPrint(Pointer address) { // super(address); // } // public AVBPrint() { // super(); // } // }; // // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avformat57/Avformat57Library.java // public static class FILE extends PointerType { // public FILE(Pointer address) { // super(address); // } // public FILE() { // super(); // } // }; // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/Avutil55Library.java import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.sun.jna.*; import com.sun.jna.ptr.*; import org.ffmpeg.avformat57.Avformat57Library.AVBPrint; import org.ffmpeg.avformat57.Avformat57Library.FILE; import java.nio.*; * @return 0 on success, AVERROR(EINVAL) if the parsing fails.<br> * Original signature : <code>int av_get_extended_channel_layout(const char*, uint64_t*, int*)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:42</i> */ int av_get_extended_channel_layout(String name, LongBuffer channel_layout, IntBuffer nb_channels); /** * Return a description of a channel layout.<br> * If nb_channels is <= 0, it is guessed from the channel_layout.<br> * @param buf put here the string containing the channel layout<br> * @param buf_size size in bytes of the buffer<br> * Original signature : <code>void av_get_channel_layout_string(char*, int, int, uint64_t)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:50</i><br> * @deprecated use the safer methods {@link #av_get_channel_layout_string(ByteBuffer, int, int, long)} and {@link #av_get_channel_layout_string(Pointer, int, int, long)} instead */ @Deprecated void av_get_channel_layout_string(Pointer buf, int buf_size, int nb_channels, long channel_layout); /** * Return a description of a channel layout.<br> * If nb_channels is <= 0, it is guessed from the channel_layout.<br> * @param buf put here the string containing the channel layout<br> * @param buf_size size in bytes of the buffer<br> * Original signature : <code>void av_get_channel_layout_string(char*, int, int, uint64_t)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:50</i> */ void av_get_channel_layout_string(ByteBuffer buf, int buf_size, int nb_channels, long channel_layout); /** * Append a description of a channel layout to a bprint buffer.<br> * Original signature : <code>void av_bprint_channel_layout(AVBPrint*, int, uint64_t)</code><br> * <i>native declaration : .\libavutil\channel_layout.h:56</i> */
void av_bprint_channel_layout(AVBPrint bp, int nb_channels, long channel_layout);
cqjjjzr/Laplacian
Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avcodec57/AVCodecParameters.java
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/AVRational.java // public class AVRational extends Structure { // /** < Numerator */ // public int num; // /** < Denominator */ // public int den; // public AVRational() { // super(); // } // protected List<String> getFieldOrder() { // return Arrays.asList("num", "den"); // } // /** // * @param num < Numerator<br> // * @param den < Denominator // */ // public AVRational(int num, int den) { // super(); // this.num = num; // this.den = den; // } // public AVRational(Pointer peer) { // super(peer); // } // public static class ByReference extends AVRational implements Structure.ByReference { // // }; // public static class ByValue extends AVRational implements Structure.ByValue { // // }; // }
import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; import org.ffmpeg.avutil55.AVRational;
package org.ffmpeg.avcodec57; /** * <i>native declaration : .\libavcodec\avcodec.h:1173</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVCodecParameters extends Structure { /** * @see org.ffmpeg.avutil55.Avutil55Library#AVMediaType<br> * C type : AVMediaType */ public int codec_type; /** * @see AVCodecID<br> * C type : AVCodecID */ public int codec_id; public int codec_tag; /** C type : uint8_t* */ public Pointer extradata; public int extradata_size; public int format; public long bit_rate; public int bits_per_coded_sample; public int bits_per_raw_sample; public int profile; public int level; public int width; public int height; /** C type : AVRational */
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/AVRational.java // public class AVRational extends Structure { // /** < Numerator */ // public int num; // /** < Denominator */ // public int den; // public AVRational() { // super(); // } // protected List<String> getFieldOrder() { // return Arrays.asList("num", "den"); // } // /** // * @param num < Numerator<br> // * @param den < Denominator // */ // public AVRational(int num, int den) { // super(); // this.num = num; // this.den = den; // } // public AVRational(Pointer peer) { // super(peer); // } // public static class ByReference extends AVRational implements Structure.ByReference { // // }; // public static class ByValue extends AVRational implements Structure.ByValue { // // }; // } // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avcodec57/AVCodecParameters.java import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; import org.ffmpeg.avutil55.AVRational; package org.ffmpeg.avcodec57; /** * <i>native declaration : .\libavcodec\avcodec.h:1173</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVCodecParameters extends Structure { /** * @see org.ffmpeg.avutil55.Avutil55Library#AVMediaType<br> * C type : AVMediaType */ public int codec_type; /** * @see AVCodecID<br> * C type : AVCodecID */ public int codec_id; public int codec_tag; /** C type : uint8_t* */ public Pointer extradata; public int extradata_size; public int format; public long bit_rate; public int bits_per_coded_sample; public int bits_per_raw_sample; public int profile; public int level; public int width; public int height; /** C type : AVRational */
public AVRational sample_aspect_ratio;
cqjjjzr/Laplacian
Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avdevice57/AVDeviceCapabilitiesQuery.java
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/AVRational.java // public class AVRational extends Structure { // /** < Numerator */ // public int num; // /** < Denominator */ // public int den; // public AVRational() { // super(); // } // protected List<String> getFieldOrder() { // return Arrays.asList("num", "den"); // } // /** // * @param num < Numerator<br> // * @param den < Denominator // */ // public AVRational(int num, int den) { // super(); // this.num = num; // this.den = den; // } // public AVRational(Pointer peer) { // super(peer); // } // public static class ByReference extends AVRational implements Structure.ByReference { // // }; // public static class ByValue extends AVRational implements Structure.ByValue { // // }; // }
import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.PointerByReference; import org.ffmpeg.avutil55.AVRational; import java.util.Arrays; import java.util.List;
package org.ffmpeg.avdevice57; /** * <i>native declaration : libavdevice\avdevice.h:134</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVDeviceCapabilitiesQuery extends Structure { /** C type : const AVClass* */ public Pointer av_class; /** C type : AVFormatContext* */ public org.ffmpeg.avformat57.AVFormatContext.ByReference device_context; /** * @see org.ffmpeg.avcodec57.Avcodec57Library#AVCodecID<br> * C type : AVCodecID */ public int codec; /** * @see org.ffmpeg.avutil55.Avutil55Library#AVSampleFormat<br> * C type : AVSampleFormat */ public int sample_format; /** * @see org.ffmpeg.avutil55.Avutil55Library#AVPixelFormat<br> * C type : AVPixelFormat */ public int pixel_format; public int sample_rate; public int channels; public long channel_layout; public int window_width; public int window_height; public int frame_width; public int frame_height; /** C type : AVRational */
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/AVRational.java // public class AVRational extends Structure { // /** < Numerator */ // public int num; // /** < Denominator */ // public int den; // public AVRational() { // super(); // } // protected List<String> getFieldOrder() { // return Arrays.asList("num", "den"); // } // /** // * @param num < Numerator<br> // * @param den < Denominator // */ // public AVRational(int num, int den) { // super(); // this.num = num; // this.den = den; // } // public AVRational(Pointer peer) { // super(peer); // } // public static class ByReference extends AVRational implements Structure.ByReference { // // }; // public static class ByValue extends AVRational implements Structure.ByValue { // // }; // } // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avdevice57/AVDeviceCapabilitiesQuery.java import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.PointerByReference; import org.ffmpeg.avutil55.AVRational; import java.util.Arrays; import java.util.List; package org.ffmpeg.avdevice57; /** * <i>native declaration : libavdevice\avdevice.h:134</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVDeviceCapabilitiesQuery extends Structure { /** C type : const AVClass* */ public Pointer av_class; /** C type : AVFormatContext* */ public org.ffmpeg.avformat57.AVFormatContext.ByReference device_context; /** * @see org.ffmpeg.avcodec57.Avcodec57Library#AVCodecID<br> * C type : AVCodecID */ public int codec; /** * @see org.ffmpeg.avutil55.Avutil55Library#AVSampleFormat<br> * C type : AVSampleFormat */ public int sample_format; /** * @see org.ffmpeg.avutil55.Avutil55Library#AVPixelFormat<br> * C type : AVPixelFormat */ public int pixel_format; public int sample_rate; public int channels; public long channel_layout; public int window_width; public int window_height; public int frame_width; public int frame_height; /** C type : AVRational */
public AVRational fps;
cqjjjzr/Laplacian
Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avfilter6/AVBufferSrcParameters.java
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/AVRational.java // public class AVRational extends Structure { // /** < Numerator */ // public int num; // /** < Denominator */ // public int den; // public AVRational() { // super(); // } // protected List<String> getFieldOrder() { // return Arrays.asList("num", "den"); // } // /** // * @param num < Numerator<br> // * @param den < Denominator // */ // public AVRational(int num, int den) { // super(); // this.num = num; // this.den = den; // } // public AVRational(Pointer peer) { // super(peer); // } // public static class ByReference extends AVRational implements Structure.ByReference { // // }; // public static class ByValue extends AVRational implements Structure.ByValue { // // }; // }
import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; import org.ffmpeg.avutil55.AVRational;
package org.ffmpeg.avfilter6; /** * <i>native declaration : libavfilter\buffersrc.h:34</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVBufferSrcParameters extends Structure { public int format; /** C type : AVRational */
// Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avutil55/AVRational.java // public class AVRational extends Structure { // /** < Numerator */ // public int num; // /** < Denominator */ // public int den; // public AVRational() { // super(); // } // protected List<String> getFieldOrder() { // return Arrays.asList("num", "den"); // } // /** // * @param num < Numerator<br> // * @param den < Denominator // */ // public AVRational(int num, int den) { // super(); // this.num = num; // this.den = den; // } // public AVRational(Pointer peer) { // super(peer); // } // public static class ByReference extends AVRational implements Structure.ByReference { // // }; // public static class ByValue extends AVRational implements Structure.ByValue { // // }; // } // Path: Laplacian.Essential.Desktop/src/main/java/org/ffmpeg/avfilter6/AVBufferSrcParameters.java import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; import org.ffmpeg.avutil55.AVRational; package org.ffmpeg.avfilter6; /** * <i>native declaration : libavfilter\buffersrc.h:34</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class AVBufferSrcParameters extends Structure { public int format; /** C type : AVRational */
public AVRational time_base;
cernekee/ics-openconnect
app/src/main/java/app/openconnect/fragments/CommonMenu.java
// Path: app/src/main/java/app/openconnect/FragActivity.java // public class FragActivity extends Activity { // // public static final String TAG = "OpenConnect"; // // public static final String EXTRA_FRAGMENT_NAME = "app.openconnect.fragment_name"; // // public static final String FRAGMENT_PREFIX = "app.openconnect.fragments."; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if(savedInstanceState == null) { // try { // String fragName = getIntent().getStringExtra(EXTRA_FRAGMENT_NAME); // Fragment frag = (Fragment)Class.forName(FRAGMENT_PREFIX + fragName).newInstance(); // getFragmentManager().beginTransaction().add(android.R.id.content, frag).commit(); // } catch (Exception e) { // Log.e(TAG, "unable to create fragment", e); // finish(); // } // } // } // // }
import android.view.Menu; import android.view.MenuItem; import app.openconnect.FragActivity; import app.openconnect.R; import org.acra.ACRA; import org.acra.ACRAConfiguration; import org.acra.ErrorReporter; import android.content.Context; import android.content.Intent;
/* * Copyright (c) 2014, Kevin Cernekee * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.fragments; public class CommonMenu { private static final int MENU_SETTINGS = 15; private static final int MENU_SECURID = 20; private static final int MENU_REPORT_PROBLEM = 25; private static final int MENU_ABOUT = 30; private Context mContext; public CommonMenu(Context ctx, Menu menu, boolean isConnected) { mContext = ctx; menu.add(Menu.NONE, MENU_SETTINGS, Menu.NONE, R.string.generalsettings) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); menu.add(Menu.NONE, MENU_SECURID, Menu.NONE, R.string.securid_info) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); menu.add(Menu.NONE, MENU_REPORT_PROBLEM, Menu.NONE, R.string.report_problem) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); menu.add(Menu.NONE, MENU_ABOUT, Menu.NONE, R.string.about_openconnect) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); } private boolean startFragActivity(String fragName) {
// Path: app/src/main/java/app/openconnect/FragActivity.java // public class FragActivity extends Activity { // // public static final String TAG = "OpenConnect"; // // public static final String EXTRA_FRAGMENT_NAME = "app.openconnect.fragment_name"; // // public static final String FRAGMENT_PREFIX = "app.openconnect.fragments."; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if(savedInstanceState == null) { // try { // String fragName = getIntent().getStringExtra(EXTRA_FRAGMENT_NAME); // Fragment frag = (Fragment)Class.forName(FRAGMENT_PREFIX + fragName).newInstance(); // getFragmentManager().beginTransaction().add(android.R.id.content, frag).commit(); // } catch (Exception e) { // Log.e(TAG, "unable to create fragment", e); // finish(); // } // } // } // // } // Path: app/src/main/java/app/openconnect/fragments/CommonMenu.java import android.view.Menu; import android.view.MenuItem; import app.openconnect.FragActivity; import app.openconnect.R; import org.acra.ACRA; import org.acra.ACRAConfiguration; import org.acra.ErrorReporter; import android.content.Context; import android.content.Intent; /* * Copyright (c) 2014, Kevin Cernekee * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.fragments; public class CommonMenu { private static final int MENU_SETTINGS = 15; private static final int MENU_SECURID = 20; private static final int MENU_REPORT_PROBLEM = 25; private static final int MENU_ABOUT = 30; private Context mContext; public CommonMenu(Context ctx, Menu menu, boolean isConnected) { mContext = ctx; menu.add(Menu.NONE, MENU_SETTINGS, Menu.NONE, R.string.generalsettings) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); menu.add(Menu.NONE, MENU_SECURID, Menu.NONE, R.string.securid_info) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); menu.add(Menu.NONE, MENU_REPORT_PROBLEM, Menu.NONE, R.string.report_problem) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); menu.add(Menu.NONE, MENU_ABOUT, Menu.NONE, R.string.about_openconnect) .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); } private boolean startFragActivity(String fragName) {
Intent intent = new Intent(mContext, FragActivity.class);
cernekee/ics-openconnect
app/src/main/java/app/openconnect/core/ProfileManager.java
// Path: app/src/main/java/app/openconnect/VpnProfile.java // public class VpnProfile implements Comparable<VpnProfile> { // public static final String INLINE_TAG = "[[INLINE]]"; // // public SharedPreferences mPrefs; // public String mName; // // private UUID mUuid; // // private void loadPrefs(SharedPreferences prefs) { // mPrefs = prefs; // // String uuid = mPrefs.getString("profile_uuid", null); // if (uuid != null) { // mUuid = UUID.fromString(uuid); // } // mName = mPrefs.getString("profile_name", null); // } // // public VpnProfile(SharedPreferences prefs, String uuid, String name) { // prefs.edit() // .putString("profile_uuid", uuid) // .putString("profile_name", name) // .commit(); // loadPrefs(prefs); // } // // public VpnProfile(SharedPreferences prefs) { // loadPrefs(prefs); // } // // public VpnProfile(String name, String uuid) { // mUuid = UUID.fromString(uuid); // mName = name; // } // // public boolean isValid() { // if (mName == null || mUuid == null) { // return false; // } // return true; // } // // public UUID getUUID() { // return mUuid; // // } // // public String getName() { // return mName; // } // // // Used by the Array Adapter // @Override // public String toString() { // return mName; // } // // public String getUUIDString() { // return mUuid.toString(); // } // // @Override // public int compareTo(VpnProfile arg0) { // Locale def = Locale.getDefault(); // return getName().toUpperCase(def).compareTo(arg0.getName().toUpperCase(def)); // } // }
import java.util.UUID; import app.openconnect.VpnProfile; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Collection; import java.util.HashMap; import java.util.Locale;
/* * Copyright (c) 2013, Kevin Cernekee * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.core; public class ProfileManager { public static final String TAG = "OpenConnect"; public static String fileSelectKeys[] = { "ca_certificate", "user_certificate", "private_key", "custom_csd_wrapper" }; private static final String PROFILE_PFX = "profile-";
// Path: app/src/main/java/app/openconnect/VpnProfile.java // public class VpnProfile implements Comparable<VpnProfile> { // public static final String INLINE_TAG = "[[INLINE]]"; // // public SharedPreferences mPrefs; // public String mName; // // private UUID mUuid; // // private void loadPrefs(SharedPreferences prefs) { // mPrefs = prefs; // // String uuid = mPrefs.getString("profile_uuid", null); // if (uuid != null) { // mUuid = UUID.fromString(uuid); // } // mName = mPrefs.getString("profile_name", null); // } // // public VpnProfile(SharedPreferences prefs, String uuid, String name) { // prefs.edit() // .putString("profile_uuid", uuid) // .putString("profile_name", name) // .commit(); // loadPrefs(prefs); // } // // public VpnProfile(SharedPreferences prefs) { // loadPrefs(prefs); // } // // public VpnProfile(String name, String uuid) { // mUuid = UUID.fromString(uuid); // mName = name; // } // // public boolean isValid() { // if (mName == null || mUuid == null) { // return false; // } // return true; // } // // public UUID getUUID() { // return mUuid; // // } // // public String getName() { // return mName; // } // // // Used by the Array Adapter // @Override // public String toString() { // return mName; // } // // public String getUUIDString() { // return mUuid.toString(); // } // // @Override // public int compareTo(VpnProfile arg0) { // Locale def = Locale.getDefault(); // return getName().toUpperCase(def).compareTo(arg0.getName().toUpperCase(def)); // } // } // Path: app/src/main/java/app/openconnect/core/ProfileManager.java import java.util.UUID; import app.openconnect.VpnProfile; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Collection; import java.util.HashMap; import java.util.Locale; /* * Copyright (c) 2013, Kevin Cernekee * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.core; public class ProfileManager { public static final String TAG = "OpenConnect"; public static String fileSelectKeys[] = { "ca_certificate", "user_certificate", "private_key", "custom_csd_wrapper" }; private static final String PROFILE_PFX = "profile-";
private static HashMap<String,VpnProfile> mProfiles;
cernekee/ics-openconnect
app/src/main/java/app/openconnect/core/X509Utils.java
// Path: app/src/main/java/app/openconnect/VpnProfile.java // public class VpnProfile implements Comparable<VpnProfile> { // public static final String INLINE_TAG = "[[INLINE]]"; // // public SharedPreferences mPrefs; // public String mName; // // private UUID mUuid; // // private void loadPrefs(SharedPreferences prefs) { // mPrefs = prefs; // // String uuid = mPrefs.getString("profile_uuid", null); // if (uuid != null) { // mUuid = UUID.fromString(uuid); // } // mName = mPrefs.getString("profile_name", null); // } // // public VpnProfile(SharedPreferences prefs, String uuid, String name) { // prefs.edit() // .putString("profile_uuid", uuid) // .putString("profile_name", name) // .commit(); // loadPrefs(prefs); // } // // public VpnProfile(SharedPreferences prefs) { // loadPrefs(prefs); // } // // public VpnProfile(String name, String uuid) { // mUuid = UUID.fromString(uuid); // mName = name; // } // // public boolean isValid() { // if (mName == null || mUuid == null) { // return false; // } // return true; // } // // public UUID getUUID() { // return mUuid; // // } // // public String getName() { // return mName; // } // // // Used by the Array Adapter // @Override // public String toString() { // return mName; // } // // public String getUUIDString() { // return mUuid.toString(); // } // // @Override // public int compareTo(VpnProfile arg0) { // Locale def = Locale.getDefault(); // return getName().toUpperCase(def).compareTo(arg0.getName().toUpperCase(def)); // } // }
import org.spongycastle.util.io.pem.PemObject; import org.spongycastle.util.io.pem.PemReader; import javax.security.auth.x500.X500Principal; import java.io.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import android.content.Context; import android.text.TextUtils; import app.openconnect.R; import app.openconnect.VpnProfile;
/* * Adapted from OpenVPN for Android * Copyright (c) 2012-2013, Arne Schwabe * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.core; public class X509Utils { public static Certificate getCertificateFromFile(String certfilename) throws FileNotFoundException, CertificateException { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); InputStream inStream;
// Path: app/src/main/java/app/openconnect/VpnProfile.java // public class VpnProfile implements Comparable<VpnProfile> { // public static final String INLINE_TAG = "[[INLINE]]"; // // public SharedPreferences mPrefs; // public String mName; // // private UUID mUuid; // // private void loadPrefs(SharedPreferences prefs) { // mPrefs = prefs; // // String uuid = mPrefs.getString("profile_uuid", null); // if (uuid != null) { // mUuid = UUID.fromString(uuid); // } // mName = mPrefs.getString("profile_name", null); // } // // public VpnProfile(SharedPreferences prefs, String uuid, String name) { // prefs.edit() // .putString("profile_uuid", uuid) // .putString("profile_name", name) // .commit(); // loadPrefs(prefs); // } // // public VpnProfile(SharedPreferences prefs) { // loadPrefs(prefs); // } // // public VpnProfile(String name, String uuid) { // mUuid = UUID.fromString(uuid); // mName = name; // } // // public boolean isValid() { // if (mName == null || mUuid == null) { // return false; // } // return true; // } // // public UUID getUUID() { // return mUuid; // // } // // public String getName() { // return mName; // } // // // Used by the Array Adapter // @Override // public String toString() { // return mName; // } // // public String getUUIDString() { // return mUuid.toString(); // } // // @Override // public int compareTo(VpnProfile arg0) { // Locale def = Locale.getDefault(); // return getName().toUpperCase(def).compareTo(arg0.getName().toUpperCase(def)); // } // } // Path: app/src/main/java/app/openconnect/core/X509Utils.java import org.spongycastle.util.io.pem.PemObject; import org.spongycastle.util.io.pem.PemReader; import javax.security.auth.x500.X500Principal; import java.io.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import android.content.Context; import android.text.TextUtils; import app.openconnect.R; import app.openconnect.VpnProfile; /* * Adapted from OpenVPN for Android * Copyright (c) 2012-2013, Arne Schwabe * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.core; public class X509Utils { public static Certificate getCertificateFromFile(String certfilename) throws FileNotFoundException, CertificateException { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); InputStream inStream;
if(certfilename.startsWith(VpnProfile.INLINE_TAG)) {
cernekee/ics-openconnect
app/src/main/java/app/openconnect/fragments/SendDumpFragment.java
// Path: app/src/main/java/app/openconnect/core/OpenVPN.java // public class OpenVPN { // // public static void logError(String msg) { // } // // public static void logError(int ressourceId, Object... args) { // } // // public static void logInfo(String message) { // } // // public static void logInfo(int ressourceId, Object... args) { // } // // public enum ConnectionStatus { // LEVEL_CONNECTED, // LEVEL_VPNPAUSED, // LEVEL_CONNECTING_SERVER_REPLIED, // LEVEL_CONNECTING_NO_SERVER_REPLY_YET, // LEVEL_NONETWORK, // LEVEL_NOTCONNECTED, // LEVEL_AUTH_FAILED, // LEVEL_WAITING_FOR_USER_INPUT, // UNKNOWN_LEVEL // } // }
import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import app.openconnect.R; import app.openconnect.core.OpenVPN; import java.io.File; import java.util.ArrayList; import android.app.Fragment; import android.content.Context;
return v; } public void emailMiniDumps() { //need to "send multiple" to get more than one attachment final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE); emailIntent.setType("*/*"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"Kevin Cernekee <cernekee@gmail.com>"}); String version; String name="ics-openconnect"; try { PackageInfo packageinfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version = packageinfo.versionName; name = packageinfo.applicationInfo.name; } catch (NameNotFoundException e) { version = "error fetching version"; } emailIntent.putExtra(Intent.EXTRA_SUBJECT, String.format("%s %s Minidump",name,version)); emailIntent.putExtra(Intent.EXTRA_TEXT, "Please describe the issue you have experienced"); ArrayList<Uri> uris = new ArrayList<Uri>(); File ldump = getLastestDump(getActivity()); if(ldump==null) {
// Path: app/src/main/java/app/openconnect/core/OpenVPN.java // public class OpenVPN { // // public static void logError(String msg) { // } // // public static void logError(int ressourceId, Object... args) { // } // // public static void logInfo(String message) { // } // // public static void logInfo(int ressourceId, Object... args) { // } // // public enum ConnectionStatus { // LEVEL_CONNECTED, // LEVEL_VPNPAUSED, // LEVEL_CONNECTING_SERVER_REPLIED, // LEVEL_CONNECTING_NO_SERVER_REPLY_YET, // LEVEL_NONETWORK, // LEVEL_NOTCONNECTED, // LEVEL_AUTH_FAILED, // LEVEL_WAITING_FOR_USER_INPUT, // UNKNOWN_LEVEL // } // } // Path: app/src/main/java/app/openconnect/fragments/SendDumpFragment.java import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import app.openconnect.R; import app.openconnect.core.OpenVPN; import java.io.File; import java.util.ArrayList; import android.app.Fragment; import android.content.Context; return v; } public void emailMiniDumps() { //need to "send multiple" to get more than one attachment final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE); emailIntent.setType("*/*"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"Kevin Cernekee <cernekee@gmail.com>"}); String version; String name="ics-openconnect"; try { PackageInfo packageinfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version = packageinfo.versionName; name = packageinfo.applicationInfo.name; } catch (NameNotFoundException e) { version = "error fetching version"; } emailIntent.putExtra(Intent.EXTRA_SUBJECT, String.format("%s %s Minidump",name,version)); emailIntent.putExtra(Intent.EXTRA_TEXT, "Please describe the issue you have experienced"); ArrayList<Uri> uris = new ArrayList<Uri>(); File ldump = getLastestDump(getActivity()); if(ldump==null) {
OpenVPN.logError("No Minidump found!");
cernekee/ics-openconnect
app/src/main/java/app/openconnect/core/VPNConnector.java
// Path: app/src/main/java/app/openconnect/core/OpenVpnService.java // public class LocalBinder extends Binder { // public OpenVpnService getService() { // // Return this instance of LocalService so clients can call public methods // return OpenVpnService.this; // } // }
import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Handler; import android.os.IBinder; import android.util.Log; import app.openconnect.R; import app.openconnect.core.OpenVpnService.LocalBinder; import org.infradead.libopenconnect.LibOpenConnect.VPNStats; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent;
mStatsHandler.removeCallbacks(mStatsRunnable); mStatsHandler = null; } } public void unbind() { stop(); if (service != null) { service.updateActivityRefcount(mIsActivity ? -1 : 0); } mContext.unbindService(mConnection); } public String getByteCountSummary() { if (!statsValid) { return ""; } return mContext.getString(R.string.statusline_bytecount, OpenVpnService.humanReadableByteCount(newStats.rxBytes, false), OpenVpnService.humanReadableByteCount(deltaStats.rxBytes, true), OpenVpnService.humanReadableByteCount(newStats.txBytes, false), OpenVpnService.humanReadableByteCount(deltaStats.txBytes, true)); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder serviceBinder) { // We've bound to LocalService, cast the IBinder and get // LocalService instance
// Path: app/src/main/java/app/openconnect/core/OpenVpnService.java // public class LocalBinder extends Binder { // public OpenVpnService getService() { // // Return this instance of LocalService so clients can call public methods // return OpenVpnService.this; // } // } // Path: app/src/main/java/app/openconnect/core/VPNConnector.java import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Handler; import android.os.IBinder; import android.util.Log; import app.openconnect.R; import app.openconnect.core.OpenVpnService.LocalBinder; import org.infradead.libopenconnect.LibOpenConnect.VPNStats; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; mStatsHandler.removeCallbacks(mStatsRunnable); mStatsHandler = null; } } public void unbind() { stop(); if (service != null) { service.updateActivityRefcount(mIsActivity ? -1 : 0); } mContext.unbindService(mConnection); } public String getByteCountSummary() { if (!statsValid) { return ""; } return mContext.getString(R.string.statusline_bytecount, OpenVpnService.humanReadableByteCount(newStats.rxBytes, false), OpenVpnService.humanReadableByteCount(deltaStats.rxBytes, true), OpenVpnService.humanReadableByteCount(newStats.txBytes, false), OpenVpnService.humanReadableByteCount(deltaStats.txBytes, true)); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder serviceBinder) { // We've bound to LocalService, cast the IBinder and get // LocalService instance
LocalBinder binder = (LocalBinder) serviceBinder;
cernekee/ics-openconnect
app/src/main/java/app/openconnect/fragments/FeedbackFragment.java
// Path: app/src/main/java/app/openconnect/FragActivity.java // public class FragActivity extends Activity { // // public static final String TAG = "OpenConnect"; // // public static final String EXTRA_FRAGMENT_NAME = "app.openconnect.fragment_name"; // // public static final String FRAGMENT_PREFIX = "app.openconnect.fragments."; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if(savedInstanceState == null) { // try { // String fragName = getIntent().getStringExtra(EXTRA_FRAGMENT_NAME); // Fragment frag = (Fragment)Class.forName(FRAGMENT_PREFIX + fragName).newInstance(); // getFragmentManager().beginTransaction().add(android.R.id.content, frag).commit(); // } catch (Exception e) { // Log.e(TAG, "unable to create fragment", e); // finish(); // } // } // } // // }
import java.util.Calendar; import android.app.Activity; import android.app.Fragment; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import app.openconnect.FragActivity; import app.openconnect.R;
/* * Copyright (c) 2014, Kevin Cernekee * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.fragments; public class FeedbackFragment extends Fragment { public static final String TAG = "OpenConnect"; public static final String marketURI = "market://details?id=app.openconnect"; /* ask for feedback exactly once, after NAGDAYS && NAGUSES */ private static final int nagDays = 14; private static final long nagUses = 10; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.feedback, container, false); final Activity act = getActivity(); Button b; /* * Adapted from: * http://www.techrepublic.com/blog/software-engineer/get-more-positive-ratings-for-your-app-in-google-play/1111/ */ b = (Button)v.findViewById(R.id.i_love_it); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { recordNag(act); Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(marketURI)); try { startActivity(i); } catch (ActivityNotFoundException e) { /* not all devices have a handler for market:// URIs registered */ } act.finish(); } }); b = (Button)v.findViewById(R.id.needs_work); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { recordNag(act); String ver = "???"; try { PackageInfo packageinfo = act.getPackageManager().getPackageInfo(act.getPackageName(), 0); ver = packageinfo.versionName; } catch (NameNotFoundException e) { } Intent i = new Intent(android.content.Intent.ACTION_SEND); i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"cernekee+oc@gmail.com"}); i.putExtra(android.content.Intent.EXTRA_SUBJECT, "ics-openconnect v" + ver + " - Needs Improvement!"); i.setType("plain/text"); try { startActivity(i); } catch (ActivityNotFoundException e) { /* this probably never happens */ } act.finish(); } }); b = (Button)v.findViewById(R.id.maybe_later); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { act.finish(); } }); return v; } private static void recordNag(Context ctx) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx); sp.edit().putBoolean("feedback_nagged", true).commit(); } private static boolean isNagOK(Context ctx) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx); if (sp.getBoolean("feedback_nagged", false)) { return false; } long first = sp.getLong("first_use", -1); if (first == -1) { return false; } Calendar now = Calendar.getInstance(); Calendar nagDay = Calendar.getInstance(); nagDay.setTimeInMillis(first); nagDay.add(Calendar.DATE, nagDays); if (!now.after(nagDay)) { return false; } long numUses = sp.getLong("num_uses", 0); if (numUses < nagUses) { return false; } return true; } public static void feedbackNag(Context ctx) { if (!isNagOK(ctx)) { return; } recordNag(ctx);
// Path: app/src/main/java/app/openconnect/FragActivity.java // public class FragActivity extends Activity { // // public static final String TAG = "OpenConnect"; // // public static final String EXTRA_FRAGMENT_NAME = "app.openconnect.fragment_name"; // // public static final String FRAGMENT_PREFIX = "app.openconnect.fragments."; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if(savedInstanceState == null) { // try { // String fragName = getIntent().getStringExtra(EXTRA_FRAGMENT_NAME); // Fragment frag = (Fragment)Class.forName(FRAGMENT_PREFIX + fragName).newInstance(); // getFragmentManager().beginTransaction().add(android.R.id.content, frag).commit(); // } catch (Exception e) { // Log.e(TAG, "unable to create fragment", e); // finish(); // } // } // } // // } // Path: app/src/main/java/app/openconnect/fragments/FeedbackFragment.java import java.util.Calendar; import android.app.Activity; import android.app.Fragment; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import app.openconnect.FragActivity; import app.openconnect.R; /* * Copyright (c) 2014, Kevin Cernekee * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library. */ package app.openconnect.fragments; public class FeedbackFragment extends Fragment { public static final String TAG = "OpenConnect"; public static final String marketURI = "market://details?id=app.openconnect"; /* ask for feedback exactly once, after NAGDAYS && NAGUSES */ private static final int nagDays = 14; private static final long nagUses = 10; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.feedback, container, false); final Activity act = getActivity(); Button b; /* * Adapted from: * http://www.techrepublic.com/blog/software-engineer/get-more-positive-ratings-for-your-app-in-google-play/1111/ */ b = (Button)v.findViewById(R.id.i_love_it); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { recordNag(act); Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(marketURI)); try { startActivity(i); } catch (ActivityNotFoundException e) { /* not all devices have a handler for market:// URIs registered */ } act.finish(); } }); b = (Button)v.findViewById(R.id.needs_work); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { recordNag(act); String ver = "???"; try { PackageInfo packageinfo = act.getPackageManager().getPackageInfo(act.getPackageName(), 0); ver = packageinfo.versionName; } catch (NameNotFoundException e) { } Intent i = new Intent(android.content.Intent.ACTION_SEND); i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"cernekee+oc@gmail.com"}); i.putExtra(android.content.Intent.EXTRA_SUBJECT, "ics-openconnect v" + ver + " - Needs Improvement!"); i.setType("plain/text"); try { startActivity(i); } catch (ActivityNotFoundException e) { /* this probably never happens */ } act.finish(); } }); b = (Button)v.findViewById(R.id.maybe_later); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { act.finish(); } }); return v; } private static void recordNag(Context ctx) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx); sp.edit().putBoolean("feedback_nagged", true).commit(); } private static boolean isNagOK(Context ctx) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx); if (sp.getBoolean("feedback_nagged", false)) { return false; } long first = sp.getLong("first_use", -1); if (first == -1) { return false; } Calendar now = Calendar.getInstance(); Calendar nagDay = Calendar.getInstance(); nagDay.setTimeInMillis(first); nagDay.add(Calendar.DATE, nagDays); if (!now.after(nagDay)) { return false; } long numUses = sp.getLong("num_uses", 0); if (numUses < nagUses) { return false; } return true; } public static void feedbackNag(Context ctx) { if (!isNagOK(ctx)) { return; } recordNag(ctx);
Intent intent = new Intent(ctx, FragActivity.class);
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/MapFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/Expression.java // public interface Expression<T> { // /** // * Evaluate this expression against a JSON-like structure and return the result. // */ // T search(T input); // }
import java.util.List; import java.util.ArrayList; import io.burt.jmespath.Adapter; import io.burt.jmespath.Expression;
package io.burt.jmespath.function; public class MapFunction extends BaseFunction { public MapFunction() { super( ArgumentConstraints.expression(), ArgumentConstraints.arrayOf(ArgumentConstraints.anyValue()) ); } @Override
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/Expression.java // public interface Expression<T> { // /** // * Evaluate this expression against a JSON-like structure and return the result. // */ // T search(T input); // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/MapFunction.java import java.util.List; import java.util.ArrayList; import io.burt.jmespath.Adapter; import io.burt.jmespath.Expression; package io.burt.jmespath.function; public class MapFunction extends BaseFunction { public MapFunction() { super( ArgumentConstraints.expression(), ArgumentConstraints.arrayOf(ArgumentConstraints.anyValue()) ); } @Override
protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/MapFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/Expression.java // public interface Expression<T> { // /** // * Evaluate this expression against a JSON-like structure and return the result. // */ // T search(T input); // }
import java.util.List; import java.util.ArrayList; import io.burt.jmespath.Adapter; import io.burt.jmespath.Expression;
package io.burt.jmespath.function; public class MapFunction extends BaseFunction { public MapFunction() { super( ArgumentConstraints.expression(), ArgumentConstraints.arrayOf(ArgumentConstraints.anyValue()) ); } @Override protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/Expression.java // public interface Expression<T> { // /** // * Evaluate this expression against a JSON-like structure and return the result. // */ // T search(T input); // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/MapFunction.java import java.util.List; import java.util.ArrayList; import io.burt.jmespath.Adapter; import io.burt.jmespath.Expression; package io.burt.jmespath.function; public class MapFunction extends BaseFunction { public MapFunction() { super( ArgumentConstraints.expression(), ArgumentConstraints.arrayOf(ArgumentConstraints.anyValue()) ); } @Override protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {
Expression<T> expression = arguments.get(0).expression();
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/node/FlattenArrayNode.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // }
import java.util.List; import java.util.LinkedList; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType;
package io.burt.jmespath.node; public class FlattenArrayNode<T> extends Node<T> { public FlattenArrayNode(Adapter<T> runtime) { super(runtime); } @Override public T search(T input) {
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // } // Path: jmespath-core/src/main/java/io/burt/jmespath/node/FlattenArrayNode.java import java.util.List; import java.util.LinkedList; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType; package io.burt.jmespath.node; public class FlattenArrayNode<T> extends Node<T> { public FlattenArrayNode(Adapter<T> runtime) { super(runtime); } @Override public T search(T input) {
if (runtime.typeOf(input) == JmesPathType.ARRAY) {
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/JoinFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // }
import java.util.List; import java.util.Iterator; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType;
package io.burt.jmespath.function; public class JoinFunction extends BaseFunction { public JoinFunction() { super(
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/JoinFunction.java import java.util.List; import java.util.Iterator; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType; package io.burt.jmespath.function; public class JoinFunction extends BaseFunction { public JoinFunction() { super(
ArgumentConstraints.typeOf(JmesPathType.STRING),
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/JoinFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // }
import java.util.List; import java.util.Iterator; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType;
package io.burt.jmespath.function; public class JoinFunction extends BaseFunction { public JoinFunction() { super( ArgumentConstraints.typeOf(JmesPathType.STRING), ArgumentConstraints.arrayOf(ArgumentConstraints.typeOf(JmesPathType.STRING)) ); } @Override
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/JoinFunction.java import java.util.List; import java.util.Iterator; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType; package io.burt.jmespath.function; public class JoinFunction extends BaseFunction { public JoinFunction() { super( ArgumentConstraints.typeOf(JmesPathType.STRING), ArgumentConstraints.arrayOf(ArgumentConstraints.typeOf(JmesPathType.STRING)) ); } @Override
protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/BaseFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // }
import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import java.util.regex.Matcher; import io.burt.jmespath.Adapter;
while (m.find(offset)) { String piece = n.substring(m.start(), m.end()).toLowerCase(); if (piece.equals("function")) { break; } snakeCaseName.append(piece); snakeCaseName.append('_'); offset = m.end(); } snakeCaseName.deleteCharAt(snakeCaseName.length() - 1); return snakeCaseName.toString(); } @Override public String name() { return name; } @Override public ArgumentConstraint argumentConstraints() { return argumentConstraints; } /** * Call this function with a list of arguments. * * The arguments can be either values or expressions, and will be checked * by the function's argument constraints before the function runs. */ @Override
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/BaseFunction.java import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import java.util.regex.Matcher; import io.burt.jmespath.Adapter; while (m.find(offset)) { String piece = n.substring(m.start(), m.end()).toLowerCase(); if (piece.equals("function")) { break; } snakeCaseName.append(piece); snakeCaseName.append('_'); offset = m.end(); } snakeCaseName.deleteCharAt(snakeCaseName.length() - 1); return snakeCaseName.toString(); } @Override public String name() { return name; } @Override public ArgumentConstraint argumentConstraints() { return argumentConstraints; } /** * Call this function with a list of arguments. * * The arguments can be either values or expressions, and will be checked * by the function's argument constraints before the function runs. */ @Override
public <T> T call(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/node/OperatorNode.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/Expression.java // public interface Expression<T> { // /** // * Evaluate this expression against a JSON-like structure and return the result. // */ // T search(T input); // }
import java.util.Arrays; import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.Expression;
package io.burt.jmespath.node; public abstract class OperatorNode<T> extends Node<T> { private final List<Expression<T>> operands; @SafeVarargs
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/Expression.java // public interface Expression<T> { // /** // * Evaluate this expression against a JSON-like structure and return the result. // */ // T search(T input); // } // Path: jmespath-core/src/main/java/io/burt/jmespath/node/OperatorNode.java import java.util.Arrays; import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.Expression; package io.burt.jmespath.node; public abstract class OperatorNode<T> extends Node<T> { private final List<Expression<T>> operands; @SafeVarargs
public OperatorNode(Adapter<T> runtime, Expression<T>... operands) {
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/ToStringFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // }
import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType;
package io.burt.jmespath.function; public class ToStringFunction extends BaseFunction { public ToStringFunction() { super(ArgumentConstraints.anyValue()); } @Override
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/ToStringFunction.java import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType; package io.burt.jmespath.function; public class ToStringFunction extends BaseFunction { public ToStringFunction() { super(ArgumentConstraints.anyValue()); } @Override
protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/ToStringFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // }
import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType;
package io.burt.jmespath.function; public class ToStringFunction extends BaseFunction { public ToStringFunction() { super(ArgumentConstraints.anyValue()); } @Override protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) { T subject = arguments.get(0).value();
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/ToStringFunction.java import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType; package io.burt.jmespath.function; public class ToStringFunction extends BaseFunction { public ToStringFunction() { super(ArgumentConstraints.anyValue()); } @Override protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) { T subject = arguments.get(0).value();
if (runtime.typeOf(subject) == JmesPathType.STRING) {
burtcorp/jmespath-java
jmespath-core/src/main/java/io/burt/jmespath/function/NotNullFunction.java
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // }
import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType;
package io.burt.jmespath.function; public class NotNullFunction extends BaseFunction { public NotNullFunction() { super(ArgumentConstraints.listOf(1, Integer.MAX_VALUE, ArgumentConstraints.anyValue())); } @Override
// Path: jmespath-core/src/main/java/io/burt/jmespath/Adapter.java // public interface Adapter<T> extends JmesPath<T>, Comparator<T> { // /** // * Parse a JSON string to a value. // * // * May throw exceptions when the given string is not valid JSON. The exact // * exceptions thrown will depend on the concrete implementation. // */ // T parseString(String str); // // /** // * Converts the argument to a {@link List}. // * // * When the argument represents an array the list will contain the elements of // * the array, when the argument represents an object the result is a list of // * the object's values and for all other types the result is an empty list. // */ // List<T> toList(T value); // // /** // * Converts the argument to a {@link String}. When the argument represents a string // * its string value is returned, otherwise a string with the value encoded // * as JSON is returned. // */ // String toString(T value); // // /** // * Converts the argument to a {@link Number}, or null if the argument does not // * represent a number. // */ // Number toNumber(T value); // // /** // * Returns true when the argument is truthy. // * // * All values are truthy, except the following, as per the JMESPath // * specification: <code>false</code>, <code>null</code>, empty lists, empty // * objects, empty strings. // */ // boolean isTruthy(T value); // // /** // * Returns the JSON type of the argument. // * // * As per the JMESPath specification the types are: <code>number</code>, // * <code>string</code>, <code>boolean</code>, <code>array</code>, // * <code>object</code>, <code>null</code>. // * // * @see JmesPathType // */ // JmesPathType typeOf(T value); // // /** // * Returns the value of a property of an object. // * // * The first argument must be an object and the second argument may be // * the name of a property on that object. When the property does not exist // * a null value (<em>not</em> Java <code>null</code>) is returned. // */ // @Deprecated // T getProperty(T value, String name); // // /** // * Returns the value of a property of an object. // * // * The first argument must represent an object and the second argument may be // * the name (which must be a string value) of a property of that object. // * When the property does not exist or represents null a null value (but not // * Java null) is returned. // */ // T getProperty(T value, T name); // // /** // * Returns all the property names of the given object, or an empty collection // * when the given value does not represent an object. // * // * The property names are always string values. // */ // Collection<T> getPropertyNames(T value); // // /** // * Returns a null value (<em>not</em> Java <code>null</code>). // */ // T createNull(); // // /** // * Returns an array value with the specified elements. // */ // T createArray(Collection<T> elements); // // /** // * Returns a string value containing the specified string. // */ // T createString(String str); // // /** // * Returns a boolean value containing the specified boolean. // */ // T createBoolean(boolean b); // // /** // * Returns an object value with the specified properties. // * // * The map keys must all be string values. // * // * Creating nested objects is not supported. // */ // T createObject(Map<T, T> obj); // // /** // * Returns a number value containing the specified floating point number. // */ // T createNumber(double n); // // /** // * Returns a number value containing the specified integer. // */ // T createNumber(long n); // // /** // * Throws an exception or returns a fallback value when a type check fails // * during a function call evaluation. // */ // T handleArgumentTypeError(Function function, String expectedType, String actualType); // // /** // * Returns a function registry that can be used by the expression compiler // * to look up functions. // */ // FunctionRegistry functionRegistry(); // // /** // * Returns a node factory that can be used by the expression compiler to build // * the interpreter AST. // */ // NodeFactory<T> nodeFactory(); // } // // Path: jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java // public enum JmesPathType { // NUMBER, // STRING, // BOOLEAN, // ARRAY, // OBJECT, // NULL; // // @Override // public String toString() { // return name().toLowerCase(); // } // } // Path: jmespath-core/src/main/java/io/burt/jmespath/function/NotNullFunction.java import java.util.List; import io.burt.jmespath.Adapter; import io.burt.jmespath.JmesPathType; package io.burt.jmespath.function; public class NotNullFunction extends BaseFunction { public NotNullFunction() { super(ArgumentConstraints.listOf(1, Integer.MAX_VALUE, ArgumentConstraints.anyValue())); } @Override
protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {