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
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/lock/LockSetup.java
// Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/TritonScheduler.java // @Singleton // public class TritonScheduler { // // private ScheduledExecutorService executor; // // public TritonScheduler() { // executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("triton-scheduler-")); // } // // /** // * Schedule once with delay // * @param command // * @param delay // */ // public void schedule(Runnable command, long delay) { // executor.schedule(command, delay, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task at fixed rate // * @param command // * @param delay // * @param period // */ // public void scheduleAtFixedRate(Runnable command, long delay, long period) { // executor.scheduleAtFixedRate(command, delay, period, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task with fixed delay // * @param command // * @param delay // * @param period // */ // public void scheduleWithFixedDelay(Runnable command, long delay, long period) { // executor.scheduleWithFixedDelay(command, delay, period, TimeUnit.MILLISECONDS); // } // // } // // Path: src/main/java/com/amebame/triton/service/lock/method/LockMethods.java // public class LockMethods { // // private LockManager manager; // // @Inject // public LockMethods(LockManager manager) { // this.manager = manager; // } // // @TritonMethod(value="lock.acquire", async=true) // public void acquire(Channel channel, TritonMessage message, LockAcquire acquire) { // LockOwner owner = new LockOwner(channel, message.getCallId()); // manager.lock(owner, acquire.getKey(), acquire.getTimeout()); // } // // @TritonMethod("lock.release") // public boolean release(Channel channel, TritonMessage message, LockRelease release) { // LockOwner owner = new LockOwner(channel, message.getCallId(), release.getOwnerId()); // manager.unlock(owner, release.getKey()); // return true; // } // // }
import javax.inject.Inject; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.TritonScheduler; import com.amebame.triton.service.lock.method.LockMethods;
package com.amebame.triton.service.lock; public class LockSetup { @Inject private TritonServerContext context;
// Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/TritonScheduler.java // @Singleton // public class TritonScheduler { // // private ScheduledExecutorService executor; // // public TritonScheduler() { // executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("triton-scheduler-")); // } // // /** // * Schedule once with delay // * @param command // * @param delay // */ // public void schedule(Runnable command, long delay) { // executor.schedule(command, delay, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task at fixed rate // * @param command // * @param delay // * @param period // */ // public void scheduleAtFixedRate(Runnable command, long delay, long period) { // executor.scheduleAtFixedRate(command, delay, period, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task with fixed delay // * @param command // * @param delay // * @param period // */ // public void scheduleWithFixedDelay(Runnable command, long delay, long period) { // executor.scheduleWithFixedDelay(command, delay, period, TimeUnit.MILLISECONDS); // } // // } // // Path: src/main/java/com/amebame/triton/service/lock/method/LockMethods.java // public class LockMethods { // // private LockManager manager; // // @Inject // public LockMethods(LockManager manager) { // this.manager = manager; // } // // @TritonMethod(value="lock.acquire", async=true) // public void acquire(Channel channel, TritonMessage message, LockAcquire acquire) { // LockOwner owner = new LockOwner(channel, message.getCallId()); // manager.lock(owner, acquire.getKey(), acquire.getTimeout()); // } // // @TritonMethod("lock.release") // public boolean release(Channel channel, TritonMessage message, LockRelease release) { // LockOwner owner = new LockOwner(channel, message.getCallId(), release.getOwnerId()); // manager.unlock(owner, release.getKey()); // return true; // } // // } // Path: src/main/java/com/amebame/triton/service/lock/LockSetup.java import javax.inject.Inject; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.TritonScheduler; import com.amebame.triton.service.lock.method.LockMethods; package com.amebame.triton.service.lock; public class LockSetup { @Inject private TritonServerContext context;
@Inject private LockMethods methods;
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/lock/LockSetup.java
// Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/TritonScheduler.java // @Singleton // public class TritonScheduler { // // private ScheduledExecutorService executor; // // public TritonScheduler() { // executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("triton-scheduler-")); // } // // /** // * Schedule once with delay // * @param command // * @param delay // */ // public void schedule(Runnable command, long delay) { // executor.schedule(command, delay, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task at fixed rate // * @param command // * @param delay // * @param period // */ // public void scheduleAtFixedRate(Runnable command, long delay, long period) { // executor.scheduleAtFixedRate(command, delay, period, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task with fixed delay // * @param command // * @param delay // * @param period // */ // public void scheduleWithFixedDelay(Runnable command, long delay, long period) { // executor.scheduleWithFixedDelay(command, delay, period, TimeUnit.MILLISECONDS); // } // // } // // Path: src/main/java/com/amebame/triton/service/lock/method/LockMethods.java // public class LockMethods { // // private LockManager manager; // // @Inject // public LockMethods(LockManager manager) { // this.manager = manager; // } // // @TritonMethod(value="lock.acquire", async=true) // public void acquire(Channel channel, TritonMessage message, LockAcquire acquire) { // LockOwner owner = new LockOwner(channel, message.getCallId()); // manager.lock(owner, acquire.getKey(), acquire.getTimeout()); // } // // @TritonMethod("lock.release") // public boolean release(Channel channel, TritonMessage message, LockRelease release) { // LockOwner owner = new LockOwner(channel, message.getCallId(), release.getOwnerId()); // manager.unlock(owner, release.getKey()); // return true; // } // // }
import javax.inject.Inject; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.TritonScheduler; import com.amebame.triton.service.lock.method.LockMethods;
package com.amebame.triton.service.lock; public class LockSetup { @Inject private TritonServerContext context; @Inject private LockMethods methods; @Inject private LockClearner cleaner;
// Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/TritonScheduler.java // @Singleton // public class TritonScheduler { // // private ScheduledExecutorService executor; // // public TritonScheduler() { // executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("triton-scheduler-")); // } // // /** // * Schedule once with delay // * @param command // * @param delay // */ // public void schedule(Runnable command, long delay) { // executor.schedule(command, delay, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task at fixed rate // * @param command // * @param delay // * @param period // */ // public void scheduleAtFixedRate(Runnable command, long delay, long period) { // executor.scheduleAtFixedRate(command, delay, period, TimeUnit.MILLISECONDS); // } // // /** // * Schedule task with fixed delay // * @param command // * @param delay // * @param period // */ // public void scheduleWithFixedDelay(Runnable command, long delay, long period) { // executor.scheduleWithFixedDelay(command, delay, period, TimeUnit.MILLISECONDS); // } // // } // // Path: src/main/java/com/amebame/triton/service/lock/method/LockMethods.java // public class LockMethods { // // private LockManager manager; // // @Inject // public LockMethods(LockManager manager) { // this.manager = manager; // } // // @TritonMethod(value="lock.acquire", async=true) // public void acquire(Channel channel, TritonMessage message, LockAcquire acquire) { // LockOwner owner = new LockOwner(channel, message.getCallId()); // manager.lock(owner, acquire.getKey(), acquire.getTimeout()); // } // // @TritonMethod("lock.release") // public boolean release(Channel channel, TritonMessage message, LockRelease release) { // LockOwner owner = new LockOwner(channel, message.getCallId(), release.getOwnerId()); // manager.unlock(owner, release.getKey()); // return true; // } // // } // Path: src/main/java/com/amebame/triton/service/lock/LockSetup.java import javax.inject.Inject; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.TritonScheduler; import com.amebame.triton.service.lock.method.LockMethods; package com.amebame.triton.service.lock; public class LockSetup { @Inject private TritonServerContext context; @Inject private LockMethods methods; @Inject private LockClearner cleaner;
@Inject private TritonScheduler scheduler;
ameba-proteus/triton-server
src/test/java/com/amebame/proteus/triton/TritonByteTest.java
// Path: src/main/java/com/amebame/triton/server/util/BytesUtil.java // public class BytesUtil { // // public BytesUtil() { // } // // private static final int ZERO = 0x00; // private static final int MAX = 0xff; // // /** // * Get next byte array // * @param buffer // * @return // */ // public static final byte[] next(byte[] bytes) { // return _next(copy(bytes)); // } // // /** // * Get next buffer // * @param buffer // * @return // */ // public static final ByteBuffer next(ByteBuffer buffer) { // return ByteBuffer.wrap(_next(copy(buffer))); // } // // private static final byte[] _next(byte[] bytes) { // int pos = bytes.length -1; // while (pos >= 0) { // int b = bytes[pos] & 0xff; // if (b == MAX) { // bytes[pos] = ZERO; // } else { // b++; // bytes[pos] = (byte) b; // break; // } // pos--; // } // return bytes; // } // // /** // * Get previous bytes // * @param bytes // * @return // */ // public static final byte[] previous(byte[] bytes) { // return _previous(copy(bytes)); // } // // /** // * Get previous buffer // * @param buffer // * @return // */ // public static final ByteBuffer previous(ByteBuffer buffer) { // return ByteBuffer.wrap(_previous(copy(buffer))); // } // // private static final byte[] _previous(byte[] bytes) { // int pos = bytes.length -1; // while (pos >= 0) { // int b = bytes[pos] & 0xff; // if (b == ZERO) { // bytes[pos] = (byte) MAX; // } else { // b--; // bytes[pos] = (byte) b; // break; // } // pos--; // } // return bytes; // } // // /** // * Copy binary // * @param bytes // * @return // */ // private static final byte[] copy(byte[] bytes) { // byte[] copy = new byte[bytes.length]; // System.arraycopy(bytes, 0, copy, 0, bytes.length); // return copy; // } // // /** // * Copy buffer to byte array // * @param buffer // * @return // */ // private static final byte[] copy(ByteBuffer buffer) { // buffer.mark(); // byte[] bytes = new byte[buffer.limit()]; // buffer.get(bytes); // buffer.reset(); // return bytes; // } // }
import static org.junit.Assert.assertArrayEquals; import org.junit.Test; import com.amebame.triton.server.util.BytesUtil;
bytes(0xff), previous(0x00) ); assertArrayEquals( bytes(0x00, 0x00), previous(0x00, 0x01) ); assertArrayEquals( bytes(0x30, 0xa0), previous(0x30, 0xa1) ); assertArrayEquals( bytes(0xa0, 0xba, 0xff), previous(0xa0, 0xbb, 0x00) ); assertArrayEquals( bytes(0x00, 0x05, 0xff, 0xff, 0xff), previous(0x00, 0x06, 0x00, 0x00, 0x00) ); } private static final byte[] bytes(int ... values) { byte[] bytes = new byte[values.length]; for (int i = 0; i < values.length; i++) { bytes[i] = (byte) values[i]; } return bytes; } private static final byte[] next(int ... values) {
// Path: src/main/java/com/amebame/triton/server/util/BytesUtil.java // public class BytesUtil { // // public BytesUtil() { // } // // private static final int ZERO = 0x00; // private static final int MAX = 0xff; // // /** // * Get next byte array // * @param buffer // * @return // */ // public static final byte[] next(byte[] bytes) { // return _next(copy(bytes)); // } // // /** // * Get next buffer // * @param buffer // * @return // */ // public static final ByteBuffer next(ByteBuffer buffer) { // return ByteBuffer.wrap(_next(copy(buffer))); // } // // private static final byte[] _next(byte[] bytes) { // int pos = bytes.length -1; // while (pos >= 0) { // int b = bytes[pos] & 0xff; // if (b == MAX) { // bytes[pos] = ZERO; // } else { // b++; // bytes[pos] = (byte) b; // break; // } // pos--; // } // return bytes; // } // // /** // * Get previous bytes // * @param bytes // * @return // */ // public static final byte[] previous(byte[] bytes) { // return _previous(copy(bytes)); // } // // /** // * Get previous buffer // * @param buffer // * @return // */ // public static final ByteBuffer previous(ByteBuffer buffer) { // return ByteBuffer.wrap(_previous(copy(buffer))); // } // // private static final byte[] _previous(byte[] bytes) { // int pos = bytes.length -1; // while (pos >= 0) { // int b = bytes[pos] & 0xff; // if (b == ZERO) { // bytes[pos] = (byte) MAX; // } else { // b--; // bytes[pos] = (byte) b; // break; // } // pos--; // } // return bytes; // } // // /** // * Copy binary // * @param bytes // * @return // */ // private static final byte[] copy(byte[] bytes) { // byte[] copy = new byte[bytes.length]; // System.arraycopy(bytes, 0, copy, 0, bytes.length); // return copy; // } // // /** // * Copy buffer to byte array // * @param buffer // * @return // */ // private static final byte[] copy(ByteBuffer buffer) { // buffer.mark(); // byte[] bytes = new byte[buffer.limit()]; // buffer.get(bytes); // buffer.reset(); // return bytes; // } // } // Path: src/test/java/com/amebame/proteus/triton/TritonByteTest.java import static org.junit.Assert.assertArrayEquals; import org.junit.Test; import com.amebame.triton.server.util.BytesUtil; bytes(0xff), previous(0x00) ); assertArrayEquals( bytes(0x00, 0x00), previous(0x00, 0x01) ); assertArrayEquals( bytes(0x30, 0xa0), previous(0x30, 0xa1) ); assertArrayEquals( bytes(0xa0, 0xba, 0xff), previous(0xa0, 0xbb, 0x00) ); assertArrayEquals( bytes(0x00, 0x05, 0xff, 0xff, 0xff), previous(0x00, 0x06, 0x00, 0x00, 0x00) ); } private static final byte[] bytes(int ... values) { byte[] bytes = new byte[values.length]; for (int i = 0; i < values.length; i++) { bytes[i] = (byte) values[i]; } return bytes; } private static final byte[] next(int ... values) {
return BytesUtil.next(bytes(values));
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/memcached/TritonMemcachedClient.java
// Path: src/main/java/com/amebame/triton/config/TritonMemcachedClusterConfiguration.java // public class TritonMemcachedClusterConfiguration { // // private String[] hosts; // // private TritonMemcachedLocator locator = TritonMemcachedLocator.simple; // // public TritonMemcachedClusterConfiguration() { // } // // public String[] getHosts() { // return hosts; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // public void setHost(String host) { // this.hosts = new String[] {host}; // } // // public TritonMemcachedLocator getLocator() { // return locator; // } // // public void setLocator(TritonMemcachedLocator locator) { // this.locator = locator; // } // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedConfiguration.java // public class TritonMemcachedConfiguration { // // private Map<String, TritonMemcachedClusterConfiguration> clusters; // // public TritonMemcachedConfiguration() { // clusters = new HashMap<>(); // } // // /** // * Get cluster map // * @return // */ // public Map<String, TritonMemcachedClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Set cluster map // * @param clusters // */ // public void setClusters(Map<String, TritonMemcachedClusterConfiguration> clusters) { // this.clusters = clusters; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedLocator.java // public enum TritonMemcachedLocator { // // simple, // consistent_hash // // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // }
import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import net.rubyeye.xmemcached.HashAlgorithm; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.amebame.triton.config.TritonMemcachedClusterConfiguration; import com.amebame.triton.config.TritonMemcachedConfiguration; import com.amebame.triton.config.TritonMemcachedLocator; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner; import com.fasterxml.jackson.databind.JsonNode;
package com.amebame.triton.service.memcached; public class TritonMemcachedClient implements TritonCleaner { private static final Logger log = LogManager.getLogger(TritonMemcachedClient.class);
// Path: src/main/java/com/amebame/triton/config/TritonMemcachedClusterConfiguration.java // public class TritonMemcachedClusterConfiguration { // // private String[] hosts; // // private TritonMemcachedLocator locator = TritonMemcachedLocator.simple; // // public TritonMemcachedClusterConfiguration() { // } // // public String[] getHosts() { // return hosts; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // public void setHost(String host) { // this.hosts = new String[] {host}; // } // // public TritonMemcachedLocator getLocator() { // return locator; // } // // public void setLocator(TritonMemcachedLocator locator) { // this.locator = locator; // } // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedConfiguration.java // public class TritonMemcachedConfiguration { // // private Map<String, TritonMemcachedClusterConfiguration> clusters; // // public TritonMemcachedConfiguration() { // clusters = new HashMap<>(); // } // // /** // * Get cluster map // * @return // */ // public Map<String, TritonMemcachedClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Set cluster map // * @param clusters // */ // public void setClusters(Map<String, TritonMemcachedClusterConfiguration> clusters) { // this.clusters = clusters; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedLocator.java // public enum TritonMemcachedLocator { // // simple, // consistent_hash // // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // } // Path: src/main/java/com/amebame/triton/service/memcached/TritonMemcachedClient.java import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import net.rubyeye.xmemcached.HashAlgorithm; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.amebame.triton.config.TritonMemcachedClusterConfiguration; import com.amebame.triton.config.TritonMemcachedConfiguration; import com.amebame.triton.config.TritonMemcachedLocator; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner; import com.fasterxml.jackson.databind.JsonNode; package com.amebame.triton.service.memcached; public class TritonMemcachedClient implements TritonCleaner { private static final Logger log = LogManager.getLogger(TritonMemcachedClient.class);
private TritonMemcachedConfiguration config;
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/memcached/TritonMemcachedClient.java
// Path: src/main/java/com/amebame/triton/config/TritonMemcachedClusterConfiguration.java // public class TritonMemcachedClusterConfiguration { // // private String[] hosts; // // private TritonMemcachedLocator locator = TritonMemcachedLocator.simple; // // public TritonMemcachedClusterConfiguration() { // } // // public String[] getHosts() { // return hosts; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // public void setHost(String host) { // this.hosts = new String[] {host}; // } // // public TritonMemcachedLocator getLocator() { // return locator; // } // // public void setLocator(TritonMemcachedLocator locator) { // this.locator = locator; // } // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedConfiguration.java // public class TritonMemcachedConfiguration { // // private Map<String, TritonMemcachedClusterConfiguration> clusters; // // public TritonMemcachedConfiguration() { // clusters = new HashMap<>(); // } // // /** // * Get cluster map // * @return // */ // public Map<String, TritonMemcachedClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Set cluster map // * @param clusters // */ // public void setClusters(Map<String, TritonMemcachedClusterConfiguration> clusters) { // this.clusters = clusters; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedLocator.java // public enum TritonMemcachedLocator { // // simple, // consistent_hash // // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // }
import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import net.rubyeye.xmemcached.HashAlgorithm; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.amebame.triton.config.TritonMemcachedClusterConfiguration; import com.amebame.triton.config.TritonMemcachedConfiguration; import com.amebame.triton.config.TritonMemcachedLocator; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner; import com.fasterxml.jackson.databind.JsonNode;
package com.amebame.triton.service.memcached; public class TritonMemcachedClient implements TritonCleaner { private static final Logger log = LogManager.getLogger(TritonMemcachedClient.class); private TritonMemcachedConfiguration config; private Map<String, MemcachedClient> clients; private MemcachedJsonTranscoder transcoder = new MemcachedJsonTranscoder(); @Inject public TritonMemcachedClient(TritonMemcachedConfiguration config) throws IOException { this.config = config; this.clients = new HashMap<>(); // creating cluster configuration
// Path: src/main/java/com/amebame/triton/config/TritonMemcachedClusterConfiguration.java // public class TritonMemcachedClusterConfiguration { // // private String[] hosts; // // private TritonMemcachedLocator locator = TritonMemcachedLocator.simple; // // public TritonMemcachedClusterConfiguration() { // } // // public String[] getHosts() { // return hosts; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // public void setHost(String host) { // this.hosts = new String[] {host}; // } // // public TritonMemcachedLocator getLocator() { // return locator; // } // // public void setLocator(TritonMemcachedLocator locator) { // this.locator = locator; // } // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedConfiguration.java // public class TritonMemcachedConfiguration { // // private Map<String, TritonMemcachedClusterConfiguration> clusters; // // public TritonMemcachedConfiguration() { // clusters = new HashMap<>(); // } // // /** // * Get cluster map // * @return // */ // public Map<String, TritonMemcachedClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Set cluster map // * @param clusters // */ // public void setClusters(Map<String, TritonMemcachedClusterConfiguration> clusters) { // this.clusters = clusters; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedLocator.java // public enum TritonMemcachedLocator { // // simple, // consistent_hash // // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // } // Path: src/main/java/com/amebame/triton/service/memcached/TritonMemcachedClient.java import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import net.rubyeye.xmemcached.HashAlgorithm; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.amebame.triton.config.TritonMemcachedClusterConfiguration; import com.amebame.triton.config.TritonMemcachedConfiguration; import com.amebame.triton.config.TritonMemcachedLocator; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner; import com.fasterxml.jackson.databind.JsonNode; package com.amebame.triton.service.memcached; public class TritonMemcachedClient implements TritonCleaner { private static final Logger log = LogManager.getLogger(TritonMemcachedClient.class); private TritonMemcachedConfiguration config; private Map<String, MemcachedClient> clients; private MemcachedJsonTranscoder transcoder = new MemcachedJsonTranscoder(); @Inject public TritonMemcachedClient(TritonMemcachedConfiguration config) throws IOException { this.config = config; this.clients = new HashMap<>(); // creating cluster configuration
for (Entry<String, TritonMemcachedClusterConfiguration> entry : config.getClusters().entrySet()) {
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/memcached/TritonMemcachedClient.java
// Path: src/main/java/com/amebame/triton/config/TritonMemcachedClusterConfiguration.java // public class TritonMemcachedClusterConfiguration { // // private String[] hosts; // // private TritonMemcachedLocator locator = TritonMemcachedLocator.simple; // // public TritonMemcachedClusterConfiguration() { // } // // public String[] getHosts() { // return hosts; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // public void setHost(String host) { // this.hosts = new String[] {host}; // } // // public TritonMemcachedLocator getLocator() { // return locator; // } // // public void setLocator(TritonMemcachedLocator locator) { // this.locator = locator; // } // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedConfiguration.java // public class TritonMemcachedConfiguration { // // private Map<String, TritonMemcachedClusterConfiguration> clusters; // // public TritonMemcachedConfiguration() { // clusters = new HashMap<>(); // } // // /** // * Get cluster map // * @return // */ // public Map<String, TritonMemcachedClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Set cluster map // * @param clusters // */ // public void setClusters(Map<String, TritonMemcachedClusterConfiguration> clusters) { // this.clusters = clusters; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedLocator.java // public enum TritonMemcachedLocator { // // simple, // consistent_hash // // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // }
import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import net.rubyeye.xmemcached.HashAlgorithm; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.amebame.triton.config.TritonMemcachedClusterConfiguration; import com.amebame.triton.config.TritonMemcachedConfiguration; import com.amebame.triton.config.TritonMemcachedLocator; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner; import com.fasterxml.jackson.databind.JsonNode;
* @param key */ public void delete(String cluster, String key) { MemcachedClient client = getClient(cluster); try { client.delete(key); } catch (MemcachedException | InterruptedException e) { throw new TritonMemcachedException( TritonErrors.memcached_error, e); } catch (TimeoutException e) { throw new TritonMemcachedException( TritonErrors.memcached_timeout, e); } } /** * Create client from {@link TritonMemcachedClusterConfiguration} * @param config * @return */ private MemcachedClient createClient(String name, TritonMemcachedClusterConfiguration config) throws IOException { String hosts = StringUtils.join(config.getHosts(), ' '); log.info("creating memcached client with ", hosts); XMemcachedClientBuilder builder = new XMemcachedClientBuilder( AddrUtil.getAddresses(hosts) );
// Path: src/main/java/com/amebame/triton/config/TritonMemcachedClusterConfiguration.java // public class TritonMemcachedClusterConfiguration { // // private String[] hosts; // // private TritonMemcachedLocator locator = TritonMemcachedLocator.simple; // // public TritonMemcachedClusterConfiguration() { // } // // public String[] getHosts() { // return hosts; // } // // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // public void setHost(String host) { // this.hosts = new String[] {host}; // } // // public TritonMemcachedLocator getLocator() { // return locator; // } // // public void setLocator(TritonMemcachedLocator locator) { // this.locator = locator; // } // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedConfiguration.java // public class TritonMemcachedConfiguration { // // private Map<String, TritonMemcachedClusterConfiguration> clusters; // // public TritonMemcachedConfiguration() { // clusters = new HashMap<>(); // } // // /** // * Get cluster map // * @return // */ // public Map<String, TritonMemcachedClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Set cluster map // * @param clusters // */ // public void setClusters(Map<String, TritonMemcachedClusterConfiguration> clusters) { // this.clusters = clusters; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonMemcachedLocator.java // public enum TritonMemcachedLocator { // // simple, // consistent_hash // // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // } // Path: src/main/java/com/amebame/triton/service/memcached/TritonMemcachedClient.java import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import net.rubyeye.xmemcached.HashAlgorithm; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.amebame.triton.config.TritonMemcachedClusterConfiguration; import com.amebame.triton.config.TritonMemcachedConfiguration; import com.amebame.triton.config.TritonMemcachedLocator; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner; import com.fasterxml.jackson.databind.JsonNode; * @param key */ public void delete(String cluster, String key) { MemcachedClient client = getClient(cluster); try { client.delete(key); } catch (MemcachedException | InterruptedException e) { throw new TritonMemcachedException( TritonErrors.memcached_error, e); } catch (TimeoutException e) { throw new TritonMemcachedException( TritonErrors.memcached_timeout, e); } } /** * Create client from {@link TritonMemcachedClusterConfiguration} * @param config * @return */ private MemcachedClient createClient(String name, TritonMemcachedClusterConfiguration config) throws IOException { String hosts = StringUtils.join(config.getHosts(), ' '); log.info("creating memcached client with ", hosts); XMemcachedClientBuilder builder = new XMemcachedClientBuilder( AddrUtil.getAddresses(hosts) );
if (config.getLocator() == TritonMemcachedLocator.consistent_hash) {
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/elasticsearch/TritonElasticSearchClient.java
// Path: src/main/java/com/amebame/triton/config/TritonElasticSearchClusterConfiguration.java // public class TritonElasticSearchClusterConfiguration { // // private ImmutableSettings.Builder builder; // // private String[] hosts; // // public TritonElasticSearchClusterConfiguration() { // builder = ImmutableSettings.builder(); // builder.put("client.transport.ignore_cluster_name", true); // } // // /** // * Set cluster name. // * @param name // */ // public void setName(String name) { // builder.put("cluster.name", name); // } // // /** // * Set to true to sniff and add cluster machines. // * @param sniff // */ // public void setSniff(boolean sniff) { // builder.put("client.transport.sniff", sniff); // } // // /** // * Set to true to ignore cluster name validation. // * @param ignore // */ // public void setIgnoreClusterName(boolean ignore) { // builder.put("client.transport.ignore_cluster_name", true); // } // // /** // * Set host address list. // * @param hosts ["127.0.0.1:9300", "127.0.0.2:9300", ..] // */ // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // /** // * Set single host address and port // * @param host 127.0.0.1:9300 // */ // public void setHost(String host) { // this.hosts = new String[]{ host }; // } // // /** // * Get host address list. // * @return // */ // public String[] getHosts() { // return this.hosts; // } // // /** // * Get settings to create client. // * @return // */ // public Settings getSettings() { // return builder.build(); // } // // /** // * Create {@link Client} to connect to the cluster. // * @return // */ // public Client createClient() { // TransportClient client = new TransportClient(getSettings()); // for (String host : hosts) { // client.addTransportAddress(new InetSocketTransportAddress(AddrUtil.getOneAddress(host))); // } // return client; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonElasticSearchConfiguration.java // public class TritonElasticSearchConfiguration implements TritonCleaner { // // // Cluster configuraiton map // private Map<String, TritonElasticSearchClusterConfiguration> clusters; // // // Timeout for ElasticSearch (default 5 sec) // private long timeout = 5000L; // // public TritonElasticSearchConfiguration() { // clusters = new HashMap<>(); // } // // @Override // public void clean() { // } // // /** // * Set cluster configuraiton map // * @param clusters // */ // public void setClusters(Map<String, TritonElasticSearchClusterConfiguration> clusters) { // this.clusters = clusters; // } // // /** // * Get cluster configuraiton map // * @return // */ // public Map<String, TritonElasticSearchClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Get cluster keys which are registered // * @return // */ // public Set<String> getClusterKeys() { // return clusters.keySet(); // } // // /** // * Get cluster configuration. // * @param key // * @return // */ // public TritonElasticSearchClusterConfiguration getClusterConfiguration(String key) { // return clusters.get(key); // } // // /** // * Set the timeout value in milliseconds. // * @param timeout // */ // public void setTimeout(long timeout) { // this.timeout = timeout; // } // // /** // * Get the milliseconds of timeout. // * @return // */ // public long getTimeout() { // return timeout; // } // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // }
import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.client.Client; import com.amebame.triton.config.TritonElasticSearchClusterConfiguration; import com.amebame.triton.config.TritonElasticSearchConfiguration; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner;
package com.amebame.triton.service.elasticsearch; /** * {@link TritonElasticSearchClient} provides {@link Client} instances. */ public class TritonElasticSearchClient implements TritonCleaner { private static final Logger log = LogManager.getLogger(TritonElasticSearchClient.class); // configuration
// Path: src/main/java/com/amebame/triton/config/TritonElasticSearchClusterConfiguration.java // public class TritonElasticSearchClusterConfiguration { // // private ImmutableSettings.Builder builder; // // private String[] hosts; // // public TritonElasticSearchClusterConfiguration() { // builder = ImmutableSettings.builder(); // builder.put("client.transport.ignore_cluster_name", true); // } // // /** // * Set cluster name. // * @param name // */ // public void setName(String name) { // builder.put("cluster.name", name); // } // // /** // * Set to true to sniff and add cluster machines. // * @param sniff // */ // public void setSniff(boolean sniff) { // builder.put("client.transport.sniff", sniff); // } // // /** // * Set to true to ignore cluster name validation. // * @param ignore // */ // public void setIgnoreClusterName(boolean ignore) { // builder.put("client.transport.ignore_cluster_name", true); // } // // /** // * Set host address list. // * @param hosts ["127.0.0.1:9300", "127.0.0.2:9300", ..] // */ // public void setHosts(String[] hosts) { // this.hosts = hosts; // } // // /** // * Set single host address and port // * @param host 127.0.0.1:9300 // */ // public void setHost(String host) { // this.hosts = new String[]{ host }; // } // // /** // * Get host address list. // * @return // */ // public String[] getHosts() { // return this.hosts; // } // // /** // * Get settings to create client. // * @return // */ // public Settings getSettings() { // return builder.build(); // } // // /** // * Create {@link Client} to connect to the cluster. // * @return // */ // public Client createClient() { // TransportClient client = new TransportClient(getSettings()); // for (String host : hosts) { // client.addTransportAddress(new InetSocketTransportAddress(AddrUtil.getOneAddress(host))); // } // return client; // } // // } // // Path: src/main/java/com/amebame/triton/config/TritonElasticSearchConfiguration.java // public class TritonElasticSearchConfiguration implements TritonCleaner { // // // Cluster configuraiton map // private Map<String, TritonElasticSearchClusterConfiguration> clusters; // // // Timeout for ElasticSearch (default 5 sec) // private long timeout = 5000L; // // public TritonElasticSearchConfiguration() { // clusters = new HashMap<>(); // } // // @Override // public void clean() { // } // // /** // * Set cluster configuraiton map // * @param clusters // */ // public void setClusters(Map<String, TritonElasticSearchClusterConfiguration> clusters) { // this.clusters = clusters; // } // // /** // * Get cluster configuraiton map // * @return // */ // public Map<String, TritonElasticSearchClusterConfiguration> getClusters() { // return clusters; // } // // /** // * Get cluster keys which are registered // * @return // */ // public Set<String> getClusterKeys() { // return clusters.keySet(); // } // // /** // * Get cluster configuration. // * @param key // * @return // */ // public TritonElasticSearchClusterConfiguration getClusterConfiguration(String key) { // return clusters.get(key); // } // // /** // * Set the timeout value in milliseconds. // * @param timeout // */ // public void setTimeout(long timeout) { // this.timeout = timeout; // } // // /** // * Get the milliseconds of timeout. // * @return // */ // public long getTimeout() { // return timeout; // } // } // // Path: src/main/java/com/amebame/triton/server/TritonCleaner.java // public interface TritonCleaner { // // /** // * Clean the resource. // */ // void clean(); // // } // Path: src/main/java/com/amebame/triton/service/elasticsearch/TritonElasticSearchClient.java import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.client.Client; import com.amebame.triton.config.TritonElasticSearchClusterConfiguration; import com.amebame.triton.config.TritonElasticSearchConfiguration; import com.amebame.triton.exception.TritonErrors; import com.amebame.triton.server.TritonCleaner; package com.amebame.triton.service.elasticsearch; /** * {@link TritonElasticSearchClient} provides {@link Client} instances. */ public class TritonElasticSearchClient implements TritonCleaner { private static final Logger log = LogManager.getLogger(TritonElasticSearchClient.class); // configuration
private TritonElasticSearchConfiguration config;
ameba-proteus/triton-server
src/main/java/com/amebame/triton/server/TritonServerContext.java
// Path: src/main/java/com/amebame/triton/config/TritonServerConfiguration.java // public class TritonServerConfiguration { // // // Netty configuration // private TritonNettyConfiguration netty = new TritonNettyConfiguration(); // // // Cassandra // private TritonCassandraConfiguration cassandra; // // // Memcached // private TritonMemcachedConfiguration memcached; // // // Zookeeper // private TritonZookeeperConfiguration zookeeper; // // // ElasticSearch // private TritonElasticSearchConfiguration elasticsearch; // // public TritonServerConfiguration() { // } // // public TritonNettyConfiguration getNetty() { // return netty; // } // // public void setNetty(TritonNettyConfiguration netty) { // this.netty = netty; // } // // public TritonCassandraConfiguration getCassandra() { // return cassandra; // } // // public void setCassandra(TritonCassandraConfiguration cassandra) { // this.cassandra = cassandra; // } // // public TritonMemcachedConfiguration getMemcached() { // return memcached; // } // // public void setMemcached(TritonMemcachedConfiguration memcached) { // this.memcached = memcached; // } // // public TritonZookeeperConfiguration getZookeeper() { // return zookeeper; // } // // public void setZookeeper(TritonZookeeperConfiguration zookeeper) { // this.zookeeper = zookeeper; // } // // public TritonElasticSearchConfiguration getElasticsearch() { // return elasticsearch; // } // // public void setElasticsearch(TritonElasticSearchConfiguration elasticsearch) { // this.elasticsearch = elasticsearch; // } // }
import javax.inject.Inject; import javax.inject.Singleton; import com.amebame.triton.config.TritonServerConfiguration;
package com.amebame.triton.server; @Singleton public class TritonServerContext { private TritonServerMethodMap methodMap; @Inject
// Path: src/main/java/com/amebame/triton/config/TritonServerConfiguration.java // public class TritonServerConfiguration { // // // Netty configuration // private TritonNettyConfiguration netty = new TritonNettyConfiguration(); // // // Cassandra // private TritonCassandraConfiguration cassandra; // // // Memcached // private TritonMemcachedConfiguration memcached; // // // Zookeeper // private TritonZookeeperConfiguration zookeeper; // // // ElasticSearch // private TritonElasticSearchConfiguration elasticsearch; // // public TritonServerConfiguration() { // } // // public TritonNettyConfiguration getNetty() { // return netty; // } // // public void setNetty(TritonNettyConfiguration netty) { // this.netty = netty; // } // // public TritonCassandraConfiguration getCassandra() { // return cassandra; // } // // public void setCassandra(TritonCassandraConfiguration cassandra) { // this.cassandra = cassandra; // } // // public TritonMemcachedConfiguration getMemcached() { // return memcached; // } // // public void setMemcached(TritonMemcachedConfiguration memcached) { // this.memcached = memcached; // } // // public TritonZookeeperConfiguration getZookeeper() { // return zookeeper; // } // // public void setZookeeper(TritonZookeeperConfiguration zookeeper) { // this.zookeeper = zookeeper; // } // // public TritonElasticSearchConfiguration getElasticsearch() { // return elasticsearch; // } // // public void setElasticsearch(TritonElasticSearchConfiguration elasticsearch) { // this.elasticsearch = elasticsearch; // } // } // Path: src/main/java/com/amebame/triton/server/TritonServerContext.java import javax.inject.Inject; import javax.inject.Singleton; import com.amebame.triton.config.TritonServerConfiguration; package com.amebame.triton.server; @Singleton public class TritonServerContext { private TritonServerMethodMap methodMap; @Inject
public TritonServerContext(TritonServerConfiguration config) {
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/memcached/TritonMemcachedSetup.java
// Path: src/main/java/com/amebame/triton/server/TritonServerCleaner.java // @Singleton // public class TritonServerCleaner { // // private static final Logger log = LogManager.getLogger(TritonServerCleaner.class); // // private List<TritonCleaner> cleaners; // // public TritonServerCleaner() { // this.cleaners = new ArrayList<TritonCleaner>(); // } // // public void add(TritonCleaner cleaner) { // this.cleaners.add(cleaner); // } // // public void add(final Runnable runnable) { // this.cleaners.add(new TritonCleaner() { // @Override // public void clean() { // runnable.run(); // } // }); // } // // public void clean() { // for (TritonCleaner cleaner : cleaners) { // try { // cleaner.clean(); // } catch (Exception e) { // log.error("failed to cleanup", e); // } // } // } // } // // Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/memcached/method/TritonMemcachedMethods.java // public class TritonMemcachedMethods { // // private TritonMemcachedClient client; // // @Inject // public TritonMemcachedMethods(TritonMemcachedClient client) { // this.client = client; // } // // @TritonMethod("memcached.get") // public Object get(GetCache data) { // String cluster = data.getCluster(); // if (data.getKey() != null) { // // get by single key // return client.get(cluster, data.getKey(), data.getExpire()); // } else { // // get by multiple keys // return client.getMulti(cluster, data.getKeys()); // } // } // // @TritonMethod("memcached.set") // public boolean set(SetCache data) { // if (data.getKey() != null) { // // set single key-value data // client.set( // data.getCluster(), // data.getKey(), // data.getExpire(), // data.getValue() // ); // } else { // // set multiple data if key is not defined // JsonNode values = data.getValue(); // Iterator<Entry<String, JsonNode>> iterator = values.fields(); // while (iterator.hasNext()) { // Entry<String, JsonNode> entry = iterator.next(); // client.set( // data.getCluster(), // entry.getKey(), // data.getExpire(), // entry.getValue() // ); // } // } // return true; // } // // @TritonMethod("memcached.delete") // public boolean delete(DeleteCache data) { // String cluster = data.getCluster(); // for (String key : data.getKeys()) { // client.delete(cluster, key); // } // return true; // } // }
import javax.inject.Inject; import com.amebame.triton.server.TritonServerCleaner; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.memcached.method.TritonMemcachedMethods;
package com.amebame.triton.service.memcached; public class TritonMemcachedSetup { @Inject private TritonServerCleaner cleaner;
// Path: src/main/java/com/amebame/triton/server/TritonServerCleaner.java // @Singleton // public class TritonServerCleaner { // // private static final Logger log = LogManager.getLogger(TritonServerCleaner.class); // // private List<TritonCleaner> cleaners; // // public TritonServerCleaner() { // this.cleaners = new ArrayList<TritonCleaner>(); // } // // public void add(TritonCleaner cleaner) { // this.cleaners.add(cleaner); // } // // public void add(final Runnable runnable) { // this.cleaners.add(new TritonCleaner() { // @Override // public void clean() { // runnable.run(); // } // }); // } // // public void clean() { // for (TritonCleaner cleaner : cleaners) { // try { // cleaner.clean(); // } catch (Exception e) { // log.error("failed to cleanup", e); // } // } // } // } // // Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/memcached/method/TritonMemcachedMethods.java // public class TritonMemcachedMethods { // // private TritonMemcachedClient client; // // @Inject // public TritonMemcachedMethods(TritonMemcachedClient client) { // this.client = client; // } // // @TritonMethod("memcached.get") // public Object get(GetCache data) { // String cluster = data.getCluster(); // if (data.getKey() != null) { // // get by single key // return client.get(cluster, data.getKey(), data.getExpire()); // } else { // // get by multiple keys // return client.getMulti(cluster, data.getKeys()); // } // } // // @TritonMethod("memcached.set") // public boolean set(SetCache data) { // if (data.getKey() != null) { // // set single key-value data // client.set( // data.getCluster(), // data.getKey(), // data.getExpire(), // data.getValue() // ); // } else { // // set multiple data if key is not defined // JsonNode values = data.getValue(); // Iterator<Entry<String, JsonNode>> iterator = values.fields(); // while (iterator.hasNext()) { // Entry<String, JsonNode> entry = iterator.next(); // client.set( // data.getCluster(), // entry.getKey(), // data.getExpire(), // entry.getValue() // ); // } // } // return true; // } // // @TritonMethod("memcached.delete") // public boolean delete(DeleteCache data) { // String cluster = data.getCluster(); // for (String key : data.getKeys()) { // client.delete(cluster, key); // } // return true; // } // } // Path: src/main/java/com/amebame/triton/service/memcached/TritonMemcachedSetup.java import javax.inject.Inject; import com.amebame.triton.server.TritonServerCleaner; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.memcached.method.TritonMemcachedMethods; package com.amebame.triton.service.memcached; public class TritonMemcachedSetup { @Inject private TritonServerCleaner cleaner;
@Inject private TritonServerContext context;
ameba-proteus/triton-server
src/main/java/com/amebame/triton/service/memcached/TritonMemcachedSetup.java
// Path: src/main/java/com/amebame/triton/server/TritonServerCleaner.java // @Singleton // public class TritonServerCleaner { // // private static final Logger log = LogManager.getLogger(TritonServerCleaner.class); // // private List<TritonCleaner> cleaners; // // public TritonServerCleaner() { // this.cleaners = new ArrayList<TritonCleaner>(); // } // // public void add(TritonCleaner cleaner) { // this.cleaners.add(cleaner); // } // // public void add(final Runnable runnable) { // this.cleaners.add(new TritonCleaner() { // @Override // public void clean() { // runnable.run(); // } // }); // } // // public void clean() { // for (TritonCleaner cleaner : cleaners) { // try { // cleaner.clean(); // } catch (Exception e) { // log.error("failed to cleanup", e); // } // } // } // } // // Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/memcached/method/TritonMemcachedMethods.java // public class TritonMemcachedMethods { // // private TritonMemcachedClient client; // // @Inject // public TritonMemcachedMethods(TritonMemcachedClient client) { // this.client = client; // } // // @TritonMethod("memcached.get") // public Object get(GetCache data) { // String cluster = data.getCluster(); // if (data.getKey() != null) { // // get by single key // return client.get(cluster, data.getKey(), data.getExpire()); // } else { // // get by multiple keys // return client.getMulti(cluster, data.getKeys()); // } // } // // @TritonMethod("memcached.set") // public boolean set(SetCache data) { // if (data.getKey() != null) { // // set single key-value data // client.set( // data.getCluster(), // data.getKey(), // data.getExpire(), // data.getValue() // ); // } else { // // set multiple data if key is not defined // JsonNode values = data.getValue(); // Iterator<Entry<String, JsonNode>> iterator = values.fields(); // while (iterator.hasNext()) { // Entry<String, JsonNode> entry = iterator.next(); // client.set( // data.getCluster(), // entry.getKey(), // data.getExpire(), // entry.getValue() // ); // } // } // return true; // } // // @TritonMethod("memcached.delete") // public boolean delete(DeleteCache data) { // String cluster = data.getCluster(); // for (String key : data.getKeys()) { // client.delete(cluster, key); // } // return true; // } // }
import javax.inject.Inject; import com.amebame.triton.server.TritonServerCleaner; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.memcached.method.TritonMemcachedMethods;
package com.amebame.triton.service.memcached; public class TritonMemcachedSetup { @Inject private TritonServerCleaner cleaner; @Inject private TritonServerContext context; @Inject private TritonMemcachedClient client;
// Path: src/main/java/com/amebame/triton/server/TritonServerCleaner.java // @Singleton // public class TritonServerCleaner { // // private static final Logger log = LogManager.getLogger(TritonServerCleaner.class); // // private List<TritonCleaner> cleaners; // // public TritonServerCleaner() { // this.cleaners = new ArrayList<TritonCleaner>(); // } // // public void add(TritonCleaner cleaner) { // this.cleaners.add(cleaner); // } // // public void add(final Runnable runnable) { // this.cleaners.add(new TritonCleaner() { // @Override // public void clean() { // runnable.run(); // } // }); // } // // public void clean() { // for (TritonCleaner cleaner : cleaners) { // try { // cleaner.clean(); // } catch (Exception e) { // log.error("failed to cleanup", e); // } // } // } // } // // Path: src/main/java/com/amebame/triton/server/TritonServerContext.java // @Singleton // public class TritonServerContext { // // private TritonServerMethodMap methodMap; // // @Inject // public TritonServerContext(TritonServerConfiguration config) { // methodMap = new TritonServerMethodMap(); // } // // /** // * Add server methods from the target object // * @param target // */ // public void addServerMethod(Object target) { // methodMap.register(target); // } // // /** // * Get server method by name // * @param name // * @return // */ // public TritonServerMethod getServerMethod(String name) { // return methodMap.getMethod(name); // } // } // // Path: src/main/java/com/amebame/triton/service/memcached/method/TritonMemcachedMethods.java // public class TritonMemcachedMethods { // // private TritonMemcachedClient client; // // @Inject // public TritonMemcachedMethods(TritonMemcachedClient client) { // this.client = client; // } // // @TritonMethod("memcached.get") // public Object get(GetCache data) { // String cluster = data.getCluster(); // if (data.getKey() != null) { // // get by single key // return client.get(cluster, data.getKey(), data.getExpire()); // } else { // // get by multiple keys // return client.getMulti(cluster, data.getKeys()); // } // } // // @TritonMethod("memcached.set") // public boolean set(SetCache data) { // if (data.getKey() != null) { // // set single key-value data // client.set( // data.getCluster(), // data.getKey(), // data.getExpire(), // data.getValue() // ); // } else { // // set multiple data if key is not defined // JsonNode values = data.getValue(); // Iterator<Entry<String, JsonNode>> iterator = values.fields(); // while (iterator.hasNext()) { // Entry<String, JsonNode> entry = iterator.next(); // client.set( // data.getCluster(), // entry.getKey(), // data.getExpire(), // entry.getValue() // ); // } // } // return true; // } // // @TritonMethod("memcached.delete") // public boolean delete(DeleteCache data) { // String cluster = data.getCluster(); // for (String key : data.getKeys()) { // client.delete(cluster, key); // } // return true; // } // } // Path: src/main/java/com/amebame/triton/service/memcached/TritonMemcachedSetup.java import javax.inject.Inject; import com.amebame.triton.server.TritonServerCleaner; import com.amebame.triton.server.TritonServerContext; import com.amebame.triton.service.memcached.method.TritonMemcachedMethods; package com.amebame.triton.service.memcached; public class TritonMemcachedSetup { @Inject private TritonServerCleaner cleaner; @Inject private TritonServerContext context; @Inject private TritonMemcachedClient client;
@Inject private TritonMemcachedMethods methods;
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java
// Path: Source/src/de/tum/in/www1/jReto/util/RetryableActionExecutor.java // public static interface RetryableAction { // /** // * Runs the RetryableAction. // * // * @param attemptNumber The number of times the action has been attempted. // * */ // void run(int attemptNumber); // }
import java.util.concurrent.Executor; import de.tum.in.www1.jReto.util.RetryableActionExecutor.RetryableAction;
package de.tum.in.www1.jReto.util; /** * A StartStopHelper is a helper class for objects that have a "started" and "stopped" state, where both the transition to the "started" and "failed" state * (ie. starting and stopping something) may fail and should be retried. Can also be used when the object switches from the "started" to the "stopped" state unexpectedly, and the "started" state should be restored. * * The user of this class should notify the StartStopHelper of state changes by calling onStart() and onStop(). * */ public class StartStopHelper { /** * Represents the desired states this class should help reach. * */ private static enum State { Started, Stopped } /** A RetryableActionExecutor that attempts to exectute the start action */ private final RetryableActionExecutor starter; /** A RetryableActionExecutor that attempts to exectute the stop action */ private final RetryableActionExecutor stopper; /** The state that should be reached. * * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call * the start action until it is notified about a successful start via onStart(). */ private State desiredState = State.Stopped; /** * Creates a new StartStopHelper. * * @param startAction The start action * @param stopAction The stop action * @param timerSettings The timer settings used to retry the start and stop actions * @param executor The executor to execute the start and stop action on. * */
// Path: Source/src/de/tum/in/www1/jReto/util/RetryableActionExecutor.java // public static interface RetryableAction { // /** // * Runs the RetryableAction. // * // * @param attemptNumber The number of times the action has been attempted. // * */ // void run(int attemptNumber); // } // Path: Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java import java.util.concurrent.Executor; import de.tum.in.www1.jReto.util.RetryableActionExecutor.RetryableAction; package de.tum.in.www1.jReto.util; /** * A StartStopHelper is a helper class for objects that have a "started" and "stopped" state, where both the transition to the "started" and "failed" state * (ie. starting and stopping something) may fail and should be retried. Can also be used when the object switches from the "started" to the "stopped" state unexpectedly, and the "started" state should be restored. * * The user of this class should notify the StartStopHelper of state changes by calling onStart() and onStop(). * */ public class StartStopHelper { /** * Represents the desired states this class should help reach. * */ private static enum State { Started, Stopped } /** A RetryableActionExecutor that attempts to exectute the start action */ private final RetryableActionExecutor starter; /** A RetryableActionExecutor that attempts to exectute the stop action */ private final RetryableActionExecutor stopper; /** The state that should be reached. * * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call * the start action until it is notified about a successful start via onStart(). */ private State desiredState = State.Stopped; /** * Creates a new StartStopHelper. * * @param startAction The start action * @param stopAction The stop action * @param timerSettings The timer settings used to retry the start and stop actions * @param executor The executor to execute the start and stop action on. * */
public StartStopHelper(RetryableAction startAction, RetryableAction stopAction, Timer.BackoffTimerSettings timerSettings, Executor executor) {
ls1intum/jReto
Source/test/jReto/module/dummy/DummyAddress.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Connection; import jReto.util.RunLoop;
package jReto.module.dummy; public class DummyAddress implements Address { public static interface DummySocket { void write(ByteBuffer data); void close(); void sabotage(); } public class ForwardingConnection { private DummyConnection inConnection; private DummyConnection outConnection; private DummyAdvertiser advertiser;
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/module/dummy/DummyAddress.java import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Connection; import jReto.util.RunLoop; package jReto.module.dummy; public class DummyAddress implements Address { public static interface DummySocket { void write(ByteBuffer data); void close(); void sabotage(); } public class ForwardingConnection { private DummyConnection inConnection; private DummyConnection outConnection; private DummyAdvertiser advertiser;
public ForwardingConnection(final DummyNetworkInterface networkInterface, DummyAdvertiser advertiser, RunLoop runloop) {
ls1intum/jReto
Source/test/jReto/module/dummy/DummyAddress.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Connection; import jReto.util.RunLoop;
outConnection.onSabotage(); } }); } public void advertiseConnection() { getInConnection().setConnected(true); this.advertiser.onConnection(getInConnection()); } public DummyConnection getOutConnection() { return this.outConnection; } public DummyConnection getInConnection() { return this.inConnection; } } private DummyNetworkInterface networkInterface; private DummyAdvertiser advertiser; private RunLoop runloop; public DummyAddress(DummyNetworkInterface networkInterface, DummyAdvertiser advertiser, RunLoop runloop) { this.networkInterface = networkInterface; this.advertiser = advertiser; this.runloop = runloop; } @Override
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/module/dummy/DummyAddress.java import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Connection; import jReto.util.RunLoop; outConnection.onSabotage(); } }); } public void advertiseConnection() { getInConnection().setConnected(true); this.advertiser.onConnection(getInConnection()); } public DummyConnection getOutConnection() { return this.outConnection; } public DummyConnection getInConnection() { return this.inConnection; } } private DummyNetworkInterface networkInterface; private DummyAdvertiser advertiser; private RunLoop runloop; public DummyAddress(DummyNetworkInterface networkInterface, DummyAdvertiser advertiser, RunLoop runloop) { this.networkInterface = networkInterface; this.advertiser = advertiser; this.runloop = runloop; } @Override
public Connection createConnection() {
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class NowReachableInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new NowReachableInformation object. */ // public NowReachableInformation(T node, T nextHop, double cost) { // this.node = node; // this.nextHop = nextHop; // this.cost = cost; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class RouteChangedInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The previous total cost for reaching this node. */ // public final double oldCost; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new RouteChangedInformation object. */ // public RouteChangedInformation(T node, T nextHop, double oldCost, double cost) { // this.node = node; // this.nextHop = nextHop; // this.oldCost = oldCost; // this.cost = cost; // } // }
import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.DirectedWeightedPseudograph; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.NowReachableInformation; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.RouteChangedInformation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map;
package de.tum.in.www1.jReto.routing.algorithm; /** * A LinkStateRoutingTable manages a graph of nodes in the network with type T. * * Link state routing works by gathering information about the full network topology; i.e. for each node in the network, * all of its neighbors are known eventually. Based on this information, the next hop to a node can be computed using a shortest path algorithm. * * Advantages of link state routing (as opposed to distance vector routing) include that link state routing converges rather quickly and * is not subject to the count-to-infinity problem; hence, no measures to combat this problem need to be taken. As the full network topology * is known to every node, rather advanced routing techniques can be implemented. * * Disadvantages include that the link state information needs to be flooded through the network, causing higher overhead than link state protocols. * The memory and computational requirements are also higher. * * The LinkStateRoutingTable class is not responsible for distributing link state information across the network; * however, it processes received link state information and can provide link state information for the local peer. * * This routing table is designed to compute all next hops and path costs for all known nodes every time when new * network topology information becomes available (e.g. neighbors added, updated or lost, and link state information received from * any peer). * * These changes in the routing table are returned as a LinkStateRoutingTable.Change object. This object includes information about * nodes that became reachable or unreachable, or information about route changes to nodes that were reachable before. * */ public class LinkStateRoutingTable<T> { /** * A Change object contains changes that occurred in the routing table caused by some operation. * */ public static class Change<T> { /** * Contains information about nodes that became reachable. * */
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class NowReachableInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new NowReachableInformation object. */ // public NowReachableInformation(T node, T nextHop, double cost) { // this.node = node; // this.nextHop = nextHop; // this.cost = cost; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class RouteChangedInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The previous total cost for reaching this node. */ // public final double oldCost; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new RouteChangedInformation object. */ // public RouteChangedInformation(T node, T nextHop, double oldCost, double cost) { // this.node = node; // this.nextHop = nextHop; // this.oldCost = oldCost; // this.cost = cost; // } // } // Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.DirectedWeightedPseudograph; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.NowReachableInformation; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.RouteChangedInformation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map; package de.tum.in.www1.jReto.routing.algorithm; /** * A LinkStateRoutingTable manages a graph of nodes in the network with type T. * * Link state routing works by gathering information about the full network topology; i.e. for each node in the network, * all of its neighbors are known eventually. Based on this information, the next hop to a node can be computed using a shortest path algorithm. * * Advantages of link state routing (as opposed to distance vector routing) include that link state routing converges rather quickly and * is not subject to the count-to-infinity problem; hence, no measures to combat this problem need to be taken. As the full network topology * is known to every node, rather advanced routing techniques can be implemented. * * Disadvantages include that the link state information needs to be flooded through the network, causing higher overhead than link state protocols. * The memory and computational requirements are also higher. * * The LinkStateRoutingTable class is not responsible for distributing link state information across the network; * however, it processes received link state information and can provide link state information for the local peer. * * This routing table is designed to compute all next hops and path costs for all known nodes every time when new * network topology information becomes available (e.g. neighbors added, updated or lost, and link state information received from * any peer). * * These changes in the routing table are returned as a LinkStateRoutingTable.Change object. This object includes information about * nodes that became reachable or unreachable, or information about route changes to nodes that were reachable before. * */ public class LinkStateRoutingTable<T> { /** * A Change object contains changes that occurred in the routing table caused by some operation. * */ public static class Change<T> { /** * Contains information about nodes that became reachable. * */
public static class NowReachableInformation<T> {
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class NowReachableInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new NowReachableInformation object. */ // public NowReachableInformation(T node, T nextHop, double cost) { // this.node = node; // this.nextHop = nextHop; // this.cost = cost; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class RouteChangedInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The previous total cost for reaching this node. */ // public final double oldCost; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new RouteChangedInformation object. */ // public RouteChangedInformation(T node, T nextHop, double oldCost, double cost) { // this.node = node; // this.nextHop = nextHop; // this.oldCost = oldCost; // this.cost = cost; // } // }
import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.DirectedWeightedPseudograph; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.NowReachableInformation; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.RouteChangedInformation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map;
package de.tum.in.www1.jReto.routing.algorithm; /** * A LinkStateRoutingTable manages a graph of nodes in the network with type T. * * Link state routing works by gathering information about the full network topology; i.e. for each node in the network, * all of its neighbors are known eventually. Based on this information, the next hop to a node can be computed using a shortest path algorithm. * * Advantages of link state routing (as opposed to distance vector routing) include that link state routing converges rather quickly and * is not subject to the count-to-infinity problem; hence, no measures to combat this problem need to be taken. As the full network topology * is known to every node, rather advanced routing techniques can be implemented. * * Disadvantages include that the link state information needs to be flooded through the network, causing higher overhead than link state protocols. * The memory and computational requirements are also higher. * * The LinkStateRoutingTable class is not responsible for distributing link state information across the network; * however, it processes received link state information and can provide link state information for the local peer. * * This routing table is designed to compute all next hops and path costs for all known nodes every time when new * network topology information becomes available (e.g. neighbors added, updated or lost, and link state information received from * any peer). * * These changes in the routing table are returned as a LinkStateRoutingTable.Change object. This object includes information about * nodes that became reachable or unreachable, or information about route changes to nodes that were reachable before. * */ public class LinkStateRoutingTable<T> { /** * A Change object contains changes that occurred in the routing table caused by some operation. * */ public static class Change<T> { /** * Contains information about nodes that became reachable. * */ public static class NowReachableInformation<T> { /** The node that became reachable */ public final T node; /** The node that is the next hop for reaching this node. */ public final T nextHop; /** The total cost for reaching this node. */ public final double cost; /** Constructs a new NowReachableInformation object. */ public NowReachableInformation(T node, T nextHop, double cost) { this.node = node; this.nextHop = nextHop; this.cost = cost; } } /** * Contains informatiown about nodes that have changed routes. * */
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class NowReachableInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new NowReachableInformation object. */ // public NowReachableInformation(T node, T nextHop, double cost) { // this.node = node; // this.nextHop = nextHop; // this.cost = cost; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java // public static class RouteChangedInformation<T> { // /** The node that became reachable */ // public final T node; // /** The node that is the next hop for reaching this node. */ // public final T nextHop; // /** The previous total cost for reaching this node. */ // public final double oldCost; // /** The total cost for reaching this node. */ // public final double cost; // // /** Constructs a new RouteChangedInformation object. */ // public RouteChangedInformation(T node, T nextHop, double oldCost, double cost) { // this.node = node; // this.nextHop = nextHop; // this.oldCost = oldCost; // this.cost = cost; // } // } // Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/LinkStateRoutingTable.java import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.DirectedWeightedPseudograph; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.NowReachableInformation; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable.Change.RouteChangedInformation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map; package de.tum.in.www1.jReto.routing.algorithm; /** * A LinkStateRoutingTable manages a graph of nodes in the network with type T. * * Link state routing works by gathering information about the full network topology; i.e. for each node in the network, * all of its neighbors are known eventually. Based on this information, the next hop to a node can be computed using a shortest path algorithm. * * Advantages of link state routing (as opposed to distance vector routing) include that link state routing converges rather quickly and * is not subject to the count-to-infinity problem; hence, no measures to combat this problem need to be taken. As the full network topology * is known to every node, rather advanced routing techniques can be implemented. * * Disadvantages include that the link state information needs to be flooded through the network, causing higher overhead than link state protocols. * The memory and computational requirements are also higher. * * The LinkStateRoutingTable class is not responsible for distributing link state information across the network; * however, it processes received link state information and can provide link state information for the local peer. * * This routing table is designed to compute all next hops and path costs for all known nodes every time when new * network topology information becomes available (e.g. neighbors added, updated or lost, and link state information received from * any peer). * * These changes in the routing table are returned as a LinkStateRoutingTable.Change object. This object includes information about * nodes that became reachable or unreachable, or information about route changes to nodes that were reachable before. * */ public class LinkStateRoutingTable<T> { /** * A Change object contains changes that occurred in the routing table caused by some operation. * */ public static class Change<T> { /** * Contains information about nodes that became reachable. * */ public static class NowReachableInformation<T> { /** The node that became reachable */ public final T node; /** The node that is the next hop for reaching this node. */ public final T nextHop; /** The total cost for reaching this node. */ public final double cost; /** Constructs a new NowReachableInformation object. */ public NowReachableInformation(T node, T nextHop, double cost) { this.node = node; this.nextHop = nextHop; this.cost = cost; } } /** * Contains informatiown about nodes that have changed routes. * */
public static class RouteChangedInformation<T> {
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/connectivity/OutTransfer.java
// Path: Source/src/de/tum/in/www1/jReto/Connection.java // public static interface DataProvider { // ByteBuffer getData(int offset, int length); // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // }
import java.nio.ByteBuffer; import java.util.UUID; import de.tum.in.www1.jReto.Connection.DataProvider; import de.tum.in.www1.jReto.connectivity.packet.DataPacket;
package de.tum.in.www1.jReto.connectivity; /** * An OutTransfer represents a data transfer from the local peer to a remote peer. You can obtain one by calling the connection's send method. */ public class OutTransfer extends Transfer { private DataProvider dataSource; public OutTransfer(TransferManager transferManager, int dataLenght, DataProvider dataSource, UUID identifier) { super(transferManager, dataLenght, identifier); this.dataSource = dataSource; } public DataProvider getDataSource() { return this.dataSource; }
// Path: Source/src/de/tum/in/www1/jReto/Connection.java // public static interface DataProvider { // ByteBuffer getData(int offset, int length); // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // } // Path: Source/src/de/tum/in/www1/jReto/connectivity/OutTransfer.java import java.nio.ByteBuffer; import java.util.UUID; import de.tum.in.www1.jReto.Connection.DataProvider; import de.tum.in.www1.jReto.connectivity.packet.DataPacket; package de.tum.in.www1.jReto.connectivity; /** * An OutTransfer represents a data transfer from the local peer to a remote peer. You can obtain one by calling the connection's send method. */ public class OutTransfer extends Transfer { private DataProvider dataSource; public OutTransfer(TransferManager transferManager, int dataLenght, DataProvider dataSource, UUID identifier) { super(transferManager, dataLenght, identifier); this.dataSource = dataSource; } public DataProvider getDataSource() { return this.dataSource; }
DataPacket nextPacket(int length) {
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/SinglePacketHelper.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // }
import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Connection; import de.tum.in.www1.jReto.packet.Packet;
package de.tum.in.www1.jReto.routing; public class SinglePacketHelper { public static interface OnPacketHandler { void onPacket(ByteBuffer data); } public static interface OnSuccessHandler { void onSuccess(); } public static interface OnFailHandler { void onFail(); }
// Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // } // Path: Source/src/de/tum/in/www1/jReto/routing/SinglePacketHelper.java import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Connection; import de.tum.in.www1.jReto.packet.Packet; package de.tum.in.www1.jReto.routing; public class SinglePacketHelper { public static interface OnPacketHandler { void onPacket(ByteBuffer data); } public static interface OnSuccessHandler { void onSuccess(); } public static interface OnFailHandler { void onFail(); }
public static void read(Connection connection, final OnPacketHandler packetHandler, final OnFailHandler onFail) {
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/SinglePacketHelper.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // }
import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Connection; import de.tum.in.www1.jReto.packet.Packet;
private int packetsReceived = 0; @Override public void onDataSent(Connection connection) {} @Override public void onDataReceived(Connection connection, ByteBuffer data) { this.packetsReceived++; if (packetsReceived == packetCount) { connection.setHandler(null); } packetHandler.onPacket(data); if (packetsReceived == packetCount) { onSuccess.onSuccess(); } } @Override public void onConnect(Connection connection) {} @Override public void onClose(Connection connection) { connection.setHandler(null); onFail.onFail(); } }); }
// Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // } // Path: Source/src/de/tum/in/www1/jReto/routing/SinglePacketHelper.java import java.nio.ByteBuffer; import de.tum.in.www1.jReto.module.api.Connection; import de.tum.in.www1.jReto.packet.Packet; private int packetsReceived = 0; @Override public void onDataSent(Connection connection) {} @Override public void onDataReceived(Connection connection, ByteBuffer data) { this.packetsReceived++; if (packetsReceived == packetCount) { connection.setHandler(null); } packetHandler.onPacket(data); if (packetsReceived == packetCount) { onSuccess.onSuccess(); } } @Override public void onConnect(Connection connection) {} @Override public void onClose(Connection connection) { connection.setHandler(null); onFail.onFail(); } }); }
public static void write(Connection connection, final Packet packet, final OnSuccessHandler onSuccess, final OnFailHandler onFail) {
ls1intum/jReto
Source/test/jReto/module/dummy/DummyModule.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Module.java // public interface Module { // /** The Module's advertiser */ // Advertiser getAdvertiser(); // /** The Module's browser */ // Browser getBrowser(); // /** // * Sets an Executor for this module. // * It is expected that delegate methods will be called on this Executor. // */ // void setExecutor(Executor executor); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Advertiser; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.module.api.Module; import jReto.util.RunLoop;
package jReto.module.dummy; public class DummyModule implements Module { private Advertiser advertiser;
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Module.java // public interface Module { // /** The Module's advertiser */ // Advertiser getAdvertiser(); // /** The Module's browser */ // Browser getBrowser(); // /** // * Sets an Executor for this module. // * It is expected that delegate methods will be called on this Executor. // */ // void setExecutor(Executor executor); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/module/dummy/DummyModule.java import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Advertiser; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.module.api.Module; import jReto.util.RunLoop; package jReto.module.dummy; public class DummyModule implements Module { private Advertiser advertiser;
private Browser browser;
ls1intum/jReto
Source/test/jReto/module/dummy/DummyModule.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Module.java // public interface Module { // /** The Module's advertiser */ // Advertiser getAdvertiser(); // /** The Module's browser */ // Browser getBrowser(); // /** // * Sets an Executor for this module. // * It is expected that delegate methods will be called on this Executor. // */ // void setExecutor(Executor executor); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Advertiser; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.module.api.Module; import jReto.util.RunLoop;
package jReto.module.dummy; public class DummyModule implements Module { private Advertiser advertiser; private Browser browser;
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Module.java // public interface Module { // /** The Module's advertiser */ // Advertiser getAdvertiser(); // /** The Module's browser */ // Browser getBrowser(); // /** // * Sets an Executor for this module. // * It is expected that delegate methods will be called on this Executor. // */ // void setExecutor(Executor executor); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/module/dummy/DummyModule.java import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Advertiser; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.module.api.Module; import jReto.util.RunLoop; package jReto.module.dummy; public class DummyModule implements Module { private Advertiser advertiser; private Browser browser;
public DummyModule(DummyNetworkInterface networkInterface, RunLoop runloop) {
ls1intum/jReto
Source/test/jReto/unit/FloodingPacketTest.java
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // }
import static org.junit.Assert.*; import java.util.UUID; import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.packet.DataPacket; import de.tum.in.www1.jReto.routing.packets.FloodingPacket;
package jReto.unit; public class FloodingPacketTest { @Test public void test() { UUID identifier = UUID.randomUUID();
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // } // Path: Source/test/jReto/unit/FloodingPacketTest.java import static org.junit.Assert.*; import java.util.UUID; import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.packet.DataPacket; import de.tum.in.www1.jReto.routing.packets.FloodingPacket; package jReto.unit; public class FloodingPacketTest { @Test public void test() { UUID identifier = UUID.randomUUID();
DataPacket packet = new DataPacket(TestData.generate(16));
ls1intum/jReto
Source/test/jReto/unit/FloodingPacketTest.java
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // }
import static org.junit.Assert.*; import java.util.UUID; import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.packet.DataPacket; import de.tum.in.www1.jReto.routing.packets.FloodingPacket;
package jReto.unit; public class FloodingPacketTest { @Test public void test() { UUID identifier = UUID.randomUUID();
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // } // Path: Source/test/jReto/unit/FloodingPacketTest.java import static org.junit.Assert.*; import java.util.UUID; import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.packet.DataPacket; import de.tum.in.www1.jReto.routing.packets.FloodingPacket; package jReto.unit; public class FloodingPacketTest { @Test public void test() { UUID identifier = UUID.randomUUID();
DataPacket packet = new DataPacket(TestData.generate(16));
ls1intum/jReto
Source/test/jReto/unit/FloodingPacketTest.java
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // }
import static org.junit.Assert.*; import java.util.UUID; import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.packet.DataPacket; import de.tum.in.www1.jReto.routing.packets.FloodingPacket;
package jReto.unit; public class FloodingPacketTest { @Test public void test() { UUID identifier = UUID.randomUUID(); DataPacket packet = new DataPacket(TestData.generate(16));
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/packet/DataPacket.java // public class DataPacket implements Packet { // public final static PacketType TYPE = PacketType.DATA_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE; // // public final ByteBuffer data; // // public DataPacket(ByteBuffer data) { // this.data = data; // } // // public static DataPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new DataPacket(reader.getRemainingData()); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.data.remaining()); // data.add(TYPE); // data.add(this.data); // return data.getData(); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // } // Path: Source/test/jReto/unit/FloodingPacketTest.java import static org.junit.Assert.*; import java.util.UUID; import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.packet.DataPacket; import de.tum.in.www1.jReto.routing.packets.FloodingPacket; package jReto.unit; public class FloodingPacketTest { @Test public void test() { UUID identifier = UUID.randomUUID(); DataPacket packet = new DataPacket(TestData.generate(16));
FloodingPacket flood = new FloodingPacket(identifier, 1, packet.serialize());
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/managed_module/ManagedBrowser.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java // public class StartStopHelper { // /** // * Represents the desired states this class should help reach. // * */ // private static enum State { // Started, // Stopped // } // // /** A RetryableActionExecutor that attempts to exectute the start action */ // private final RetryableActionExecutor starter; // /** A RetryableActionExecutor that attempts to exectute the stop action */ // private final RetryableActionExecutor stopper; // // /** The state that should be reached. // * // * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call // * the start action until it is notified about a successful start via onStart(). */ // private State desiredState = State.Stopped; // // /** // * Creates a new StartStopHelper. // * // * @param startAction The start action // * @param stopAction The stop action // * @param timerSettings The timer settings used to retry the start and stop actions // * @param executor The executor to execute the start and stop action on. // * */ // public StartStopHelper(RetryableAction startAction, RetryableAction stopAction, Timer.BackoffTimerSettings timerSettings, Executor executor) { // this.starter = new RetryableActionExecutor(startAction, timerSettings, executor); // this.stopper = new RetryableActionExecutor(stopAction, timerSettings, executor); // } // // /** // * Runs the startAction in delays until onStart is called. // * */ // public void start() { // this.desiredState = State.Started; // // this.stopper.stop(); // this.starter.start(); // } // /** // * Runs the startAction in delays until onStart is called. // * */ // public void stop() { // this.desiredState = State.Stopped; // // this.starter.stop(); // this.stopper.start(); // } // // /** // * Call this method when the startAction succeeds, or a start occurs for another reason. Stops calling the start action. Starts calling the stop action if the stop() was called last (as opposed to start()). // * */ // public void onStart() { // this.starter.stop(); // if (this.desiredState == State.Stopped) this.stopper.start(); // } // /** // * Call this method when the stopAction succeeds, or a start occurs for another reason. Stops calling the stop action. Starts calling the start action if the start() was called last (as opposed to stop()). // * */ // public void onStop() { // this.stopper.stop(); // if (this.desiredState == State.Started) this.starter.start(); // } // }
import java.util.Date; import java.util.UUID; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.util.StartStopHelper;
package de.tum.in.www1.jReto.routing.managed_module; /** * A ManagedBrowser automatically attempts to restart a Browser if starting the browser failed. The same concept applies to stopping the Browser. * */ public class ManagedBrowser implements Browser, Browser.Handler{ private final Browser browser;
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java // public class StartStopHelper { // /** // * Represents the desired states this class should help reach. // * */ // private static enum State { // Started, // Stopped // } // // /** A RetryableActionExecutor that attempts to exectute the start action */ // private final RetryableActionExecutor starter; // /** A RetryableActionExecutor that attempts to exectute the stop action */ // private final RetryableActionExecutor stopper; // // /** The state that should be reached. // * // * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call // * the start action until it is notified about a successful start via onStart(). */ // private State desiredState = State.Stopped; // // /** // * Creates a new StartStopHelper. // * // * @param startAction The start action // * @param stopAction The stop action // * @param timerSettings The timer settings used to retry the start and stop actions // * @param executor The executor to execute the start and stop action on. // * */ // public StartStopHelper(RetryableAction startAction, RetryableAction stopAction, Timer.BackoffTimerSettings timerSettings, Executor executor) { // this.starter = new RetryableActionExecutor(startAction, timerSettings, executor); // this.stopper = new RetryableActionExecutor(stopAction, timerSettings, executor); // } // // /** // * Runs the startAction in delays until onStart is called. // * */ // public void start() { // this.desiredState = State.Started; // // this.stopper.stop(); // this.starter.start(); // } // /** // * Runs the startAction in delays until onStart is called. // * */ // public void stop() { // this.desiredState = State.Stopped; // // this.starter.stop(); // this.stopper.start(); // } // // /** // * Call this method when the startAction succeeds, or a start occurs for another reason. Stops calling the start action. Starts calling the stop action if the stop() was called last (as opposed to start()). // * */ // public void onStart() { // this.starter.stop(); // if (this.desiredState == State.Stopped) this.stopper.start(); // } // /** // * Call this method when the stopAction succeeds, or a start occurs for another reason. Stops calling the stop action. Starts calling the start action if the start() was called last (as opposed to stop()). // * */ // public void onStop() { // this.stopper.stop(); // if (this.desiredState == State.Started) this.starter.start(); // } // } // Path: Source/src/de/tum/in/www1/jReto/routing/managed_module/ManagedBrowser.java import java.util.Date; import java.util.UUID; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.util.StartStopHelper; package de.tum.in.www1.jReto.routing.managed_module; /** * A ManagedBrowser automatically attempts to restart a Browser if starting the browser failed. The same concept applies to stopping the Browser. * */ public class ManagedBrowser implements Browser, Browser.Handler{ private final Browser browser;
private final StartStopHelper startStopHelper;
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/managed_module/ManagedBrowser.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java // public class StartStopHelper { // /** // * Represents the desired states this class should help reach. // * */ // private static enum State { // Started, // Stopped // } // // /** A RetryableActionExecutor that attempts to exectute the start action */ // private final RetryableActionExecutor starter; // /** A RetryableActionExecutor that attempts to exectute the stop action */ // private final RetryableActionExecutor stopper; // // /** The state that should be reached. // * // * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call // * the start action until it is notified about a successful start via onStart(). */ // private State desiredState = State.Stopped; // // /** // * Creates a new StartStopHelper. // * // * @param startAction The start action // * @param stopAction The stop action // * @param timerSettings The timer settings used to retry the start and stop actions // * @param executor The executor to execute the start and stop action on. // * */ // public StartStopHelper(RetryableAction startAction, RetryableAction stopAction, Timer.BackoffTimerSettings timerSettings, Executor executor) { // this.starter = new RetryableActionExecutor(startAction, timerSettings, executor); // this.stopper = new RetryableActionExecutor(stopAction, timerSettings, executor); // } // // /** // * Runs the startAction in delays until onStart is called. // * */ // public void start() { // this.desiredState = State.Started; // // this.stopper.stop(); // this.starter.start(); // } // /** // * Runs the startAction in delays until onStart is called. // * */ // public void stop() { // this.desiredState = State.Stopped; // // this.starter.stop(); // this.stopper.start(); // } // // /** // * Call this method when the startAction succeeds, or a start occurs for another reason. Stops calling the start action. Starts calling the stop action if the stop() was called last (as opposed to start()). // * */ // public void onStart() { // this.starter.stop(); // if (this.desiredState == State.Stopped) this.stopper.start(); // } // /** // * Call this method when the stopAction succeeds, or a start occurs for another reason. Stops calling the stop action. Starts calling the start action if the start() was called last (as opposed to stop()). // * */ // public void onStop() { // this.stopper.stop(); // if (this.desiredState == State.Started) this.starter.start(); // } // }
import java.util.Date; import java.util.UUID; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.util.StartStopHelper;
attemptNumber -> attemptStop(attemptNumber), ManagedModule.DEFAULT_TIMER_SETTINGS, executor ); } private void attemptStart(int attemptNumber) { if (attemptNumber > 1) System.out.println(new Date()+": Retrying to start browser (attempt "+attemptNumber+"): "+ this.browser); this.browser.startBrowsing(); } private void attemptStop(int attemptNumber) { if (attemptNumber > 1) System.out.println(new Date()+": Retrying to stop browser (attempt "+attemptNumber+"): "+ this.browser); this.browser.stopBrowsing(); } @Override public void onBrowsingStarted(Browser browser) { this.startStopHelper.onStart(); this.handler.onBrowsingStarted(this); } @Override public void onBrowsingStopped(Browser browser, Object error) { this.startStopHelper.onStop(); this.handler.onBrowsingStopped(this, error); } @Override
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java // public class StartStopHelper { // /** // * Represents the desired states this class should help reach. // * */ // private static enum State { // Started, // Stopped // } // // /** A RetryableActionExecutor that attempts to exectute the start action */ // private final RetryableActionExecutor starter; // /** A RetryableActionExecutor that attempts to exectute the stop action */ // private final RetryableActionExecutor stopper; // // /** The state that should be reached. // * // * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call // * the start action until it is notified about a successful start via onStart(). */ // private State desiredState = State.Stopped; // // /** // * Creates a new StartStopHelper. // * // * @param startAction The start action // * @param stopAction The stop action // * @param timerSettings The timer settings used to retry the start and stop actions // * @param executor The executor to execute the start and stop action on. // * */ // public StartStopHelper(RetryableAction startAction, RetryableAction stopAction, Timer.BackoffTimerSettings timerSettings, Executor executor) { // this.starter = new RetryableActionExecutor(startAction, timerSettings, executor); // this.stopper = new RetryableActionExecutor(stopAction, timerSettings, executor); // } // // /** // * Runs the startAction in delays until onStart is called. // * */ // public void start() { // this.desiredState = State.Started; // // this.stopper.stop(); // this.starter.start(); // } // /** // * Runs the startAction in delays until onStart is called. // * */ // public void stop() { // this.desiredState = State.Stopped; // // this.starter.stop(); // this.stopper.start(); // } // // /** // * Call this method when the startAction succeeds, or a start occurs for another reason. Stops calling the start action. Starts calling the stop action if the stop() was called last (as opposed to start()). // * */ // public void onStart() { // this.starter.stop(); // if (this.desiredState == State.Stopped) this.stopper.start(); // } // /** // * Call this method when the stopAction succeeds, or a start occurs for another reason. Stops calling the stop action. Starts calling the start action if the start() was called last (as opposed to stop()). // * */ // public void onStop() { // this.stopper.stop(); // if (this.desiredState == State.Started) this.starter.start(); // } // } // Path: Source/src/de/tum/in/www1/jReto/routing/managed_module/ManagedBrowser.java import java.util.Date; import java.util.UUID; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Browser; import de.tum.in.www1.jReto.util.StartStopHelper; attemptNumber -> attemptStop(attemptNumber), ManagedModule.DEFAULT_TIMER_SETTINGS, executor ); } private void attemptStart(int attemptNumber) { if (attemptNumber > 1) System.out.println(new Date()+": Retrying to start browser (attempt "+attemptNumber+"): "+ this.browser); this.browser.startBrowsing(); } private void attemptStop(int attemptNumber) { if (attemptNumber > 1) System.out.println(new Date()+": Retrying to stop browser (attempt "+attemptNumber+"): "+ this.browser); this.browser.stopBrowsing(); } @Override public void onBrowsingStarted(Browser browser) { this.startStopHelper.onStart(); this.handler.onBrowsingStarted(this); } @Override public void onBrowsingStopped(Browser browser, Object error) { this.startStopHelper.onStop(); this.handler.onBrowsingStopped(this, error); } @Override
public void onAddressDiscovered(Browser browser, Address address, UUID identifier) {
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/module/remoteP2P/RemoteP2PAddress.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // }
import java.net.URI; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Connection;
package de.tum.in.www1.jReto.module.remoteP2P; public class RemoteP2PAddress implements Address { private final Executor executor; private final URI requestConnectionUri; public RemoteP2PAddress(Executor executor, URI requestConnectionUri) { this.executor = executor; this.requestConnectionUri = requestConnectionUri; } @Override
// Path: Source/src/de/tum/in/www1/jReto/module/api/Address.java // public interface Address { // /** // * Called to establish a new outgoing connection. // * @return A new connection to the peer. // */ // Connection createConnection(); // /** The cost of an address gives an heuristic about which Address should be used if multiple are available. Lower cost is preferred. An WlanAddress uses a cost of 10. */ // int getCost(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // Path: Source/src/de/tum/in/www1/jReto/module/remoteP2P/RemoteP2PAddress.java import java.net.URI; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Address; import de.tum.in.www1.jReto.module.api.Connection; package de.tum.in.www1.jReto.module.remoteP2P; public class RemoteP2PAddress implements Address { private final Executor executor; private final URI requestConnectionUri; public RemoteP2PAddress(Executor executor, URI requestConnectionUri) { this.executor = executor; this.requestConnectionUri = requestConnectionUri; } @Override
public Connection createConnection() {
ls1intum/jReto
Source/test/jReto/meta/RunLoopTest.java
// Path: Source/test/jReto/util/OrderVerifier.java // public class OrderVerifier { // private int current = 0; // // public void check(int value) { // if (value < current) throw new IllegalArgumentException("Wrong order ("+current+" called before "+value+")"); // // this.current = value; // } // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import jReto.util.OrderVerifier; import jReto.util.RunLoop; import org.junit.Test;
package jReto.meta; public class RunLoopTest { @Test public void testDispatchedRunLoop() {
// Path: Source/test/jReto/util/OrderVerifier.java // public class OrderVerifier { // private int current = 0; // // public void check(int value) { // if (value < current) throw new IllegalArgumentException("Wrong order ("+current+" called before "+value+")"); // // this.current = value; // } // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/meta/RunLoopTest.java import jReto.util.OrderVerifier; import jReto.util.RunLoop; import org.junit.Test; package jReto.meta; public class RunLoopTest { @Test public void testDispatchedRunLoop() {
final RunLoop runloop = new RunLoop(false);
ls1intum/jReto
Source/test/jReto/meta/RunLoopTest.java
// Path: Source/test/jReto/util/OrderVerifier.java // public class OrderVerifier { // private int current = 0; // // public void check(int value) { // if (value < current) throw new IllegalArgumentException("Wrong order ("+current+" called before "+value+")"); // // this.current = value; // } // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import jReto.util.OrderVerifier; import jReto.util.RunLoop; import org.junit.Test;
package jReto.meta; public class RunLoopTest { @Test public void testDispatchedRunLoop() { final RunLoop runloop = new RunLoop(false);
// Path: Source/test/jReto/util/OrderVerifier.java // public class OrderVerifier { // private int current = 0; // // public void check(int value) { // if (value < current) throw new IllegalArgumentException("Wrong order ("+current+" called before "+value+")"); // // this.current = value; // } // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/meta/RunLoopTest.java import jReto.util.OrderVerifier; import jReto.util.RunLoop; import org.junit.Test; package jReto.meta; public class RunLoopTest { @Test public void testDispatchedRunLoop() { final RunLoop runloop = new RunLoop(false);
final OrderVerifier verifyer = new OrderVerifier();
ls1intum/jReto
Source/test/jReto/module/dummy/DummyAdvertiser.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import java.util.UUID; import de.tum.in.www1.jReto.module.api.Advertiser; import jReto.util.RunLoop;
package jReto.module.dummy; public class DummyAdvertiser implements Advertiser { private DummyNetworkInterface networkInterface;
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/module/dummy/DummyAdvertiser.java import java.util.UUID; import de.tum.in.www1.jReto.module.api.Advertiser; import jReto.util.RunLoop; package jReto.module.dummy; public class DummyAdvertiser implements Advertiser { private DummyNetworkInterface networkInterface;
private RunLoop runloop;
ls1intum/jReto
Source/test/jReto/module/dummy/DummyNetworkInterface.java
// Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import jReto.util.RunLoop; import java.util.HashSet; import java.util.Set;
package jReto.module.dummy; public class DummyNetworkInterface { String interfaceName; Set<DummyBrowser> browsers; Set<DummyAdvertiser> advertisers;
// Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/module/dummy/DummyNetworkInterface.java import jReto.util.RunLoop; import java.util.HashSet; import java.util.Set; package jReto.module.dummy; public class DummyNetworkInterface { String interfaceName; Set<DummyBrowser> browsers; Set<DummyAdvertiser> advertisers;
RunLoop runloop;
ls1intum/jReto
Source/test/jReto/unit/DefaultDataProcessingTest.java
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataConsumer.java // public class DefaultDataConsumer { // private final ByteBuffer data; // private final int length; // // public DefaultDataConsumer(int length) { // this.length = length; // this.data = ByteBuffer.allocate(length); // } // // public int getDataLength() { // return this.length; // } // // public void consume(ByteBuffer data) { // if (this.data.remaining() < data.remaining()) throw new IllegalArgumentException("data contains "+data.remaining()+" additional bytes, can consume "+this.data.remaining()+" bytes maximum."); // this.data.put(data); // } // // public ByteBuffer getData() { // this.data.rewind(); // return this.data; // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataSource.java // public class DefaultDataSource { // private final int length; // private final ByteBuffer data; // // public DefaultDataSource(ByteBuffer data) { // this.length = data.remaining(); // this.data = data; // } // // public int getDataLength() { // return this.length; // } // // public ByteBuffer getData(int offset, int length) { // if (offset+length > this.length) { // throw new IllegalArgumentException("Trying to use offset "+offset+" and length "+length+", total buffer length is "+this.length); // } // // Note: this implementation should be reasonably fast. No data is copied; this creates just a new "view" on the buffer // ByteBuffer result = this.data.duplicate(); // // result.position(offset); // result = result.slice(); // result.limit(length); // // result.rewind(); // // return result; // } // }
import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.DefaultDataConsumer; import de.tum.in.www1.jReto.connectivity.DefaultDataSource;
package jReto.unit; /** * Tests for DefaultDataConsumer and DefaultDataSource. * */ public class DefaultDataProcessingTest { @Test (expected = IllegalArgumentException.class) public void invalidSourceTest1() {
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataConsumer.java // public class DefaultDataConsumer { // private final ByteBuffer data; // private final int length; // // public DefaultDataConsumer(int length) { // this.length = length; // this.data = ByteBuffer.allocate(length); // } // // public int getDataLength() { // return this.length; // } // // public void consume(ByteBuffer data) { // if (this.data.remaining() < data.remaining()) throw new IllegalArgumentException("data contains "+data.remaining()+" additional bytes, can consume "+this.data.remaining()+" bytes maximum."); // this.data.put(data); // } // // public ByteBuffer getData() { // this.data.rewind(); // return this.data; // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataSource.java // public class DefaultDataSource { // private final int length; // private final ByteBuffer data; // // public DefaultDataSource(ByteBuffer data) { // this.length = data.remaining(); // this.data = data; // } // // public int getDataLength() { // return this.length; // } // // public ByteBuffer getData(int offset, int length) { // if (offset+length > this.length) { // throw new IllegalArgumentException("Trying to use offset "+offset+" and length "+length+", total buffer length is "+this.length); // } // // Note: this implementation should be reasonably fast. No data is copied; this creates just a new "view" on the buffer // ByteBuffer result = this.data.duplicate(); // // result.position(offset); // result = result.slice(); // result.limit(length); // // result.rewind(); // // return result; // } // } // Path: Source/test/jReto/unit/DefaultDataProcessingTest.java import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.DefaultDataConsumer; import de.tum.in.www1.jReto.connectivity.DefaultDataSource; package jReto.unit; /** * Tests for DefaultDataConsumer and DefaultDataSource. * */ public class DefaultDataProcessingTest { @Test (expected = IllegalArgumentException.class) public void invalidSourceTest1() {
DefaultDataSource source = new DefaultDataSource(TestData.generate(0));
ls1intum/jReto
Source/test/jReto/unit/DefaultDataProcessingTest.java
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataConsumer.java // public class DefaultDataConsumer { // private final ByteBuffer data; // private final int length; // // public DefaultDataConsumer(int length) { // this.length = length; // this.data = ByteBuffer.allocate(length); // } // // public int getDataLength() { // return this.length; // } // // public void consume(ByteBuffer data) { // if (this.data.remaining() < data.remaining()) throw new IllegalArgumentException("data contains "+data.remaining()+" additional bytes, can consume "+this.data.remaining()+" bytes maximum."); // this.data.put(data); // } // // public ByteBuffer getData() { // this.data.rewind(); // return this.data; // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataSource.java // public class DefaultDataSource { // private final int length; // private final ByteBuffer data; // // public DefaultDataSource(ByteBuffer data) { // this.length = data.remaining(); // this.data = data; // } // // public int getDataLength() { // return this.length; // } // // public ByteBuffer getData(int offset, int length) { // if (offset+length > this.length) { // throw new IllegalArgumentException("Trying to use offset "+offset+" and length "+length+", total buffer length is "+this.length); // } // // Note: this implementation should be reasonably fast. No data is copied; this creates just a new "view" on the buffer // ByteBuffer result = this.data.duplicate(); // // result.position(offset); // result = result.slice(); // result.limit(length); // // result.rewind(); // // return result; // } // }
import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.DefaultDataConsumer; import de.tum.in.www1.jReto.connectivity.DefaultDataSource;
package jReto.unit; /** * Tests for DefaultDataConsumer and DefaultDataSource. * */ public class DefaultDataProcessingTest { @Test (expected = IllegalArgumentException.class) public void invalidSourceTest1() {
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataConsumer.java // public class DefaultDataConsumer { // private final ByteBuffer data; // private final int length; // // public DefaultDataConsumer(int length) { // this.length = length; // this.data = ByteBuffer.allocate(length); // } // // public int getDataLength() { // return this.length; // } // // public void consume(ByteBuffer data) { // if (this.data.remaining() < data.remaining()) throw new IllegalArgumentException("data contains "+data.remaining()+" additional bytes, can consume "+this.data.remaining()+" bytes maximum."); // this.data.put(data); // } // // public ByteBuffer getData() { // this.data.rewind(); // return this.data; // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataSource.java // public class DefaultDataSource { // private final int length; // private final ByteBuffer data; // // public DefaultDataSource(ByteBuffer data) { // this.length = data.remaining(); // this.data = data; // } // // public int getDataLength() { // return this.length; // } // // public ByteBuffer getData(int offset, int length) { // if (offset+length > this.length) { // throw new IllegalArgumentException("Trying to use offset "+offset+" and length "+length+", total buffer length is "+this.length); // } // // Note: this implementation should be reasonably fast. No data is copied; this creates just a new "view" on the buffer // ByteBuffer result = this.data.duplicate(); // // result.position(offset); // result = result.slice(); // result.limit(length); // // result.rewind(); // // return result; // } // } // Path: Source/test/jReto/unit/DefaultDataProcessingTest.java import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.DefaultDataConsumer; import de.tum.in.www1.jReto.connectivity.DefaultDataSource; package jReto.unit; /** * Tests for DefaultDataConsumer and DefaultDataSource. * */ public class DefaultDataProcessingTest { @Test (expected = IllegalArgumentException.class) public void invalidSourceTest1() {
DefaultDataSource source = new DefaultDataSource(TestData.generate(0));
ls1intum/jReto
Source/test/jReto/unit/DefaultDataProcessingTest.java
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataConsumer.java // public class DefaultDataConsumer { // private final ByteBuffer data; // private final int length; // // public DefaultDataConsumer(int length) { // this.length = length; // this.data = ByteBuffer.allocate(length); // } // // public int getDataLength() { // return this.length; // } // // public void consume(ByteBuffer data) { // if (this.data.remaining() < data.remaining()) throw new IllegalArgumentException("data contains "+data.remaining()+" additional bytes, can consume "+this.data.remaining()+" bytes maximum."); // this.data.put(data); // } // // public ByteBuffer getData() { // this.data.rewind(); // return this.data; // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataSource.java // public class DefaultDataSource { // private final int length; // private final ByteBuffer data; // // public DefaultDataSource(ByteBuffer data) { // this.length = data.remaining(); // this.data = data; // } // // public int getDataLength() { // return this.length; // } // // public ByteBuffer getData(int offset, int length) { // if (offset+length > this.length) { // throw new IllegalArgumentException("Trying to use offset "+offset+" and length "+length+", total buffer length is "+this.length); // } // // Note: this implementation should be reasonably fast. No data is copied; this creates just a new "view" on the buffer // ByteBuffer result = this.data.duplicate(); // // result.position(offset); // result = result.slice(); // result.limit(length); // // result.rewind(); // // return result; // } // }
import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.DefaultDataConsumer; import de.tum.in.www1.jReto.connectivity.DefaultDataSource;
package jReto.unit; /** * Tests for DefaultDataConsumer and DefaultDataSource. * */ public class DefaultDataProcessingTest { @Test (expected = IllegalArgumentException.class) public void invalidSourceTest1() { DefaultDataSource source = new DefaultDataSource(TestData.generate(0)); source.getData(0, 1); } @Test (expected = IllegalArgumentException.class) public void invalidSourceTest2() { DefaultDataSource source = new DefaultDataSource(TestData.generate(100)); source.getData(50, 51); } @Test (expected = IllegalArgumentException.class) public void invalidConsumerTest1() {
// Path: Source/test/jReto/util/TestData.java // public class TestData { // public static ByteBuffer generate(int length) { // ByteBuffer buffer = ByteBuffer.allocate(length); // for (int i=0; i<length; i++) { // buffer.put((byte)(i%127)); // } // buffer.rewind(); // return buffer; // } // // public static void verify(ByteBuffer buffer, int length) { // int count = buffer.remaining(); // if (count != length) throw new IllegalArgumentException("Test data needs to have the correct length"); // // for (int i=0; i<count; i++) { // byte value = buffer.get(); // // if (value != i%127) throw new IllegalArgumentException("Buffer has incorrect value: "+value+", should be: "+i%127); // } // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataConsumer.java // public class DefaultDataConsumer { // private final ByteBuffer data; // private final int length; // // public DefaultDataConsumer(int length) { // this.length = length; // this.data = ByteBuffer.allocate(length); // } // // public int getDataLength() { // return this.length; // } // // public void consume(ByteBuffer data) { // if (this.data.remaining() < data.remaining()) throw new IllegalArgumentException("data contains "+data.remaining()+" additional bytes, can consume "+this.data.remaining()+" bytes maximum."); // this.data.put(data); // } // // public ByteBuffer getData() { // this.data.rewind(); // return this.data; // } // } // // Path: Source/src/de/tum/in/www1/jReto/connectivity/DefaultDataSource.java // public class DefaultDataSource { // private final int length; // private final ByteBuffer data; // // public DefaultDataSource(ByteBuffer data) { // this.length = data.remaining(); // this.data = data; // } // // public int getDataLength() { // return this.length; // } // // public ByteBuffer getData(int offset, int length) { // if (offset+length > this.length) { // throw new IllegalArgumentException("Trying to use offset "+offset+" and length "+length+", total buffer length is "+this.length); // } // // Note: this implementation should be reasonably fast. No data is copied; this creates just a new "view" on the buffer // ByteBuffer result = this.data.duplicate(); // // result.position(offset); // result = result.slice(); // result.limit(length); // // result.rewind(); // // return result; // } // } // Path: Source/test/jReto/unit/DefaultDataProcessingTest.java import jReto.util.TestData; import org.junit.Test; import de.tum.in.www1.jReto.connectivity.DefaultDataConsumer; import de.tum.in.www1.jReto.connectivity.DefaultDataSource; package jReto.unit; /** * Tests for DefaultDataConsumer and DefaultDataSource. * */ public class DefaultDataProcessingTest { @Test (expected = IllegalArgumentException.class) public void invalidSourceTest1() { DefaultDataSource source = new DefaultDataSource(TestData.generate(0)); source.getData(0, 1); } @Test (expected = IllegalArgumentException.class) public void invalidSourceTest2() { DefaultDataSource source = new DefaultDataSource(TestData.generate(100)); source.getData(50, 51); } @Test (expected = IllegalArgumentException.class) public void invalidConsumerTest1() {
DefaultDataConsumer consumer = new DefaultDataConsumer(0);
ls1intum/jReto
Source/test/jReto/unit/MulticastPacketTests.java
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/Tree.java // public class Tree<T> { // /** The tree's associated value */ // public final T value; // /** The tree's subtrees */ // public final Set<Tree<T>> children; // // /** Constructs a new tree given a value and a set of subtrees. */ // public Tree(T value, Set<Tree<T>> children) { // this.value = value; // this.children = children; // } // @SafeVarargs // public Tree(T value, Tree<T>... children) { // this.value = value; // this.children = new HashSet<>(Arrays.asList(children)); // } // // public int size() { // int result = 1; // // if (this.children == null) return result; // // for (Tree<T> child : this.children) { // result += child.size(); // } // // return result; // } // /** Whether the tree is a leaf */ // public boolean isLeaf() { // return this.children.size() == 0; // } // public String toString() { // return "{value: "+this.value+"; children: "+this.children+"}"; // } // @Override // public int hashCode() { // return this.value.hashCode() ^ this.children.hashCode(); // } // /** Two trees are equal if their values and subtrees are equal.*/ // @Override // public boolean equals(Object obj) { // if (!obj.getClass().equals(this.getClass())) return false; // // @SuppressWarnings("unchecked") // Tree<T> other = (Tree<T>) obj; // // if (!this.value.equals(other.value)) return false; // return this.children.equals(other.children); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/MulticastHandshake.java // public class MulticastHandshake implements Packet { // public final static PacketType TYPE = PacketType.ROUTING_HANDSHAKE; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.UUID_SIZE; // // public final UUID sourcePeerIdentifier; // public final Set<UUID> destinationIdentifiers; // public final Tree<UUID> nextHopsTree; // // public MulticastHandshake(UUID sourcePeerIdentifier, Set<UUID> destinationIdentifiers, Tree<UUID> nextHopsTree) { // if (destinationIdentifiers.size() == 0) throw new IllegalArgumentException("At least one destination is required."); // // this.sourcePeerIdentifier = sourcePeerIdentifier; // this.destinationIdentifiers = destinationIdentifiers; // this.nextHopsTree = nextHopsTree; // } // // public static MulticastHandshake deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // UUID sourcePeerIdentifier = reader.getUUID(); // int destinationsCount = reader.getInt(); // // if (destinationsCount == 0) { // System.err.println("Invalid MulticastHandshake: No destinations specified."); // return null; // } // if (!reader.checkRemaining(destinationsCount * Constants.UUID_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read destinations."); // return null; // } // // Set<UUID> destinations = new HashSet<>(); // for (int i=0; i<destinationsCount; i++) { // destinations.add(reader.getUUID()); // } // // Tree<UUID> nextHopsTree = deserializeNextHopTree(reader); // // return new MulticastHandshake(sourcePeerIdentifier, destinations, nextHopsTree); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + Constants.INT_SIZE + destinationIdentifiers.size() * Constants.UUID_SIZE + nextHopsTree.size() * (Constants.INT_SIZE + Constants.UUID_SIZE)); // data.add(TYPE); // data.add(this.sourcePeerIdentifier); // data.add(destinationIdentifiers.size()); // for (UUID destinationIdentifier : destinationIdentifiers) data.add(destinationIdentifier); // // serializeNextHopTree(data, nextHopsTree); // // return data.getData(); // } // // private static Tree<UUID> deserializeNextHopTree(DataReader reader) { // if (!reader.checkRemaining(Constants.UUID_SIZE + Constants.INT_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read hop tree."); // return null; // } // // UUID value = reader.getUUID(); // int childrenCount = reader.getInt(); // Set<Tree<UUID>> children = new HashSet<>(); // // for (int i=0; i<childrenCount; i++) { // Tree<UUID> child = deserializeNextHopTree(reader); // if (child == null) return null; // // children.add(child); // } // // return new Tree<>(value, children); // } // private void serializeNextHopTree(DataWriter data, Tree<UUID> tree) { // data.add(tree.value); // data.add(tree.children.size()); // // for (Tree<UUID> child : tree.children) { // serializeNextHopTree(data, child); // } // } // }
import static org.junit.Assert.*; import java.util.Arrays; import java.util.HashSet; import java.util.UUID; import org.junit.Test; import de.tum.in.www1.jReto.routing.algorithm.Tree; import de.tum.in.www1.jReto.routing.packets.MulticastHandshake;
package jReto.unit; public class MulticastPacketTests { @Test public void testMulticastPacketSimple() {
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/Tree.java // public class Tree<T> { // /** The tree's associated value */ // public final T value; // /** The tree's subtrees */ // public final Set<Tree<T>> children; // // /** Constructs a new tree given a value and a set of subtrees. */ // public Tree(T value, Set<Tree<T>> children) { // this.value = value; // this.children = children; // } // @SafeVarargs // public Tree(T value, Tree<T>... children) { // this.value = value; // this.children = new HashSet<>(Arrays.asList(children)); // } // // public int size() { // int result = 1; // // if (this.children == null) return result; // // for (Tree<T> child : this.children) { // result += child.size(); // } // // return result; // } // /** Whether the tree is a leaf */ // public boolean isLeaf() { // return this.children.size() == 0; // } // public String toString() { // return "{value: "+this.value+"; children: "+this.children+"}"; // } // @Override // public int hashCode() { // return this.value.hashCode() ^ this.children.hashCode(); // } // /** Two trees are equal if their values and subtrees are equal.*/ // @Override // public boolean equals(Object obj) { // if (!obj.getClass().equals(this.getClass())) return false; // // @SuppressWarnings("unchecked") // Tree<T> other = (Tree<T>) obj; // // if (!this.value.equals(other.value)) return false; // return this.children.equals(other.children); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/MulticastHandshake.java // public class MulticastHandshake implements Packet { // public final static PacketType TYPE = PacketType.ROUTING_HANDSHAKE; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.UUID_SIZE; // // public final UUID sourcePeerIdentifier; // public final Set<UUID> destinationIdentifiers; // public final Tree<UUID> nextHopsTree; // // public MulticastHandshake(UUID sourcePeerIdentifier, Set<UUID> destinationIdentifiers, Tree<UUID> nextHopsTree) { // if (destinationIdentifiers.size() == 0) throw new IllegalArgumentException("At least one destination is required."); // // this.sourcePeerIdentifier = sourcePeerIdentifier; // this.destinationIdentifiers = destinationIdentifiers; // this.nextHopsTree = nextHopsTree; // } // // public static MulticastHandshake deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // UUID sourcePeerIdentifier = reader.getUUID(); // int destinationsCount = reader.getInt(); // // if (destinationsCount == 0) { // System.err.println("Invalid MulticastHandshake: No destinations specified."); // return null; // } // if (!reader.checkRemaining(destinationsCount * Constants.UUID_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read destinations."); // return null; // } // // Set<UUID> destinations = new HashSet<>(); // for (int i=0; i<destinationsCount; i++) { // destinations.add(reader.getUUID()); // } // // Tree<UUID> nextHopsTree = deserializeNextHopTree(reader); // // return new MulticastHandshake(sourcePeerIdentifier, destinations, nextHopsTree); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + Constants.INT_SIZE + destinationIdentifiers.size() * Constants.UUID_SIZE + nextHopsTree.size() * (Constants.INT_SIZE + Constants.UUID_SIZE)); // data.add(TYPE); // data.add(this.sourcePeerIdentifier); // data.add(destinationIdentifiers.size()); // for (UUID destinationIdentifier : destinationIdentifiers) data.add(destinationIdentifier); // // serializeNextHopTree(data, nextHopsTree); // // return data.getData(); // } // // private static Tree<UUID> deserializeNextHopTree(DataReader reader) { // if (!reader.checkRemaining(Constants.UUID_SIZE + Constants.INT_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read hop tree."); // return null; // } // // UUID value = reader.getUUID(); // int childrenCount = reader.getInt(); // Set<Tree<UUID>> children = new HashSet<>(); // // for (int i=0; i<childrenCount; i++) { // Tree<UUID> child = deserializeNextHopTree(reader); // if (child == null) return null; // // children.add(child); // } // // return new Tree<>(value, children); // } // private void serializeNextHopTree(DataWriter data, Tree<UUID> tree) { // data.add(tree.value); // data.add(tree.children.size()); // // for (Tree<UUID> child : tree.children) { // serializeNextHopTree(data, child); // } // } // } // Path: Source/test/jReto/unit/MulticastPacketTests.java import static org.junit.Assert.*; import java.util.Arrays; import java.util.HashSet; import java.util.UUID; import org.junit.Test; import de.tum.in.www1.jReto.routing.algorithm.Tree; import de.tum.in.www1.jReto.routing.packets.MulticastHandshake; package jReto.unit; public class MulticastPacketTests { @Test public void testMulticastPacketSimple() {
Tree<UUID> testTree = new Tree<>(UUID.randomUUID());
ls1intum/jReto
Source/test/jReto/unit/MulticastPacketTests.java
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/Tree.java // public class Tree<T> { // /** The tree's associated value */ // public final T value; // /** The tree's subtrees */ // public final Set<Tree<T>> children; // // /** Constructs a new tree given a value and a set of subtrees. */ // public Tree(T value, Set<Tree<T>> children) { // this.value = value; // this.children = children; // } // @SafeVarargs // public Tree(T value, Tree<T>... children) { // this.value = value; // this.children = new HashSet<>(Arrays.asList(children)); // } // // public int size() { // int result = 1; // // if (this.children == null) return result; // // for (Tree<T> child : this.children) { // result += child.size(); // } // // return result; // } // /** Whether the tree is a leaf */ // public boolean isLeaf() { // return this.children.size() == 0; // } // public String toString() { // return "{value: "+this.value+"; children: "+this.children+"}"; // } // @Override // public int hashCode() { // return this.value.hashCode() ^ this.children.hashCode(); // } // /** Two trees are equal if their values and subtrees are equal.*/ // @Override // public boolean equals(Object obj) { // if (!obj.getClass().equals(this.getClass())) return false; // // @SuppressWarnings("unchecked") // Tree<T> other = (Tree<T>) obj; // // if (!this.value.equals(other.value)) return false; // return this.children.equals(other.children); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/MulticastHandshake.java // public class MulticastHandshake implements Packet { // public final static PacketType TYPE = PacketType.ROUTING_HANDSHAKE; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.UUID_SIZE; // // public final UUID sourcePeerIdentifier; // public final Set<UUID> destinationIdentifiers; // public final Tree<UUID> nextHopsTree; // // public MulticastHandshake(UUID sourcePeerIdentifier, Set<UUID> destinationIdentifiers, Tree<UUID> nextHopsTree) { // if (destinationIdentifiers.size() == 0) throw new IllegalArgumentException("At least one destination is required."); // // this.sourcePeerIdentifier = sourcePeerIdentifier; // this.destinationIdentifiers = destinationIdentifiers; // this.nextHopsTree = nextHopsTree; // } // // public static MulticastHandshake deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // UUID sourcePeerIdentifier = reader.getUUID(); // int destinationsCount = reader.getInt(); // // if (destinationsCount == 0) { // System.err.println("Invalid MulticastHandshake: No destinations specified."); // return null; // } // if (!reader.checkRemaining(destinationsCount * Constants.UUID_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read destinations."); // return null; // } // // Set<UUID> destinations = new HashSet<>(); // for (int i=0; i<destinationsCount; i++) { // destinations.add(reader.getUUID()); // } // // Tree<UUID> nextHopsTree = deserializeNextHopTree(reader); // // return new MulticastHandshake(sourcePeerIdentifier, destinations, nextHopsTree); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + Constants.INT_SIZE + destinationIdentifiers.size() * Constants.UUID_SIZE + nextHopsTree.size() * (Constants.INT_SIZE + Constants.UUID_SIZE)); // data.add(TYPE); // data.add(this.sourcePeerIdentifier); // data.add(destinationIdentifiers.size()); // for (UUID destinationIdentifier : destinationIdentifiers) data.add(destinationIdentifier); // // serializeNextHopTree(data, nextHopsTree); // // return data.getData(); // } // // private static Tree<UUID> deserializeNextHopTree(DataReader reader) { // if (!reader.checkRemaining(Constants.UUID_SIZE + Constants.INT_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read hop tree."); // return null; // } // // UUID value = reader.getUUID(); // int childrenCount = reader.getInt(); // Set<Tree<UUID>> children = new HashSet<>(); // // for (int i=0; i<childrenCount; i++) { // Tree<UUID> child = deserializeNextHopTree(reader); // if (child == null) return null; // // children.add(child); // } // // return new Tree<>(value, children); // } // private void serializeNextHopTree(DataWriter data, Tree<UUID> tree) { // data.add(tree.value); // data.add(tree.children.size()); // // for (Tree<UUID> child : tree.children) { // serializeNextHopTree(data, child); // } // } // }
import static org.junit.Assert.*; import java.util.Arrays; import java.util.HashSet; import java.util.UUID; import org.junit.Test; import de.tum.in.www1.jReto.routing.algorithm.Tree; import de.tum.in.www1.jReto.routing.packets.MulticastHandshake;
package jReto.unit; public class MulticastPacketTests { @Test public void testMulticastPacketSimple() { Tree<UUID> testTree = new Tree<>(UUID.randomUUID());
// Path: Source/src/de/tum/in/www1/jReto/routing/algorithm/Tree.java // public class Tree<T> { // /** The tree's associated value */ // public final T value; // /** The tree's subtrees */ // public final Set<Tree<T>> children; // // /** Constructs a new tree given a value and a set of subtrees. */ // public Tree(T value, Set<Tree<T>> children) { // this.value = value; // this.children = children; // } // @SafeVarargs // public Tree(T value, Tree<T>... children) { // this.value = value; // this.children = new HashSet<>(Arrays.asList(children)); // } // // public int size() { // int result = 1; // // if (this.children == null) return result; // // for (Tree<T> child : this.children) { // result += child.size(); // } // // return result; // } // /** Whether the tree is a leaf */ // public boolean isLeaf() { // return this.children.size() == 0; // } // public String toString() { // return "{value: "+this.value+"; children: "+this.children+"}"; // } // @Override // public int hashCode() { // return this.value.hashCode() ^ this.children.hashCode(); // } // /** Two trees are equal if their values and subtrees are equal.*/ // @Override // public boolean equals(Object obj) { // if (!obj.getClass().equals(this.getClass())) return false; // // @SuppressWarnings("unchecked") // Tree<T> other = (Tree<T>) obj; // // if (!this.value.equals(other.value)) return false; // return this.children.equals(other.children); // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/MulticastHandshake.java // public class MulticastHandshake implements Packet { // public final static PacketType TYPE = PacketType.ROUTING_HANDSHAKE; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.UUID_SIZE; // // public final UUID sourcePeerIdentifier; // public final Set<UUID> destinationIdentifiers; // public final Tree<UUID> nextHopsTree; // // public MulticastHandshake(UUID sourcePeerIdentifier, Set<UUID> destinationIdentifiers, Tree<UUID> nextHopsTree) { // if (destinationIdentifiers.size() == 0) throw new IllegalArgumentException("At least one destination is required."); // // this.sourcePeerIdentifier = sourcePeerIdentifier; // this.destinationIdentifiers = destinationIdentifiers; // this.nextHopsTree = nextHopsTree; // } // // public static MulticastHandshake deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // UUID sourcePeerIdentifier = reader.getUUID(); // int destinationsCount = reader.getInt(); // // if (destinationsCount == 0) { // System.err.println("Invalid MulticastHandshake: No destinations specified."); // return null; // } // if (!reader.checkRemaining(destinationsCount * Constants.UUID_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read destinations."); // return null; // } // // Set<UUID> destinations = new HashSet<>(); // for (int i=0; i<destinationsCount; i++) { // destinations.add(reader.getUUID()); // } // // Tree<UUID> nextHopsTree = deserializeNextHopTree(reader); // // return new MulticastHandshake(sourcePeerIdentifier, destinations, nextHopsTree); // } // public ByteBuffer serialize() { // DataWriter data = new DataWriter(MINIMUM_LENGTH + Constants.INT_SIZE + destinationIdentifiers.size() * Constants.UUID_SIZE + nextHopsTree.size() * (Constants.INT_SIZE + Constants.UUID_SIZE)); // data.add(TYPE); // data.add(this.sourcePeerIdentifier); // data.add(destinationIdentifiers.size()); // for (UUID destinationIdentifier : destinationIdentifiers) data.add(destinationIdentifier); // // serializeNextHopTree(data, nextHopsTree); // // return data.getData(); // } // // private static Tree<UUID> deserializeNextHopTree(DataReader reader) { // if (!reader.checkRemaining(Constants.UUID_SIZE + Constants.INT_SIZE)) { // System.err.println("Invalid MulticastHandshake: Not enough data remaining to read hop tree."); // return null; // } // // UUID value = reader.getUUID(); // int childrenCount = reader.getInt(); // Set<Tree<UUID>> children = new HashSet<>(); // // for (int i=0; i<childrenCount; i++) { // Tree<UUID> child = deserializeNextHopTree(reader); // if (child == null) return null; // // children.add(child); // } // // return new Tree<>(value, children); // } // private void serializeNextHopTree(DataWriter data, Tree<UUID> tree) { // data.add(tree.value); // data.add(tree.children.size()); // // for (Tree<UUID> child : tree.children) { // serializeNextHopTree(data, child); // } // } // } // Path: Source/test/jReto/unit/MulticastPacketTests.java import static org.junit.Assert.*; import java.util.Arrays; import java.util.HashSet; import java.util.UUID; import org.junit.Test; import de.tum.in.www1.jReto.routing.algorithm.Tree; import de.tum.in.www1.jReto.routing.packets.MulticastHandshake; package jReto.unit; public class MulticastPacketTests { @Test public void testMulticastPacketSimple() { Tree<UUID> testTree = new Tree<>(UUID.randomUUID());
MulticastHandshake handshake = new MulticastHandshake(UUID.randomUUID(), new HashSet<UUID>(Arrays.asList(UUID.randomUUID())), testTree);
ls1intum/jReto
Source/test/jReto/module/dummy/DummyBrowser.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // }
import java.util.HashMap; import java.util.Map; import java.util.UUID; import de.tum.in.www1.jReto.module.api.Browser; import jReto.util.RunLoop;
package jReto.module.dummy; public class DummyBrowser implements Browser { private DummyNetworkInterface networkInterface;
// Path: Source/src/de/tum/in/www1/jReto/module/api/Browser.java // public interface Browser { // /** // * The Browser.Handler interface allows an implementation of the Browser protocol to inform it's delegate about various events. // */ // public static interface Handler { // /** Called when the Browser started to browse. */ // void onBrowsingStarted(Browser browser); // /** Called when the Browser stopped to browse. */ // void onBrowsingStopped(Browser browser, Object error); // /** Called when the Browser discovered an address. */ // void onAddressDiscovered(Browser browser, Address address, UUID identifier); // /** Called when the Browser lost an address, i.e. when that address becomes invalid for any reason. */ // void onAddressRemoved(Browser browser, Address address, UUID identifier); // } // // /** Sets the Browser's delegate */ // void setBrowserHandler(Handler handler); // /** The Browser's delegate */ // Handler getBrowserHandler(); // // /** Whether the Browser is currently active. */ // boolean isBrowsing(); // // /** Starts browsing for other peers. */ // void startBrowsing(); // /** Stops browsing for other peers. */ // void stopBrowsing(); // } // // Path: Source/test/jReto/util/RunLoop.java // public class RunLoop implements Executor { // private BlockingQueue<Runnable> queue; // private boolean running; // private boolean executeImmediately; // // public RunLoop(boolean executeImmediately) { // this.queue = new LinkedBlockingQueue<>(); // this.running = true; // this.executeImmediately = executeImmediately; // } // // public void execute(Runnable runnable) { // if (this.executeImmediately) { // runnable.run(); // } else { // this.queue.add(runnable); // } // } // // public void start() { // while (this.running) { // try { // this.queue.take().run(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // // public void stop() { // this.queue.add(new Runnable() { // // @Override // public void run() { // RunLoop.this.running = false; // } // }); // } // } // Path: Source/test/jReto/module/dummy/DummyBrowser.java import java.util.HashMap; import java.util.Map; import java.util.UUID; import de.tum.in.www1.jReto.module.api.Browser; import jReto.util.RunLoop; package jReto.module.dummy; public class DummyBrowser implements Browser { private DummyNetworkInterface networkInterface;
private RunLoop runloop;
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/FloodingPacketManager.java
// Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/PacketType.java // public enum PacketType { // UNKNOWN(0), // // // Routing Layer // LINK_HANDHAKE(1), // ROUTING_HANDSHAKE(2), // LINK_STATE(3), // FLOODED_PACKET(4), // ROUTED_CONNECTION_ESTABLISHED_CONFIRMATION(5), // // // Connectivity // MANAGED_CONNECTION_HANDSHAKE(10), // CLOSE_REQUEST(11), // CLOSE_ANNOUNCE(12), // CLOSE_ACKNOWLEDGE(13), // // // Data transmission // TRANSFER_STARTED(20), // DATA_PACKET(21), // CANCELLED_TRANSFER(22), // PROGRESS_INFORMATION(23); // // private static final Map<Integer, PacketType> intToTypeMap = new HashMap<Integer, PacketType>(); // static { // for (PacketType type : PacketType.values()) { // intToTypeMap.put(type.value, type); // } // } // // private final int value; // // PacketType(int value) { // this.value = value; // } // public static PacketType fromRaw(int value) { // PacketType result = intToTypeMap.get(value); // if (result == null) result = PacketType.UNKNOWN; // return result; // } // public static PacketType fromData(ByteBuffer data) { // if (data.remaining() < 4) { // System.err.println("Insufficient data to get packet type."); // return PacketType.UNKNOWN; // } // // int value = data.getInt(); // data.rewind(); // PacketType type = PacketType.fromRaw(value); // // if (type == PacketType.UNKNOWN) { // System.err.println("Read unknown type, value was: "+value); // } // // return type; // } // public int toRaw() { // return this.value; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // }
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import de.tum.in.www1.jReto.packet.Packet; import de.tum.in.www1.jReto.packet.PacketType; import de.tum.in.www1.jReto.routing.packets.FloodingPacket;
package de.tum.in.www1.jReto.routing; /** * The FloodingPacketManager implements the Flooding algorithm used to distribute packets through the network. * When a packet is received, and it or a newer one has been seen before, it is discarded. This is accomplished by storing the last seen sequence number * for each sender. * If the packet is new, it is forwarded to all direct neighbors of the local peer. */ public class FloodingPacketManager { public static interface PacketHandler {
// Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/PacketType.java // public enum PacketType { // UNKNOWN(0), // // // Routing Layer // LINK_HANDHAKE(1), // ROUTING_HANDSHAKE(2), // LINK_STATE(3), // FLOODED_PACKET(4), // ROUTED_CONNECTION_ESTABLISHED_CONFIRMATION(5), // // // Connectivity // MANAGED_CONNECTION_HANDSHAKE(10), // CLOSE_REQUEST(11), // CLOSE_ANNOUNCE(12), // CLOSE_ACKNOWLEDGE(13), // // // Data transmission // TRANSFER_STARTED(20), // DATA_PACKET(21), // CANCELLED_TRANSFER(22), // PROGRESS_INFORMATION(23); // // private static final Map<Integer, PacketType> intToTypeMap = new HashMap<Integer, PacketType>(); // static { // for (PacketType type : PacketType.values()) { // intToTypeMap.put(type.value, type); // } // } // // private final int value; // // PacketType(int value) { // this.value = value; // } // public static PacketType fromRaw(int value) { // PacketType result = intToTypeMap.get(value); // if (result == null) result = PacketType.UNKNOWN; // return result; // } // public static PacketType fromData(ByteBuffer data) { // if (data.remaining() < 4) { // System.err.println("Insufficient data to get packet type."); // return PacketType.UNKNOWN; // } // // int value = data.getInt(); // data.rewind(); // PacketType type = PacketType.fromRaw(value); // // if (type == PacketType.UNKNOWN) { // System.err.println("Read unknown type, value was: "+value); // } // // return type; // } // public int toRaw() { // return this.value; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // } // Path: Source/src/de/tum/in/www1/jReto/routing/FloodingPacketManager.java import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import de.tum.in.www1.jReto.packet.Packet; import de.tum.in.www1.jReto.packet.PacketType; import de.tum.in.www1.jReto.routing.packets.FloodingPacket; package de.tum.in.www1.jReto.routing; /** * The FloodingPacketManager implements the Flooding algorithm used to distribute packets through the network. * When a packet is received, and it or a newer one has been seen before, it is discarded. This is accomplished by storing the last seen sequence number * for each sender. * If the packet is new, it is forwarded to all direct neighbors of the local peer. */ public class FloodingPacketManager { public static interface PacketHandler {
Set<PacketType> getHandledPacketTypes();
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/FloodingPacketManager.java
// Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/PacketType.java // public enum PacketType { // UNKNOWN(0), // // // Routing Layer // LINK_HANDHAKE(1), // ROUTING_HANDSHAKE(2), // LINK_STATE(3), // FLOODED_PACKET(4), // ROUTED_CONNECTION_ESTABLISHED_CONFIRMATION(5), // // // Connectivity // MANAGED_CONNECTION_HANDSHAKE(10), // CLOSE_REQUEST(11), // CLOSE_ANNOUNCE(12), // CLOSE_ACKNOWLEDGE(13), // // // Data transmission // TRANSFER_STARTED(20), // DATA_PACKET(21), // CANCELLED_TRANSFER(22), // PROGRESS_INFORMATION(23); // // private static final Map<Integer, PacketType> intToTypeMap = new HashMap<Integer, PacketType>(); // static { // for (PacketType type : PacketType.values()) { // intToTypeMap.put(type.value, type); // } // } // // private final int value; // // PacketType(int value) { // this.value = value; // } // public static PacketType fromRaw(int value) { // PacketType result = intToTypeMap.get(value); // if (result == null) result = PacketType.UNKNOWN; // return result; // } // public static PacketType fromData(ByteBuffer data) { // if (data.remaining() < 4) { // System.err.println("Insufficient data to get packet type."); // return PacketType.UNKNOWN; // } // // int value = data.getInt(); // data.rewind(); // PacketType type = PacketType.fromRaw(value); // // if (type == PacketType.UNKNOWN) { // System.err.println("Read unknown type, value was: "+value); // } // // return type; // } // public int toRaw() { // return this.value; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // }
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import de.tum.in.www1.jReto.packet.Packet; import de.tum.in.www1.jReto.packet.PacketType; import de.tum.in.www1.jReto.routing.packets.FloodingPacket;
package de.tum.in.www1.jReto.routing; /** * The FloodingPacketManager implements the Flooding algorithm used to distribute packets through the network. * When a packet is received, and it or a newer one has been seen before, it is discarded. This is accomplished by storing the last seen sequence number * for each sender. * If the packet is new, it is forwarded to all direct neighbors of the local peer. */ public class FloodingPacketManager { public static interface PacketHandler { Set<PacketType> getHandledPacketTypes(); void handlePacket(ByteBuffer data, PacketType type); } /** The Router responsible for this flooding packet manager. */ private final Router router; /** The packet handler registered with this flooding packet manager */ private final PacketHandler packetHandler; /** The next sequence number that will be used for packets sent from this peer. */ private int currentSequenceNumber = 0; /** The highest sequence number seen for each remote peer. */ private Map<UUID, Integer> sequenceNumbers = new HashMap<>(); /** Constructs a new FloodingPacketManager */ public FloodingPacketManager(PacketHandler packetHandler, Router router) { this.packetHandler = packetHandler; this.router = router; } public Set<PacketType> getHandledPacketTypes() { return new HashSet<>(Arrays.asList(PacketType.FLOODED_PACKET)); } /** Handles a received packet from a given source. If the packet is new, it is forwarded and handled, otherwise it is dismissed. */ public void handlePacket(ByteBuffer data, PacketType type, UUID sourceIdentifier) {
// Path: Source/src/de/tum/in/www1/jReto/packet/Packet.java // public interface Packet { // public ByteBuffer serialize(); // } // // Path: Source/src/de/tum/in/www1/jReto/packet/PacketType.java // public enum PacketType { // UNKNOWN(0), // // // Routing Layer // LINK_HANDHAKE(1), // ROUTING_HANDSHAKE(2), // LINK_STATE(3), // FLOODED_PACKET(4), // ROUTED_CONNECTION_ESTABLISHED_CONFIRMATION(5), // // // Connectivity // MANAGED_CONNECTION_HANDSHAKE(10), // CLOSE_REQUEST(11), // CLOSE_ANNOUNCE(12), // CLOSE_ACKNOWLEDGE(13), // // // Data transmission // TRANSFER_STARTED(20), // DATA_PACKET(21), // CANCELLED_TRANSFER(22), // PROGRESS_INFORMATION(23); // // private static final Map<Integer, PacketType> intToTypeMap = new HashMap<Integer, PacketType>(); // static { // for (PacketType type : PacketType.values()) { // intToTypeMap.put(type.value, type); // } // } // // private final int value; // // PacketType(int value) { // this.value = value; // } // public static PacketType fromRaw(int value) { // PacketType result = intToTypeMap.get(value); // if (result == null) result = PacketType.UNKNOWN; // return result; // } // public static PacketType fromData(ByteBuffer data) { // if (data.remaining() < 4) { // System.err.println("Insufficient data to get packet type."); // return PacketType.UNKNOWN; // } // // int value = data.getInt(); // data.rewind(); // PacketType type = PacketType.fromRaw(value); // // if (type == PacketType.UNKNOWN) { // System.err.println("Read unknown type, value was: "+value); // } // // return type; // } // public int toRaw() { // return this.value; // } // } // // Path: Source/src/de/tum/in/www1/jReto/routing/packets/FloodingPacket.java // public class FloodingPacket implements Packet { // public final static PacketType TYPE = PacketType.FLOODED_PACKET; // public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.INT_SIZE + Constants.UUID_SIZE; // // public final UUID originIdentifier; // public final int sequenceNumber; // public final ByteBuffer payload; // // public FloodingPacket(UUID originIdentifier, int sequenceNumber, ByteBuffer payload) { // if (payload.remaining() == 0) { // System.err.println("Warning: Created FloodingPacket with 0 length payload."); // } // // this.originIdentifier = originIdentifier; // this.sequenceNumber = sequenceNumber; // this.payload = payload; // } // // public static FloodingPacket deserialize(ByteBuffer data) { // DataReader reader = new DataReader(data); // if (!DataChecker.check(reader, TYPE, MINIMUM_LENGTH)) return null; // // return new FloodingPacket(reader.getUUID(), reader.getInt(), reader.getRemainingData()); // } // public ByteBuffer serialize() { // this.payload.rewind(); // Maybe someone from outside accessed the buffer and didn't rewind it // DataWriter data = new DataWriter(MINIMUM_LENGTH + this.payload.remaining()); // data.add(TYPE); // data.add(this.originIdentifier); // data.add(this.sequenceNumber); // data.add(this.payload); // this.payload.rewind(); // Make sure someone from outside can use the buffer without rewinding first // return data.getData(); // } // } // Path: Source/src/de/tum/in/www1/jReto/routing/FloodingPacketManager.java import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import de.tum.in.www1.jReto.packet.Packet; import de.tum.in.www1.jReto.packet.PacketType; import de.tum.in.www1.jReto.routing.packets.FloodingPacket; package de.tum.in.www1.jReto.routing; /** * The FloodingPacketManager implements the Flooding algorithm used to distribute packets through the network. * When a packet is received, and it or a newer one has been seen before, it is discarded. This is accomplished by storing the last seen sequence number * for each sender. * If the packet is new, it is forwarded to all direct neighbors of the local peer. */ public class FloodingPacketManager { public static interface PacketHandler { Set<PacketType> getHandledPacketTypes(); void handlePacket(ByteBuffer data, PacketType type); } /** The Router responsible for this flooding packet manager. */ private final Router router; /** The packet handler registered with this flooding packet manager */ private final PacketHandler packetHandler; /** The next sequence number that will be used for packets sent from this peer. */ private int currentSequenceNumber = 0; /** The highest sequence number seen for each remote peer. */ private Map<UUID, Integer> sequenceNumbers = new HashMap<>(); /** Constructs a new FloodingPacketManager */ public FloodingPacketManager(PacketHandler packetHandler, Router router) { this.packetHandler = packetHandler; this.router = router; } public Set<PacketType> getHandledPacketTypes() { return new HashSet<>(Arrays.asList(PacketType.FLOODED_PACKET)); } /** Handles a received packet from a given source. If the packet is new, it is forwarded and handled, otherwise it is dismissed. */ public void handlePacket(ByteBuffer data, PacketType type, UUID sourceIdentifier) {
FloodingPacket floodingPacket = FloodingPacket.deserialize(data);
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/managed_module/ManagedAdvertiser.java
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java // public class StartStopHelper { // /** // * Represents the desired states this class should help reach. // * */ // private static enum State { // Started, // Stopped // } // // /** A RetryableActionExecutor that attempts to exectute the start action */ // private final RetryableActionExecutor starter; // /** A RetryableActionExecutor that attempts to exectute the stop action */ // private final RetryableActionExecutor stopper; // // /** The state that should be reached. // * // * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call // * the start action until it is notified about a successful start via onStart(). */ // private State desiredState = State.Stopped; // // /** // * Creates a new StartStopHelper. // * // * @param startAction The start action // * @param stopAction The stop action // * @param timerSettings The timer settings used to retry the start and stop actions // * @param executor The executor to execute the start and stop action on. // * */ // public StartStopHelper(RetryableAction startAction, RetryableAction stopAction, Timer.BackoffTimerSettings timerSettings, Executor executor) { // this.starter = new RetryableActionExecutor(startAction, timerSettings, executor); // this.stopper = new RetryableActionExecutor(stopAction, timerSettings, executor); // } // // /** // * Runs the startAction in delays until onStart is called. // * */ // public void start() { // this.desiredState = State.Started; // // this.stopper.stop(); // this.starter.start(); // } // /** // * Runs the startAction in delays until onStart is called. // * */ // public void stop() { // this.desiredState = State.Stopped; // // this.starter.stop(); // this.stopper.start(); // } // // /** // * Call this method when the startAction succeeds, or a start occurs for another reason. Stops calling the start action. Starts calling the stop action if the stop() was called last (as opposed to start()). // * */ // public void onStart() { // this.starter.stop(); // if (this.desiredState == State.Stopped) this.stopper.start(); // } // /** // * Call this method when the stopAction succeeds, or a start occurs for another reason. Stops calling the stop action. Starts calling the start action if the start() was called last (as opposed to stop()). // * */ // public void onStop() { // this.stopper.stop(); // if (this.desiredState == State.Started) this.starter.start(); // } // }
import java.util.Date; import java.util.UUID; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Advertiser; import de.tum.in.www1.jReto.module.api.Connection; import de.tum.in.www1.jReto.util.StartStopHelper;
package de.tum.in.www1.jReto.routing.managed_module; /** * A ManagedAdvertiser automatically attempts to restart an Advertiser if starting the advertiser failed. The same concept applies to stopping the advertiser. * */ public class ManagedAdvertiser implements Advertiser, Advertiser.Handler { private final Advertiser advertiser;
// Path: Source/src/de/tum/in/www1/jReto/module/api/Advertiser.java // public interface Advertiser { // /** // * The Advertiser.Handler interface allows the Advertiser to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the advertiser started advertising. */ // void onAdvertisingStarted(Advertiser advertiser); // /** Called when the advertiser stopped advertising. */ // void onAdvertisingStopped(Advertiser advertiser); // /** Called when the advertiser received an incoming connection from a remote peer. */ // void onConnection(Advertiser advertiser, Connection connection); // } // // /** Sets the advertiser's delegate. */ // void setAdvertiserHandler(Handler handler); // /** Returns the advertiser's delegate. */ // Handler getAdvertiserHandler(); // /** Whether the advertiser is currently active. */ // boolean isAdvertising(); // /** // * Starts advertising. // * @param identifier A UUID identifying the local peer. // */ // void startAdvertisingWithPeerIdentifier(UUID identifier); // /** // * Stops advertising. // */ // void stopAdvertising(); // } // // Path: Source/src/de/tum/in/www1/jReto/module/api/Connection.java // public interface Connection { // /** // * The Connection.Handler interface allows the Connection to inform its delegate about various events. // */ // public static interface Handler { // /** Called when the connection connected successfully.*/ // void onConnect(Connection connection); // /** Called when the connection closes. Has an optional error parameter to indicate issues. (Used to report problems to the user). */ // void onClose(Connection connection); // /** Called when data was received. */ // void onDataReceived(Connection connection, ByteBuffer data); // /** Called for each writeData call, when it is complete. */ // void onDataSent(Connection connection); // } // // /** Sets the connection's delegate. */ // void setHandler(Handler handler); // /** The connection's delegate. */ // Handler getHandler(); // // /** Whether this connection is currently connected. */ // boolean isConnected(); // /** Reto sends packets which may vary in size. This property may return an ideal packet size that should be used if possible. */ // int getRecommendedPacketSize(); // // /** Connects the connection. */ // void connect(); // /** Closes the connection. */ // void close(); // // /** Sends data using the connection. */ // void writeData(ByteBuffer data); // } // // Path: Source/src/de/tum/in/www1/jReto/util/StartStopHelper.java // public class StartStopHelper { // /** // * Represents the desired states this class should help reach. // * */ // private static enum State { // Started, // Stopped // } // // /** A RetryableActionExecutor that attempts to exectute the start action */ // private final RetryableActionExecutor starter; // /** A RetryableActionExecutor that attempts to exectute the stop action */ // private final RetryableActionExecutor stopper; // // /** The state that should be reached. // * // * E.g.: When the switching the desired state to the started state (by calling start), the StartStopHelper will call // * the start action until it is notified about a successful start via onStart(). */ // private State desiredState = State.Stopped; // // /** // * Creates a new StartStopHelper. // * // * @param startAction The start action // * @param stopAction The stop action // * @param timerSettings The timer settings used to retry the start and stop actions // * @param executor The executor to execute the start and stop action on. // * */ // public StartStopHelper(RetryableAction startAction, RetryableAction stopAction, Timer.BackoffTimerSettings timerSettings, Executor executor) { // this.starter = new RetryableActionExecutor(startAction, timerSettings, executor); // this.stopper = new RetryableActionExecutor(stopAction, timerSettings, executor); // } // // /** // * Runs the startAction in delays until onStart is called. // * */ // public void start() { // this.desiredState = State.Started; // // this.stopper.stop(); // this.starter.start(); // } // /** // * Runs the startAction in delays until onStart is called. // * */ // public void stop() { // this.desiredState = State.Stopped; // // this.starter.stop(); // this.stopper.start(); // } // // /** // * Call this method when the startAction succeeds, or a start occurs for another reason. Stops calling the start action. Starts calling the stop action if the stop() was called last (as opposed to start()). // * */ // public void onStart() { // this.starter.stop(); // if (this.desiredState == State.Stopped) this.stopper.start(); // } // /** // * Call this method when the stopAction succeeds, or a start occurs for another reason. Stops calling the stop action. Starts calling the start action if the start() was called last (as opposed to stop()). // * */ // public void onStop() { // this.stopper.stop(); // if (this.desiredState == State.Started) this.starter.start(); // } // } // Path: Source/src/de/tum/in/www1/jReto/routing/managed_module/ManagedAdvertiser.java import java.util.Date; import java.util.UUID; import java.util.concurrent.Executor; import de.tum.in.www1.jReto.module.api.Advertiser; import de.tum.in.www1.jReto.module.api.Connection; import de.tum.in.www1.jReto.util.StartStopHelper; package de.tum.in.www1.jReto.routing.managed_module; /** * A ManagedAdvertiser automatically attempts to restart an Advertiser if starting the advertiser failed. The same concept applies to stopping the advertiser. * */ public class ManagedAdvertiser implements Advertiser, Advertiser.Handler { private final Advertiser advertiser;
private final StartStopHelper startStopHelper;
cathive/fx-guice
src/test/java/com/cathive/fx/guice/FXMLComponentTest.java
// Path: src/test/java/com/cathive/fx/guice/example/SimpleFXMLComponent.java // @FXMLComponent(location = "/SimpleFXMLComponent.fxml", resources = "SimpleFXMLComponent") // public final class SimpleFXMLComponent extends VBox { // // private final IntegerProperty theAnswerToEverything = new SimpleIntegerProperty(); // // @Inject private Injector injector; // // @FXML private URL location; // @FXML private ResourceBundle resources; // // @FXML private Button button; // @FXML private Label label; // // private boolean initialized = false; // // public SimpleFXMLComponent() { // super(); // } // // public Injector getInjector() { // return this.injector; // } // // public void initialize() { // this.initialized = true; // } // // public Button getButton() { // return this.button; // } // // public Label getLabel() { // return this.label; // } // // public boolean isInitialized() { // return this.initialized; // } // // public int getTheAnswerToEverything() { // return this.theAnswerToEverything.get(); // } // // public void setTheAnswerToEverything(final int theAnswerToEverything) { // this.theAnswerToEverything.set(theAnswerToEverything); // } // // public IntegerProperty theAnswerToEverythingProperty() { // return this.theAnswerToEverything; // } // // } // // Path: src/test/java/com/cathive/fx/guice/example/ExampleFXMLComponentWrapperController.java // @FXMLController // public class ExampleFXMLComponentWrapperController { // // @Inject private Injector injector; // // @FXML SimpleFXMLComponent simpleComponent1; // @FXML SimpleFXMLComponent simpleComponent2; // // public Injector getInjector() { // return this.injector; // } // // public SimpleFXMLComponent getSimpleComponent1() { // return this.simpleComponent1; // } // // public SimpleFXMLComponent getSimpleComponent2() { // return this.simpleComponent2; // } // // } // // Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // }
import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.google.inject.Guice; import com.google.inject.Injector; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import javafx.application.Application; import javafx.scene.Parent; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.cathive.fx.guice.example.SimpleFXMLComponent; import com.cathive.fx.guice.example.ExampleFXMLComponentWrapperController;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * * @author Benjamin P. Jung */ // FIXME These tests are currently broken. It is necessary to fully load a // JavaFX application before components can be instantiated correctly. @Test public class FXMLComponentTest { private Injector injector;
// Path: src/test/java/com/cathive/fx/guice/example/SimpleFXMLComponent.java // @FXMLComponent(location = "/SimpleFXMLComponent.fxml", resources = "SimpleFXMLComponent") // public final class SimpleFXMLComponent extends VBox { // // private final IntegerProperty theAnswerToEverything = new SimpleIntegerProperty(); // // @Inject private Injector injector; // // @FXML private URL location; // @FXML private ResourceBundle resources; // // @FXML private Button button; // @FXML private Label label; // // private boolean initialized = false; // // public SimpleFXMLComponent() { // super(); // } // // public Injector getInjector() { // return this.injector; // } // // public void initialize() { // this.initialized = true; // } // // public Button getButton() { // return this.button; // } // // public Label getLabel() { // return this.label; // } // // public boolean isInitialized() { // return this.initialized; // } // // public int getTheAnswerToEverything() { // return this.theAnswerToEverything.get(); // } // // public void setTheAnswerToEverything(final int theAnswerToEverything) { // this.theAnswerToEverything.set(theAnswerToEverything); // } // // public IntegerProperty theAnswerToEverythingProperty() { // return this.theAnswerToEverything; // } // // } // // Path: src/test/java/com/cathive/fx/guice/example/ExampleFXMLComponentWrapperController.java // @FXMLController // public class ExampleFXMLComponentWrapperController { // // @Inject private Injector injector; // // @FXML SimpleFXMLComponent simpleComponent1; // @FXML SimpleFXMLComponent simpleComponent2; // // public Injector getInjector() { // return this.injector; // } // // public SimpleFXMLComponent getSimpleComponent1() { // return this.simpleComponent1; // } // // public SimpleFXMLComponent getSimpleComponent2() { // return this.simpleComponent2; // } // // } // // Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // Path: src/test/java/com/cathive/fx/guice/FXMLComponentTest.java import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.google.inject.Guice; import com.google.inject.Injector; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import javafx.application.Application; import javafx.scene.Parent; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.cathive.fx.guice.example.SimpleFXMLComponent; import com.cathive.fx.guice.example.ExampleFXMLComponentWrapperController; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * * @author Benjamin P. Jung */ // FIXME These tests are currently broken. It is necessary to fully load a // JavaFX application before components can be instantiated correctly. @Test public class FXMLComponentTest { private Injector injector;
private SimpleFXMLComponent simpleComponent;
cathive/fx-guice
src/test/java/com/cathive/fx/guice/FXMLComponentTest.java
// Path: src/test/java/com/cathive/fx/guice/example/SimpleFXMLComponent.java // @FXMLComponent(location = "/SimpleFXMLComponent.fxml", resources = "SimpleFXMLComponent") // public final class SimpleFXMLComponent extends VBox { // // private final IntegerProperty theAnswerToEverything = new SimpleIntegerProperty(); // // @Inject private Injector injector; // // @FXML private URL location; // @FXML private ResourceBundle resources; // // @FXML private Button button; // @FXML private Label label; // // private boolean initialized = false; // // public SimpleFXMLComponent() { // super(); // } // // public Injector getInjector() { // return this.injector; // } // // public void initialize() { // this.initialized = true; // } // // public Button getButton() { // return this.button; // } // // public Label getLabel() { // return this.label; // } // // public boolean isInitialized() { // return this.initialized; // } // // public int getTheAnswerToEverything() { // return this.theAnswerToEverything.get(); // } // // public void setTheAnswerToEverything(final int theAnswerToEverything) { // this.theAnswerToEverything.set(theAnswerToEverything); // } // // public IntegerProperty theAnswerToEverythingProperty() { // return this.theAnswerToEverything; // } // // } // // Path: src/test/java/com/cathive/fx/guice/example/ExampleFXMLComponentWrapperController.java // @FXMLController // public class ExampleFXMLComponentWrapperController { // // @Inject private Injector injector; // // @FXML SimpleFXMLComponent simpleComponent1; // @FXML SimpleFXMLComponent simpleComponent2; // // public Injector getInjector() { // return this.injector; // } // // public SimpleFXMLComponent getSimpleComponent1() { // return this.simpleComponent1; // } // // public SimpleFXMLComponent getSimpleComponent2() { // return this.simpleComponent2; // } // // } // // Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // }
import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.google.inject.Guice; import com.google.inject.Injector; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import javafx.application.Application; import javafx.scene.Parent; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.cathive.fx.guice.example.SimpleFXMLComponent; import com.cathive.fx.guice.example.ExampleFXMLComponentWrapperController;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * * @author Benjamin P. Jung */ // FIXME These tests are currently broken. It is necessary to fully load a // JavaFX application before components can be instantiated correctly. @Test public class FXMLComponentTest { private Injector injector; private SimpleFXMLComponent simpleComponent; @BeforeTest protected void initialize() {
// Path: src/test/java/com/cathive/fx/guice/example/SimpleFXMLComponent.java // @FXMLComponent(location = "/SimpleFXMLComponent.fxml", resources = "SimpleFXMLComponent") // public final class SimpleFXMLComponent extends VBox { // // private final IntegerProperty theAnswerToEverything = new SimpleIntegerProperty(); // // @Inject private Injector injector; // // @FXML private URL location; // @FXML private ResourceBundle resources; // // @FXML private Button button; // @FXML private Label label; // // private boolean initialized = false; // // public SimpleFXMLComponent() { // super(); // } // // public Injector getInjector() { // return this.injector; // } // // public void initialize() { // this.initialized = true; // } // // public Button getButton() { // return this.button; // } // // public Label getLabel() { // return this.label; // } // // public boolean isInitialized() { // return this.initialized; // } // // public int getTheAnswerToEverything() { // return this.theAnswerToEverything.get(); // } // // public void setTheAnswerToEverything(final int theAnswerToEverything) { // this.theAnswerToEverything.set(theAnswerToEverything); // } // // public IntegerProperty theAnswerToEverythingProperty() { // return this.theAnswerToEverything; // } // // } // // Path: src/test/java/com/cathive/fx/guice/example/ExampleFXMLComponentWrapperController.java // @FXMLController // public class ExampleFXMLComponentWrapperController { // // @Inject private Injector injector; // // @FXML SimpleFXMLComponent simpleComponent1; // @FXML SimpleFXMLComponent simpleComponent2; // // public Injector getInjector() { // return this.injector; // } // // public SimpleFXMLComponent getSimpleComponent1() { // return this.simpleComponent1; // } // // public SimpleFXMLComponent getSimpleComponent2() { // return this.simpleComponent2; // } // // } // // Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // Path: src/test/java/com/cathive/fx/guice/FXMLComponentTest.java import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.google.inject.Guice; import com.google.inject.Injector; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import javafx.application.Application; import javafx.scene.Parent; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.cathive.fx.guice.example.SimpleFXMLComponent; import com.cathive.fx.guice.example.ExampleFXMLComponentWrapperController; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * * @author Benjamin P. Jung */ // FIXME These tests are currently broken. It is necessary to fully load a // JavaFX application before components can be instantiated correctly. @Test public class FXMLComponentTest { private Injector injector; private SimpleFXMLComponent simpleComponent; @BeforeTest protected void initialize() {
this.injector = Guice.createInjector(new FXMLLoadingModule());
cathive/fx-guice
src/main/java/com/cathive/fx/guice/fxml/FXMLControllerMembersInjector.java
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // }
import java.lang.reflect.Field; import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.google.inject.MembersInjector;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.fxml; /** * * @author Benjamin P. Jung */ final class FXMLControllerMembersInjector<T> implements MembersInjector<T> { private final Field field; private final FXMLController annotation; private final FXMLLoadingScope scope; FXMLControllerMembersInjector(final Field field, final FXMLController annotation, final FXMLLoadingScope scope) { super(); this.field = field; this.annotation = annotation; this.scope = scope; field.setAccessible(true); } @Override public void injectMembers(T instance) { Object controllerInstance = null; if (!annotation.controllerId().isEmpty()) {
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // Path: src/main/java/com/cathive/fx/guice/fxml/FXMLControllerMembersInjector.java import java.lang.reflect.Field; import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.google.inject.MembersInjector; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.fxml; /** * * @author Benjamin P. Jung */ final class FXMLControllerMembersInjector<T> implements MembersInjector<T> { private final Field field; private final FXMLController annotation; private final FXMLLoadingScope scope; FXMLControllerMembersInjector(final Field field, final FXMLController annotation, final FXMLLoadingScope scope) { super(); this.field = field; this.annotation = annotation; this.scope = scope; field.setAccessible(true); } @Override public void injectMembers(T instance) { Object controllerInstance = null; if (!annotation.controllerId().isEmpty()) {
controllerInstance = new ControllerLookup(scope.getIdentifiables()).lookup(annotation.controllerId());
cathive/fx-guice
src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/IdentifiableController.java // public interface IdentifiableController { // // /** // * @return The string ID that can be used to lookup this controller. This // * could be hard coded or could return the ID set on the FXML for // * this control in the {@link Parent}. // */ // String getId(); // // } // // Path: src/main/java/com/cathive/fx/guice/controllerlookup/ParentIDFinder.java // public final class ParentIDFinder { // // /** Private constructor - should never be needed. */ // private ParentIDFinder() { // // Intentionally left empty. // // No instance of this class should ever be needed. // } // // /** // * Find a non {@code null} ID on the given {@link Parent}. If the ID is // * {@code null} then search up the graph to find a node with the given ID. // * // * @param node // * The starting node. // * @return The ID of this node or the ID of the parent if this is // * {@code null}, if this is also null then the parent's parent will // * be returned if non-{@code null} and so on. If no parent's have an // * ID set then {@code null} is returned. // */ // public static String getParentId(final Node node) { // final String parentId; // if (node == null) { // parentId = null; // } else if (node.getId() != null) { // parentId = node.getId(); // } else { // parentId = getParentId(node.getParent()); // } // return parentId; // } // // }
import javafx.fxml.FXML; import javafx.scene.Parent; import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.IdentifiableController; import com.cathive.fx.guice.controllerlookup.ParentIDFinder;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.lookupexample; @FXMLController public class InnerLookupController implements IdentifiableController { @FXML private Parent root; @Override public String getId() {
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/IdentifiableController.java // public interface IdentifiableController { // // /** // * @return The string ID that can be used to lookup this controller. This // * could be hard coded or could return the ID set on the FXML for // * this control in the {@link Parent}. // */ // String getId(); // // } // // Path: src/main/java/com/cathive/fx/guice/controllerlookup/ParentIDFinder.java // public final class ParentIDFinder { // // /** Private constructor - should never be needed. */ // private ParentIDFinder() { // // Intentionally left empty. // // No instance of this class should ever be needed. // } // // /** // * Find a non {@code null} ID on the given {@link Parent}. If the ID is // * {@code null} then search up the graph to find a node with the given ID. // * // * @param node // * The starting node. // * @return The ID of this node or the ID of the parent if this is // * {@code null}, if this is also null then the parent's parent will // * be returned if non-{@code null} and so on. If no parent's have an // * ID set then {@code null} is returned. // */ // public static String getParentId(final Node node) { // final String parentId; // if (node == null) { // parentId = null; // } else if (node.getId() != null) { // parentId = node.getId(); // } else { // parentId = getParentId(node.getParent()); // } // return parentId; // } // // } // Path: src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java import javafx.fxml.FXML; import javafx.scene.Parent; import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.IdentifiableController; import com.cathive.fx.guice.controllerlookup.ParentIDFinder; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.lookupexample; @FXMLController public class InnerLookupController implements IdentifiableController { @FXML private Parent root; @Override public String getId() {
return ParentIDFinder.getParentId(root);
cathive/fx-guice
src/test/java/com/cathive/fx/guice/GuiceFXMLLoaderTest.java
// Path: src/test/java/com/cathive/fx/guice/example/ExamplePaneController.java // @FXMLController // public class ExamplePaneController implements Initializable { // // private List<String> methodCalls = new ArrayList<>(); // // private boolean initialized = false; // private boolean injected = false; // // @FXML private AnchorPane rootPane; // // @Inject private void postConstruct() { // methodCalls.add("postConstruct()"); // this.injected = true; // } // // @Override public void initialize(URL url, ResourceBundle rb) { // methodCalls.add("initialize(java.net.URL, java.util.ResourceBundle)"); // this.initialized = true; // } // // public boolean isInitialized() { // return this.initialized; // } // // public boolean isInjected() { // return this.injected; // } // // public List<String> getMethodCalls() { // return this.methodCalls; // } // // public AnchorPane getRootPane() { // return this.rootPane; // } // // }
import org.testng.annotations.Test; import com.cathive.fx.guice.example.ExamplePaneController; import com.google.inject.Injector; import com.google.inject.Module; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.ResourceBundle; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import org.mockito.Mockito; import org.testng.annotations.BeforeClass;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * * @author Benjamin P. Jung */ @Test(singleThreaded = true) public class GuiceFXMLLoaderTest { // Initialized prior to all test methods! private Injector injector = null; private GuiceFXMLLoader fxmlLoader = null;
// Path: src/test/java/com/cathive/fx/guice/example/ExamplePaneController.java // @FXMLController // public class ExamplePaneController implements Initializable { // // private List<String> methodCalls = new ArrayList<>(); // // private boolean initialized = false; // private boolean injected = false; // // @FXML private AnchorPane rootPane; // // @Inject private void postConstruct() { // methodCalls.add("postConstruct()"); // this.injected = true; // } // // @Override public void initialize(URL url, ResourceBundle rb) { // methodCalls.add("initialize(java.net.URL, java.util.ResourceBundle)"); // this.initialized = true; // } // // public boolean isInitialized() { // return this.initialized; // } // // public boolean isInjected() { // return this.injected; // } // // public List<String> getMethodCalls() { // return this.methodCalls; // } // // public AnchorPane getRootPane() { // return this.rootPane; // } // // } // Path: src/test/java/com/cathive/fx/guice/GuiceFXMLLoaderTest.java import org.testng.annotations.Test; import com.cathive.fx.guice.example.ExamplePaneController; import com.google.inject.Injector; import com.google.inject.Module; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.ResourceBundle; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import org.mockito.Mockito; import org.testng.annotations.BeforeClass; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * * @author Benjamin P. Jung */ @Test(singleThreaded = true) public class GuiceFXMLLoaderTest { // Initialized prior to all test methods! private Injector injector = null; private GuiceFXMLLoader fxmlLoader = null;
private ExamplePaneController ctrl;
cathive/fx-guice
src/main/java/com/cathive/fx/guice/GuiceApplication.java
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // // Path: src/main/java/com/cathive/fx/guice/prefs/PersistentPropertyModule.java // public final class PersistentPropertyModule extends AbstractModule { // // @Override // public void configure() { // bindListener(Matchers.any(), new PersistentPropertyTypeListener()); // } // // } // // Path: src/main/java/com/cathive/fx/guice/thread/FxApplicationThreadModule.java // public final class FxApplicationThreadModule extends AbstractModule { // // @Override // protected void configure() { // bindInterceptor( // Matchers.any(), // Matchers.annotatedWith(FxApplicationThread.class), // new FxApplicationThreadMethodInterceptor()); // } // // }
import com.google.inject.Module; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.util.*; import com.google.inject.Provider; import javafx.application.Application; import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.cathive.fx.guice.prefs.PersistentPropertyModule; import com.cathive.fx.guice.thread.FxApplicationThreadModule; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector;
* during the invocation of this overriden method: {@link #init(java.util.List)}.</p> */ @Override public final void init() throws Exception { super.init(); @SuppressWarnings("unchecked") final Class<GuiceApplication> clazz = (Class<GuiceApplication>) getClass(); final GuiceApplication instance = this; // Checks the GuiceApplication instance and makes sure that none of the constructors is // annotated with @Inject! for (final Constructor<?> c: instance.getClass().getConstructors()) { if (isInjectAnnotationPresent(c)) { throw new IllegalStateException("GuiceApplication with constructor that is marked with @Inject is not allowed!"); } } final Set<Module> modules = new HashSet<>(); modules.add(new AbstractModule() { @Override protected void configure() { bind(clazz).toProvider(new Provider<GuiceApplication>() { @Override public GuiceApplication get() { return instance; } }); } });
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // // Path: src/main/java/com/cathive/fx/guice/prefs/PersistentPropertyModule.java // public final class PersistentPropertyModule extends AbstractModule { // // @Override // public void configure() { // bindListener(Matchers.any(), new PersistentPropertyTypeListener()); // } // // } // // Path: src/main/java/com/cathive/fx/guice/thread/FxApplicationThreadModule.java // public final class FxApplicationThreadModule extends AbstractModule { // // @Override // protected void configure() { // bindInterceptor( // Matchers.any(), // Matchers.annotatedWith(FxApplicationThread.class), // new FxApplicationThreadMethodInterceptor()); // } // // } // Path: src/main/java/com/cathive/fx/guice/GuiceApplication.java import com.google.inject.Module; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.util.*; import com.google.inject.Provider; import javafx.application.Application; import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.cathive.fx.guice.prefs.PersistentPropertyModule; import com.cathive.fx.guice.thread.FxApplicationThreadModule; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; * during the invocation of this overriden method: {@link #init(java.util.List)}.</p> */ @Override public final void init() throws Exception { super.init(); @SuppressWarnings("unchecked") final Class<GuiceApplication> clazz = (Class<GuiceApplication>) getClass(); final GuiceApplication instance = this; // Checks the GuiceApplication instance and makes sure that none of the constructors is // annotated with @Inject! for (final Constructor<?> c: instance.getClass().getConstructors()) { if (isInjectAnnotationPresent(c)) { throw new IllegalStateException("GuiceApplication with constructor that is marked with @Inject is not allowed!"); } } final Set<Module> modules = new HashSet<>(); modules.add(new AbstractModule() { @Override protected void configure() { bind(clazz).toProvider(new Provider<GuiceApplication>() { @Override public GuiceApplication get() { return instance; } }); } });
modules.add(new FXMLLoadingModule());
cathive/fx-guice
src/main/java/com/cathive/fx/guice/GuiceApplication.java
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // // Path: src/main/java/com/cathive/fx/guice/prefs/PersistentPropertyModule.java // public final class PersistentPropertyModule extends AbstractModule { // // @Override // public void configure() { // bindListener(Matchers.any(), new PersistentPropertyTypeListener()); // } // // } // // Path: src/main/java/com/cathive/fx/guice/thread/FxApplicationThreadModule.java // public final class FxApplicationThreadModule extends AbstractModule { // // @Override // protected void configure() { // bindInterceptor( // Matchers.any(), // Matchers.annotatedWith(FxApplicationThread.class), // new FxApplicationThreadMethodInterceptor()); // } // // }
import com.google.inject.Module; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.util.*; import com.google.inject.Provider; import javafx.application.Application; import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.cathive.fx.guice.prefs.PersistentPropertyModule; import com.cathive.fx.guice.thread.FxApplicationThreadModule; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector;
*/ @Override public final void init() throws Exception { super.init(); @SuppressWarnings("unchecked") final Class<GuiceApplication> clazz = (Class<GuiceApplication>) getClass(); final GuiceApplication instance = this; // Checks the GuiceApplication instance and makes sure that none of the constructors is // annotated with @Inject! for (final Constructor<?> c: instance.getClass().getConstructors()) { if (isInjectAnnotationPresent(c)) { throw new IllegalStateException("GuiceApplication with constructor that is marked with @Inject is not allowed!"); } } final Set<Module> modules = new HashSet<>(); modules.add(new AbstractModule() { @Override protected void configure() { bind(clazz).toProvider(new Provider<GuiceApplication>() { @Override public GuiceApplication get() { return instance; } }); } }); modules.add(new FXMLLoadingModule());
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // // Path: src/main/java/com/cathive/fx/guice/prefs/PersistentPropertyModule.java // public final class PersistentPropertyModule extends AbstractModule { // // @Override // public void configure() { // bindListener(Matchers.any(), new PersistentPropertyTypeListener()); // } // // } // // Path: src/main/java/com/cathive/fx/guice/thread/FxApplicationThreadModule.java // public final class FxApplicationThreadModule extends AbstractModule { // // @Override // protected void configure() { // bindInterceptor( // Matchers.any(), // Matchers.annotatedWith(FxApplicationThread.class), // new FxApplicationThreadMethodInterceptor()); // } // // } // Path: src/main/java/com/cathive/fx/guice/GuiceApplication.java import com.google.inject.Module; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.util.*; import com.google.inject.Provider; import javafx.application.Application; import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.cathive.fx.guice.prefs.PersistentPropertyModule; import com.cathive.fx.guice.thread.FxApplicationThreadModule; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; */ @Override public final void init() throws Exception { super.init(); @SuppressWarnings("unchecked") final Class<GuiceApplication> clazz = (Class<GuiceApplication>) getClass(); final GuiceApplication instance = this; // Checks the GuiceApplication instance and makes sure that none of the constructors is // annotated with @Inject! for (final Constructor<?> c: instance.getClass().getConstructors()) { if (isInjectAnnotationPresent(c)) { throw new IllegalStateException("GuiceApplication with constructor that is marked with @Inject is not allowed!"); } } final Set<Module> modules = new HashSet<>(); modules.add(new AbstractModule() { @Override protected void configure() { bind(clazz).toProvider(new Provider<GuiceApplication>() { @Override public GuiceApplication get() { return instance; } }); } }); modules.add(new FXMLLoadingModule());
modules.add(new FxApplicationThreadModule());
cathive/fx-guice
src/main/java/com/cathive/fx/guice/GuiceApplication.java
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // // Path: src/main/java/com/cathive/fx/guice/prefs/PersistentPropertyModule.java // public final class PersistentPropertyModule extends AbstractModule { // // @Override // public void configure() { // bindListener(Matchers.any(), new PersistentPropertyTypeListener()); // } // // } // // Path: src/main/java/com/cathive/fx/guice/thread/FxApplicationThreadModule.java // public final class FxApplicationThreadModule extends AbstractModule { // // @Override // protected void configure() { // bindInterceptor( // Matchers.any(), // Matchers.annotatedWith(FxApplicationThread.class), // new FxApplicationThreadMethodInterceptor()); // } // // }
import com.google.inject.Module; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.util.*; import com.google.inject.Provider; import javafx.application.Application; import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.cathive.fx.guice.prefs.PersistentPropertyModule; import com.cathive.fx.guice.thread.FxApplicationThreadModule; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector;
@Override public final void init() throws Exception { super.init(); @SuppressWarnings("unchecked") final Class<GuiceApplication> clazz = (Class<GuiceApplication>) getClass(); final GuiceApplication instance = this; // Checks the GuiceApplication instance and makes sure that none of the constructors is // annotated with @Inject! for (final Constructor<?> c: instance.getClass().getConstructors()) { if (isInjectAnnotationPresent(c)) { throw new IllegalStateException("GuiceApplication with constructor that is marked with @Inject is not allowed!"); } } final Set<Module> modules = new HashSet<>(); modules.add(new AbstractModule() { @Override protected void configure() { bind(clazz).toProvider(new Provider<GuiceApplication>() { @Override public GuiceApplication get() { return instance; } }); } }); modules.add(new FXMLLoadingModule()); modules.add(new FxApplicationThreadModule());
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingModule.java // public final class FXMLLoadingModule extends AbstractModule { // // public FXMLLoadingModule() { // super(); // } // // @Override // protected void configure() { // // // FXMLLoadingScope // final FXMLLoadingScope fxmlLoadingScope = new FXMLLoadingScope(); // bind(FXMLLoadingScope.class).toInstance(fxmlLoadingScope); // bindScope(FXMLController.class, fxmlLoadingScope); // bindScope(FXMLComponent.class, fxmlLoadingScope); // // // GuiceFXMLLoader // bind(GuiceFXMLLoader.class); // // // FXMLControllerTypeListener // final FXMLControllerTypeListener fxmlControllerTypeListener = new FXMLControllerTypeListener(); // requestInjection(fxmlControllerTypeListener); // bind(FXMLControllerTypeListener.class).toInstance(fxmlControllerTypeListener); // bindListener(Matchers.any(), fxmlControllerTypeListener); // // // FXMLComponentTypeListener // final FXMLComponentTypeListener fxmlComponentTypeListener = new FXMLComponentTypeListener(); // requestInjection(fxmlComponentTypeListener); // bind(FXMLComponentTypeListener.class).toInstance(fxmlComponentTypeListener); // bindListener(Matchers.any(), fxmlComponentTypeListener); // // // ControllerLookup // bind(ControllerLookup.class).toProvider(new ControllerLookupProvider(fxmlLoadingScope)); // // } // // // private final class ControllerLookupProvider implements Provider<ControllerLookup> { // private final FXMLLoadingScope fxmlLoadingScope; // private ControllerLookupProvider(final FXMLLoadingScope fxmlLoadingScope) { // super(); // this.fxmlLoadingScope = fxmlLoadingScope; // } // @Override // public ControllerLookup get() { // if (!fxmlLoadingScope.isActive()) { // throw new IllegalStateException("A ControllerLookup instance cannot be injected while outside of the FXML Loading scope."); // } // return new ControllerLookup(fxmlLoadingScope.getIdentifiables()); // } // } // // } // // Path: src/main/java/com/cathive/fx/guice/prefs/PersistentPropertyModule.java // public final class PersistentPropertyModule extends AbstractModule { // // @Override // public void configure() { // bindListener(Matchers.any(), new PersistentPropertyTypeListener()); // } // // } // // Path: src/main/java/com/cathive/fx/guice/thread/FxApplicationThreadModule.java // public final class FxApplicationThreadModule extends AbstractModule { // // @Override // protected void configure() { // bindInterceptor( // Matchers.any(), // Matchers.annotatedWith(FxApplicationThread.class), // new FxApplicationThreadMethodInterceptor()); // } // // } // Path: src/main/java/com/cathive/fx/guice/GuiceApplication.java import com.google.inject.Module; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.util.*; import com.google.inject.Provider; import javafx.application.Application; import com.cathive.fx.guice.fxml.FXMLLoadingModule; import com.cathive.fx.guice.prefs.PersistentPropertyModule; import com.cathive.fx.guice.thread.FxApplicationThreadModule; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; @Override public final void init() throws Exception { super.init(); @SuppressWarnings("unchecked") final Class<GuiceApplication> clazz = (Class<GuiceApplication>) getClass(); final GuiceApplication instance = this; // Checks the GuiceApplication instance and makes sure that none of the constructors is // annotated with @Inject! for (final Constructor<?> c: instance.getClass().getConstructors()) { if (isInjectAnnotationPresent(c)) { throw new IllegalStateException("GuiceApplication with constructor that is marked with @Inject is not allowed!"); } } final Set<Module> modules = new HashSet<>(); modules.add(new AbstractModule() { @Override protected void configure() { bind(clazz).toProvider(new Provider<GuiceApplication>() { @Override public GuiceApplication get() { return instance; } }); } }); modules.add(new FXMLLoadingModule()); modules.add(new FxApplicationThreadModule());
modules.add(new PersistentPropertyModule());
cathive/fx-guice
src/test/java/com/cathive/fx/guice/ControllerLookupApplicationTest.java
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java // @FXMLController // public class InnerLookupController implements IdentifiableController { // // @FXML // private Parent root; // // @Override // public String getId() { // return ParentIDFinder.getParentId(root); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java // @FXMLController // public class OuterLookupController { // // @Inject // private ControllerLookup controllerLookup; // // public InnerLookupController getControllerForPane1() { // return controllerLookup.lookup("examplePane1"); // } // // public InnerLookupController getControllerForPane2() { // return controllerLookup.lookup("examplePane2"); // } // // public IdentifiableController getAnyController(String id) { // return controllerLookup.lookup(id); // } // }
import com.cathive.fx.guice.lookupexample.OuterLookupController; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.ProvisionException; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javafx.stage.Stage; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.lookupexample.InnerLookupController;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; public class ControllerLookupApplicationTest { static class ControllerLookupGuiceApplication extends GuiceApplication { @Override public void start(Stage primaryStage) throws Exception { // Do nothing... } @Override public void init(List<Module> modules) throws Exception { // Intentionally left empty } } private ControllerLookupGuiceApplication app; private GuiceFXMLLoader loader; private GuiceFXMLLoader.Result result; @BeforeMethod public void setup() throws Exception { app = new ControllerLookupGuiceApplication(); app.init(); loader = app.getInjector().getInstance(GuiceFXMLLoader.class); result = loader.load( getClass().getResource("/OuterLookupPane.fxml"), ResourceBundle.getBundle("ExamplePane", Locale.ENGLISH) ); } /** * In JavaFX 8 it seems that you can't overwrite the fx:id in an fx:include tag (which was possible in JavaFX 2). * That's the reason why this test was failing on JDK8 while it was running without problems on JDK7. */ @Test(enabled = false) public void parentControllerCanLookupNestedControllers() throws Exception {
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java // @FXMLController // public class InnerLookupController implements IdentifiableController { // // @FXML // private Parent root; // // @Override // public String getId() { // return ParentIDFinder.getParentId(root); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java // @FXMLController // public class OuterLookupController { // // @Inject // private ControllerLookup controllerLookup; // // public InnerLookupController getControllerForPane1() { // return controllerLookup.lookup("examplePane1"); // } // // public InnerLookupController getControllerForPane2() { // return controllerLookup.lookup("examplePane2"); // } // // public IdentifiableController getAnyController(String id) { // return controllerLookup.lookup(id); // } // } // Path: src/test/java/com/cathive/fx/guice/ControllerLookupApplicationTest.java import com.cathive.fx.guice.lookupexample.OuterLookupController; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.ProvisionException; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javafx.stage.Stage; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.lookupexample.InnerLookupController; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; public class ControllerLookupApplicationTest { static class ControllerLookupGuiceApplication extends GuiceApplication { @Override public void start(Stage primaryStage) throws Exception { // Do nothing... } @Override public void init(List<Module> modules) throws Exception { // Intentionally left empty } } private ControllerLookupGuiceApplication app; private GuiceFXMLLoader loader; private GuiceFXMLLoader.Result result; @BeforeMethod public void setup() throws Exception { app = new ControllerLookupGuiceApplication(); app.init(); loader = app.getInjector().getInstance(GuiceFXMLLoader.class); result = loader.load( getClass().getResource("/OuterLookupPane.fxml"), ResourceBundle.getBundle("ExamplePane", Locale.ENGLISH) ); } /** * In JavaFX 8 it seems that you can't overwrite the fx:id in an fx:include tag (which was possible in JavaFX 2). * That's the reason why this test was failing on JDK8 while it was running without problems on JDK7. */ @Test(enabled = false) public void parentControllerCanLookupNestedControllers() throws Exception {
OuterLookupController controller = result.getController();
cathive/fx-guice
src/test/java/com/cathive/fx/guice/ControllerLookupApplicationTest.java
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java // @FXMLController // public class InnerLookupController implements IdentifiableController { // // @FXML // private Parent root; // // @Override // public String getId() { // return ParentIDFinder.getParentId(root); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java // @FXMLController // public class OuterLookupController { // // @Inject // private ControllerLookup controllerLookup; // // public InnerLookupController getControllerForPane1() { // return controllerLookup.lookup("examplePane1"); // } // // public InnerLookupController getControllerForPane2() { // return controllerLookup.lookup("examplePane2"); // } // // public IdentifiableController getAnyController(String id) { // return controllerLookup.lookup(id); // } // }
import com.cathive.fx.guice.lookupexample.OuterLookupController; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.ProvisionException; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javafx.stage.Stage; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.lookupexample.InnerLookupController;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; public class ControllerLookupApplicationTest { static class ControllerLookupGuiceApplication extends GuiceApplication { @Override public void start(Stage primaryStage) throws Exception { // Do nothing... } @Override public void init(List<Module> modules) throws Exception { // Intentionally left empty } } private ControllerLookupGuiceApplication app; private GuiceFXMLLoader loader; private GuiceFXMLLoader.Result result; @BeforeMethod public void setup() throws Exception { app = new ControllerLookupGuiceApplication(); app.init(); loader = app.getInjector().getInstance(GuiceFXMLLoader.class); result = loader.load( getClass().getResource("/OuterLookupPane.fxml"), ResourceBundle.getBundle("ExamplePane", Locale.ENGLISH) ); } /** * In JavaFX 8 it seems that you can't overwrite the fx:id in an fx:include tag (which was possible in JavaFX 2). * That's the reason why this test was failing on JDK8 while it was running without problems on JDK7. */ @Test(enabled = false) public void parentControllerCanLookupNestedControllers() throws Exception { OuterLookupController controller = result.getController();
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java // @FXMLController // public class InnerLookupController implements IdentifiableController { // // @FXML // private Parent root; // // @Override // public String getId() { // return ParentIDFinder.getParentId(root); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java // @FXMLController // public class OuterLookupController { // // @Inject // private ControllerLookup controllerLookup; // // public InnerLookupController getControllerForPane1() { // return controllerLookup.lookup("examplePane1"); // } // // public InnerLookupController getControllerForPane2() { // return controllerLookup.lookup("examplePane2"); // } // // public IdentifiableController getAnyController(String id) { // return controllerLookup.lookup(id); // } // } // Path: src/test/java/com/cathive/fx/guice/ControllerLookupApplicationTest.java import com.cathive.fx.guice.lookupexample.OuterLookupController; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.ProvisionException; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javafx.stage.Stage; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.lookupexample.InnerLookupController; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice; public class ControllerLookupApplicationTest { static class ControllerLookupGuiceApplication extends GuiceApplication { @Override public void start(Stage primaryStage) throws Exception { // Do nothing... } @Override public void init(List<Module> modules) throws Exception { // Intentionally left empty } } private ControllerLookupGuiceApplication app; private GuiceFXMLLoader loader; private GuiceFXMLLoader.Result result; @BeforeMethod public void setup() throws Exception { app = new ControllerLookupGuiceApplication(); app.init(); loader = app.getInjector().getInstance(GuiceFXMLLoader.class); result = loader.load( getClass().getResource("/OuterLookupPane.fxml"), ResourceBundle.getBundle("ExamplePane", Locale.ENGLISH) ); } /** * In JavaFX 8 it seems that you can't overwrite the fx:id in an fx:include tag (which was possible in JavaFX 2). * That's the reason why this test was failing on JDK8 while it was running without problems on JDK7. */ @Test(enabled = false) public void parentControllerCanLookupNestedControllers() throws Exception { OuterLookupController controller = result.getController();
InnerLookupController controllerForPane1 = controller.getControllerForPane1();
cathive/fx-guice
src/test/java/com/cathive/fx/guice/ControllerLookupApplicationTest.java
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java // @FXMLController // public class InnerLookupController implements IdentifiableController { // // @FXML // private Parent root; // // @Override // public String getId() { // return ParentIDFinder.getParentId(root); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java // @FXMLController // public class OuterLookupController { // // @Inject // private ControllerLookup controllerLookup; // // public InnerLookupController getControllerForPane1() { // return controllerLookup.lookup("examplePane1"); // } // // public InnerLookupController getControllerForPane2() { // return controllerLookup.lookup("examplePane2"); // } // // public IdentifiableController getAnyController(String id) { // return controllerLookup.lookup(id); // } // }
import com.cathive.fx.guice.lookupexample.OuterLookupController; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.ProvisionException; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javafx.stage.Stage; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.lookupexample.InnerLookupController;
assertNotNull(controllerForPane1); assertNotNull(controllerForPane2); } @Test(expectedExceptions={IllegalArgumentException.class}) public void illegalArgumentExceptionThrownWhenNoControllerExistsWithMatchingID() throws Exception { OuterLookupController controller = result.getController(); controller.getAnyController("Frederick"); } @Test public void provisionExceptionThrownInjectingAControllerLookupOutsideOfScope() throws Exception { boolean threw = false; try { app.getInjector().getInstance(HasControllerLookup.class); } catch (ProvisionException e) { // a provision exception is thrown by Guice, the cause is the // IllegalStateException thrown by the module because a // ControllerLookup cannot be injected while not loading an FXML control. assertTrue(e.getCause() instanceof IllegalStateException); threw = true; } assertTrue(threw); } static class HasControllerLookup { @Inject
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/InnerLookupController.java // @FXMLController // public class InnerLookupController implements IdentifiableController { // // @FXML // private Parent root; // // @Override // public String getId() { // return ParentIDFinder.getParentId(root); // } // } // // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java // @FXMLController // public class OuterLookupController { // // @Inject // private ControllerLookup controllerLookup; // // public InnerLookupController getControllerForPane1() { // return controllerLookup.lookup("examplePane1"); // } // // public InnerLookupController getControllerForPane2() { // return controllerLookup.lookup("examplePane2"); // } // // public IdentifiableController getAnyController(String id) { // return controllerLookup.lookup(id); // } // } // Path: src/test/java/com/cathive/fx/guice/ControllerLookupApplicationTest.java import com.cathive.fx.guice.lookupexample.OuterLookupController; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.ProvisionException; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import javafx.stage.Stage; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.lookupexample.InnerLookupController; assertNotNull(controllerForPane1); assertNotNull(controllerForPane2); } @Test(expectedExceptions={IllegalArgumentException.class}) public void illegalArgumentExceptionThrownWhenNoControllerExistsWithMatchingID() throws Exception { OuterLookupController controller = result.getController(); controller.getAnyController("Frederick"); } @Test public void provisionExceptionThrownInjectingAControllerLookupOutsideOfScope() throws Exception { boolean threw = false; try { app.getInjector().getInstance(HasControllerLookup.class); } catch (ProvisionException e) { // a provision exception is thrown by Guice, the cause is the // IllegalStateException thrown by the module because a // ControllerLookup cannot be injected while not loading an FXML control. assertTrue(e.getCause() instanceof IllegalStateException); threw = true; } assertTrue(threw); } static class HasControllerLookup { @Inject
ControllerLookup controllerLookup;
cathive/fx-guice
src/main/java/com/cathive/fx/guice/GuiceFXMLLoader.java
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLComponentBuilderFactory.java // @Singleton // public final class FXMLComponentBuilderFactory implements BuilderFactory { // // @Inject private Injector injector; // // private static final Logger LOGGER = Logger.getLogger(FXMLComponentBuilderFactory.class.getName()); // private final JavaFXBuilderFactory defaultBuilderFactory = new JavaFXBuilderFactory(); // // @SuppressWarnings({ "rawtypes", "unchecked" }) // @Override // public Builder<?> getBuilder(final Class<?> componentClass) { // final String className = componentClass.getName(); // LOGGER.log(Level.FINE, "Searching builder for component class '{0}'.", className); // if (componentClass.isAnnotationPresent(FXMLComponent.class)) { // LOGGER.log(Level.FINE, "Creating FXMLComponentBuilder for class '{0}'.", className); // return new FXMLComponentBuilder(injector, componentClass); // } // // Fall back to the default builder factory if we are not dealing with a FXMLComponent class. // return defaultBuilderFactory.getBuilder(componentClass); // } // // } // // Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingScope.java // @Singleton // public final class FXMLLoadingScope implements Scope { // // private GuiceFXMLLoader fxmlLoader; // // private Set<IdentifiableController> identifiables; // // public FXMLLoadingScope() { // super(); // } // // // /** // * Enter the scope. From here on in, controllers implementing // * {@link IdentifiableController} and annotated wih {@link FXMLController} will // * be retrievable from any {@link ControllerLookup} instance that is // * injected. // * @param fxmlLoader // * The FXML Loader to be used within this scope. // */ // public void enter(final GuiceFXMLLoader fxmlLoader) { // this.fxmlLoader = fxmlLoader; // this.identifiables = new HashSet<>(); // } // // /** // * End the scope. // */ // public void exit() { // this.identifiables = null; // this.fxmlLoader = null; // } // // @Override // public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { // return new Provider<T>() { // @Override // public T get() { // final T providedObject = unscoped.get(); // if (identifiables != null && providedObject instanceof IdentifiableController) { // final IdentifiableController identifiable = (IdentifiableController) providedObject; // identifiables.add(identifiable); // } // return providedObject; // } // }; // } // // public <T> T getInstance(final String controllerId) { // for (final IdentifiableController identifiable: identifiables) { // if (identifiable.getId().equals(controllerId)) { // return (T) identifiable; // } // } // // TODO Throw an exception maybe? // return null; // } // // public Collection<IdentifiableController> getIdentifiables() { // return identifiables; // } // // /** // * Checks whether the FXML Loading Scope is currently being used. // * @return {@code true} if this scope is currently active, {@code false} otherwise. // */ // public boolean isActive() { // return (identifiables != null); // } // // }
import com.cathive.fx.guice.fxml.FXMLComponentBuilderFactory; import com.cathive.fx.guice.fxml.FXMLLoadingScope; import com.google.inject.Inject; import com.google.inject.Injector; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.ResourceBundle;
/* * Copyright (C) 2012-2015 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * If you want to `guicify` your JavaFX experience you can use an instance of * this class instead of the FXMLLoader that ships with JavaFX. * <p>The easiest way to use this class is by just injecting it into your * JavaFX application in the right places.</p> * @see javafx.fxml.FXMLLoader * @author Benjamin P. Jung */ public class GuiceFXMLLoader { /** * Guice Injector that will be used to fetch an instance of our `controller * class`. */ private final Injector injector; /** * The loading scope that is being entered when loading FXML files. */
// Path: src/main/java/com/cathive/fx/guice/fxml/FXMLComponentBuilderFactory.java // @Singleton // public final class FXMLComponentBuilderFactory implements BuilderFactory { // // @Inject private Injector injector; // // private static final Logger LOGGER = Logger.getLogger(FXMLComponentBuilderFactory.class.getName()); // private final JavaFXBuilderFactory defaultBuilderFactory = new JavaFXBuilderFactory(); // // @SuppressWarnings({ "rawtypes", "unchecked" }) // @Override // public Builder<?> getBuilder(final Class<?> componentClass) { // final String className = componentClass.getName(); // LOGGER.log(Level.FINE, "Searching builder for component class '{0}'.", className); // if (componentClass.isAnnotationPresent(FXMLComponent.class)) { // LOGGER.log(Level.FINE, "Creating FXMLComponentBuilder for class '{0}'.", className); // return new FXMLComponentBuilder(injector, componentClass); // } // // Fall back to the default builder factory if we are not dealing with a FXMLComponent class. // return defaultBuilderFactory.getBuilder(componentClass); // } // // } // // Path: src/main/java/com/cathive/fx/guice/fxml/FXMLLoadingScope.java // @Singleton // public final class FXMLLoadingScope implements Scope { // // private GuiceFXMLLoader fxmlLoader; // // private Set<IdentifiableController> identifiables; // // public FXMLLoadingScope() { // super(); // } // // // /** // * Enter the scope. From here on in, controllers implementing // * {@link IdentifiableController} and annotated wih {@link FXMLController} will // * be retrievable from any {@link ControllerLookup} instance that is // * injected. // * @param fxmlLoader // * The FXML Loader to be used within this scope. // */ // public void enter(final GuiceFXMLLoader fxmlLoader) { // this.fxmlLoader = fxmlLoader; // this.identifiables = new HashSet<>(); // } // // /** // * End the scope. // */ // public void exit() { // this.identifiables = null; // this.fxmlLoader = null; // } // // @Override // public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { // return new Provider<T>() { // @Override // public T get() { // final T providedObject = unscoped.get(); // if (identifiables != null && providedObject instanceof IdentifiableController) { // final IdentifiableController identifiable = (IdentifiableController) providedObject; // identifiables.add(identifiable); // } // return providedObject; // } // }; // } // // public <T> T getInstance(final String controllerId) { // for (final IdentifiableController identifiable: identifiables) { // if (identifiable.getId().equals(controllerId)) { // return (T) identifiable; // } // } // // TODO Throw an exception maybe? // return null; // } // // public Collection<IdentifiableController> getIdentifiables() { // return identifiables; // } // // /** // * Checks whether the FXML Loading Scope is currently being used. // * @return {@code true} if this scope is currently active, {@code false} otherwise. // */ // public boolean isActive() { // return (identifiables != null); // } // // } // Path: src/main/java/com/cathive/fx/guice/GuiceFXMLLoader.java import com.cathive.fx.guice.fxml.FXMLComponentBuilderFactory; import com.cathive.fx.guice.fxml.FXMLLoadingScope; import com.google.inject.Inject; import com.google.inject.Injector; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.ResourceBundle; /* * Copyright (C) 2012-2015 The Cat Hive Developers. * * 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.cathive.fx.guice; /** * If you want to `guicify` your JavaFX experience you can use an instance of * this class instead of the FXMLLoader that ships with JavaFX. * <p>The easiest way to use this class is by just injecting it into your * JavaFX application in the right places.</p> * @see javafx.fxml.FXMLLoader * @author Benjamin P. Jung */ public class GuiceFXMLLoader { /** * Guice Injector that will be used to fetch an instance of our `controller * class`. */ private final Injector injector; /** * The loading scope that is being entered when loading FXML files. */
private final FXMLLoadingScope fxmlLoadingScope;
cathive/fx-guice
src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/main/java/com/cathive/fx/guice/controllerlookup/IdentifiableController.java // public interface IdentifiableController { // // /** // * @return The string ID that can be used to lookup this controller. This // * could be hard coded or could return the ID set on the FXML for // * this control in the {@link Parent}. // */ // String getId(); // // }
import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.controllerlookup.IdentifiableController; import com.google.inject.Inject;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.lookupexample; @FXMLController public class OuterLookupController { @Inject
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/main/java/com/cathive/fx/guice/controllerlookup/IdentifiableController.java // public interface IdentifiableController { // // /** // * @return The string ID that can be used to lookup this controller. This // * could be hard coded or could return the ID set on the FXML for // * this control in the {@link Parent}. // */ // String getId(); // // } // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.controllerlookup.IdentifiableController; import com.google.inject.Inject; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.lookupexample; @FXMLController public class OuterLookupController { @Inject
private ControllerLookup controllerLookup;
cathive/fx-guice
src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/main/java/com/cathive/fx/guice/controllerlookup/IdentifiableController.java // public interface IdentifiableController { // // /** // * @return The string ID that can be used to lookup this controller. This // * could be hard coded or could return the ID set on the FXML for // * this control in the {@link Parent}. // */ // String getId(); // // }
import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.controllerlookup.IdentifiableController; import com.google.inject.Inject;
/* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.lookupexample; @FXMLController public class OuterLookupController { @Inject private ControllerLookup controllerLookup; public InnerLookupController getControllerForPane1() { return controllerLookup.lookup("examplePane1"); } public InnerLookupController getControllerForPane2() { return controllerLookup.lookup("examplePane2"); }
// Path: src/main/java/com/cathive/fx/guice/controllerlookup/ControllerLookup.java // public final class ControllerLookup { // // private final Collection<IdentifiableController> identifiables; // // public ControllerLookup(Collection<IdentifiableController> identifiables) { // super(); // this.identifiables = identifiables; // } // // /** // * Returns a controller instance with the given ID. // * // * @param id // * The string ID of the controller as returned by // * {@link IdentifiableController#getId()} // * @return // * The controller with the given ID that has just been // * looked up. // * @throws IllegalArgumentException // * thrown if a controller cannot be found with the given ID. // */ // @SuppressWarnings("unchecked") // public <T> T lookup(final String id) { // for (final IdentifiableController controller : identifiables) { // if(controller.getId().equals(id)) { // return (T) controller; // } // } // throw new IllegalArgumentException("Could not find a controller with the ID '" + id + "'"); // } // } // // Path: src/main/java/com/cathive/fx/guice/controllerlookup/IdentifiableController.java // public interface IdentifiableController { // // /** // * @return The string ID that can be used to lookup this controller. This // * could be hard coded or could return the ID set on the FXML for // * this control in the {@link Parent}. // */ // String getId(); // // } // Path: src/test/java/com/cathive/fx/guice/lookupexample/OuterLookupController.java import com.cathive.fx.guice.FXMLController; import com.cathive.fx.guice.controllerlookup.ControllerLookup; import com.cathive.fx.guice.controllerlookup.IdentifiableController; import com.google.inject.Inject; /* * Copyright (C) 2012 The Cat Hive Developers. * * 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.cathive.fx.guice.lookupexample; @FXMLController public class OuterLookupController { @Inject private ControllerLookup controllerLookup; public InnerLookupController getControllerForPane1() { return controllerLookup.lookup("examplePane1"); } public InnerLookupController getControllerForPane2() { return controllerLookup.lookup("examplePane2"); }
public IdentifiableController getAnyController(String id) {
stucchio/Hobo
test/TestColor.java
// Path: src/org/styloot/hobo/CIELabColor.java // public class CIELabColor { // public final double L; // public final double a; // public final double b; // public CIELabColor(double li, double ai, double bi) { // L = li; a = ai; b = bi; // } // // public static CIELabColor CIELabFromRGB(int r, int g, int b) { // return CIELabFromRGB((byte)(r-128), (byte)(g-128), (byte)(b-128)); // } // // public static CIELabColor CIELabFromRGB(byte r, byte g, byte b) { // //First Calculate XYZ // double var_R = ( (double)(r+128) / 255.0); // double var_G = ( (double)(g+128) / 255.0); // double var_B = ( (double)(b+128) / 255.0); // // if (var_R > 0.04045) { // var_R = Math.pow(( ( var_R + 0.055 ) / 1.055 ), 2.4); // } else { // var_R /= 12.92; // } // if (var_G > 0.04045) { // var_G = Math.pow(( ( var_G + 0.055 ) / 1.055 ), 2.4); // } else { // var_G /= 12.92; // } // if (var_B > 0.04045) { // var_B = Math.pow(( ( var_B + 0.055 ) / 1.055 ), 2.4); // } else { // var_B /= 12.92; // } // var_R *= 100; // var_G *= 100; // var_B *= 100; // // double X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805; // double Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722; // double Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505; // // //Now convert to CIE // double var_X = X / ref_X; // double var_Y = Y / ref_Y; // double var_Z = Z / ref_Z; // // if (var_X > 0.008856) // var_X = Math.pow(var_X, 1.0/3.0 ); // else // var_X = ( 7.787 * var_X ) + ( 16. / 116. ); // if (var_Y > 0.008856) // var_Y = Math.pow(var_Y, 1.0/3.0 ); // else // var_Y = ( 7.787 * var_Y ) + ( 16. / 116. ); // if (var_Z > 0.008856) // var_Z = Math.pow(var_Z, 1.0/3.0 ); // else // var_Z = ( 7.787 * var_Z ) + ( 16. / 116. ); // return new CIELabColor(( 116. * var_Y ) - 16.0, 500. * ( var_X - var_Y ), 200. * ( var_Y - var_Z )); // } // // private static final double ref_X = 95.047; // private static final double ref_Y = 100.000; // private static final double ref_Z = 108.883; // // private static final double KL = 1; // private static final double K1 = 0.045; // private static final double K2 = 0.015; // public static final double SQRT_REGULARIZATION = 0.00001; // // public double distanceTo(CIELabColor other) { // //Color distance // return Math.sqrt(distance2To(other)); // } // // public static double distance2(double xL, double xa, double xb, double yL, double ya, double yb) { // /* This version does the math without boxing/unboxing overhead. // */ // double dL = xL - yL; // double da = xa - ya; // double db = xb - yb; // double Cx = Math.sqrt(xa*xa+xb*xb + SQRT_REGULARIZATION); // double Cy = Math.sqrt(ya*ya+yb*yb + SQRT_REGULARIZATION); // double dC = Cx - Cy; // double dH = Math.sqrt(da*da+db*db-dC*dC); // return (Math.pow(dL/KL,2) + Math.pow(dC/(1+K1*Cy), 2) + Math.pow(dH/(1+K2*Cy), 2)); // } // // public static double distance2(CIELabColor base, double yL, double ya, double yb) { // return distance2(base.L, base.a, base.b, yL, ya, yb); // } // // public double distance2To(CIELabColor other) { // //Color distance squared // return distance2(L, a, b, other.L, other.a, other.b); // } // // public String toString() { // return "CIELab(" + L + ", " + a + ", " + b + ")"; // } // }
import org.junit.*; import static org.junit.Assert.*; import org.styloot.hobo.CIELabColor; import java.util.*;
//package org.styloot.hobo.test; public class TestColor { public static final double TOLERANCE=1e-12; @Test public void testFromRGB(){
// Path: src/org/styloot/hobo/CIELabColor.java // public class CIELabColor { // public final double L; // public final double a; // public final double b; // public CIELabColor(double li, double ai, double bi) { // L = li; a = ai; b = bi; // } // // public static CIELabColor CIELabFromRGB(int r, int g, int b) { // return CIELabFromRGB((byte)(r-128), (byte)(g-128), (byte)(b-128)); // } // // public static CIELabColor CIELabFromRGB(byte r, byte g, byte b) { // //First Calculate XYZ // double var_R = ( (double)(r+128) / 255.0); // double var_G = ( (double)(g+128) / 255.0); // double var_B = ( (double)(b+128) / 255.0); // // if (var_R > 0.04045) { // var_R = Math.pow(( ( var_R + 0.055 ) / 1.055 ), 2.4); // } else { // var_R /= 12.92; // } // if (var_G > 0.04045) { // var_G = Math.pow(( ( var_G + 0.055 ) / 1.055 ), 2.4); // } else { // var_G /= 12.92; // } // if (var_B > 0.04045) { // var_B = Math.pow(( ( var_B + 0.055 ) / 1.055 ), 2.4); // } else { // var_B /= 12.92; // } // var_R *= 100; // var_G *= 100; // var_B *= 100; // // double X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805; // double Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722; // double Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505; // // //Now convert to CIE // double var_X = X / ref_X; // double var_Y = Y / ref_Y; // double var_Z = Z / ref_Z; // // if (var_X > 0.008856) // var_X = Math.pow(var_X, 1.0/3.0 ); // else // var_X = ( 7.787 * var_X ) + ( 16. / 116. ); // if (var_Y > 0.008856) // var_Y = Math.pow(var_Y, 1.0/3.0 ); // else // var_Y = ( 7.787 * var_Y ) + ( 16. / 116. ); // if (var_Z > 0.008856) // var_Z = Math.pow(var_Z, 1.0/3.0 ); // else // var_Z = ( 7.787 * var_Z ) + ( 16. / 116. ); // return new CIELabColor(( 116. * var_Y ) - 16.0, 500. * ( var_X - var_Y ), 200. * ( var_Y - var_Z )); // } // // private static final double ref_X = 95.047; // private static final double ref_Y = 100.000; // private static final double ref_Z = 108.883; // // private static final double KL = 1; // private static final double K1 = 0.045; // private static final double K2 = 0.015; // public static final double SQRT_REGULARIZATION = 0.00001; // // public double distanceTo(CIELabColor other) { // //Color distance // return Math.sqrt(distance2To(other)); // } // // public static double distance2(double xL, double xa, double xb, double yL, double ya, double yb) { // /* This version does the math without boxing/unboxing overhead. // */ // double dL = xL - yL; // double da = xa - ya; // double db = xb - yb; // double Cx = Math.sqrt(xa*xa+xb*xb + SQRT_REGULARIZATION); // double Cy = Math.sqrt(ya*ya+yb*yb + SQRT_REGULARIZATION); // double dC = Cx - Cy; // double dH = Math.sqrt(da*da+db*db-dC*dC); // return (Math.pow(dL/KL,2) + Math.pow(dC/(1+K1*Cy), 2) + Math.pow(dH/(1+K2*Cy), 2)); // } // // public static double distance2(CIELabColor base, double yL, double ya, double yb) { // return distance2(base.L, base.a, base.b, yL, ya, yb); // } // // public double distance2To(CIELabColor other) { // //Color distance squared // return distance2(L, a, b, other.L, other.a, other.b); // } // // public String toString() { // return "CIELab(" + L + ", " + a + ", " + b + ")"; // } // } // Path: test/TestColor.java import org.junit.*; import static org.junit.Assert.*; import org.styloot.hobo.CIELabColor; import java.util.*; //package org.styloot.hobo.test; public class TestColor { public static final double TOLERANCE=1e-12; @Test public void testFromRGB(){
CIELabColor c = CIELabColor.CIELabFromRGB(255,16,0);
stucchio/Hobo
src/org/styloot/hobo/thriftserver/HoboServerImpl.java
// Path: src/org/styloot/hobo/hoboindex/HoboIndex.java // public interface HoboIndex { // public Iterator<Item> find(String cat, Collection<String> features, CIELabColor color, double dist, int minPrice, int maxPrice); // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.thrift.TException; import org.styloot.hobo.gen.*; import org.styloot.hobo.*; import org.styloot.hobo.hoboindex.HoboIndex; import java.util.*;
package org.styloot.hobo.thriftserver; class HoboServerImpl implements Hobo.Iface { private static final Logger log = LoggerFactory.getLogger(HoboServerImpl.class);
// Path: src/org/styloot/hobo/hoboindex/HoboIndex.java // public interface HoboIndex { // public Iterator<Item> find(String cat, Collection<String> features, CIELabColor color, double dist, int minPrice, int maxPrice); // } // Path: src/org/styloot/hobo/thriftserver/HoboServerImpl.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.thrift.TException; import org.styloot.hobo.gen.*; import org.styloot.hobo.*; import org.styloot.hobo.hoboindex.HoboIndex; import java.util.*; package org.styloot.hobo.thriftserver; class HoboServerImpl implements Hobo.Iface { private static final Logger log = LoggerFactory.getLogger(HoboServerImpl.class);
public HoboServerImpl(HoboIndex idx, int ps) {
stucchio/Hobo
benchmarks/HasFeaturesBenchmark.java
// Path: src/org/styloot/hobo/Item.java // public class Item implements Comparable<Item>{ // public Item(String i, String c, Collection<String> f, int q, CIELabColor clr, int cst) { // id = i; category = Category.getCategory(c); quality = q; // features = Feature.getFeatures(f); // color = clr; // cost = cst; // } // // public Item(String i, String c, String[] f, int q, CIELabColor clr, int cst) { // id = i; category = Category.getCategory(c); quality = q; // features = Feature.getFeatures(f); // color = clr; // cost = cst; // } // // public Item(String i, String c, Vector<String> f, int q, CIELabColor clr, int cst) { // this(i, c, f.toArray((String[])(new String[]{})), q, clr, cst); // } // // public boolean hasFeatures(Collection<String> feats) { // log.warn("Calling item.hasFeatures(Collection<String> features) - will be inefficient."); // if (feats == null) { // return true; // } // return hasFeatures(Feature.getFeatures(feats)); // } // // public Feature[] getFeatures() { // return features; // } // // public boolean hasFeature(Feature f) { // for (Feature f2 : features) { // if (f == f2) { // return true; // } // } // return false; // } // // public boolean hasFeatures(Feature[] feats) { // if (feats == null) { // return true; // } // if (features == null && feats.length > 0) { //We definitely don't have the feature // return false; // } // for (Feature f : feats) { // if (!hasFeature(f)) { // return false; // } // } // return true; // } // // public boolean hasFeaturesSorted(Feature[] feats) { // return Util.isSubsetSorted(feats, features); // } // // public double colorDist2From(CIELabColor other) { // return other.distance2To(color); // } // // public CIELabColor getColor() { // return color; // } // // public final String id; // public final Category category; // public final Feature[] features; // public final int quality; // public final CIELabColor color; // public final int cost; // // public int compareTo(Item o) { // if (quality != o.quality) { // return (o.quality - quality); // } // return id.compareTo(o.id); // } // // private static final Logger log = LoggerFactory.getLogger(Item.class); // }
import org.styloot.hobo.*; import org.styloot.hobo.Item; import java.util.*;
public class HasFeaturesBenchmark { public static final int NUM_RUNS = 100000; public static final int FEATURES_PER_ITEM = 10; public static final int FEATURES_PER_QUERY = 4; private static Vector<String> randomFeatureSet(int numFeatures) { Vector<String> f = new Vector<String>(); for (int j=0;j<numFeatures;j++) { if (Math.random() > 0.5) { f.add("feature-" + j); } } return f; }
// Path: src/org/styloot/hobo/Item.java // public class Item implements Comparable<Item>{ // public Item(String i, String c, Collection<String> f, int q, CIELabColor clr, int cst) { // id = i; category = Category.getCategory(c); quality = q; // features = Feature.getFeatures(f); // color = clr; // cost = cst; // } // // public Item(String i, String c, String[] f, int q, CIELabColor clr, int cst) { // id = i; category = Category.getCategory(c); quality = q; // features = Feature.getFeatures(f); // color = clr; // cost = cst; // } // // public Item(String i, String c, Vector<String> f, int q, CIELabColor clr, int cst) { // this(i, c, f.toArray((String[])(new String[]{})), q, clr, cst); // } // // public boolean hasFeatures(Collection<String> feats) { // log.warn("Calling item.hasFeatures(Collection<String> features) - will be inefficient."); // if (feats == null) { // return true; // } // return hasFeatures(Feature.getFeatures(feats)); // } // // public Feature[] getFeatures() { // return features; // } // // public boolean hasFeature(Feature f) { // for (Feature f2 : features) { // if (f == f2) { // return true; // } // } // return false; // } // // public boolean hasFeatures(Feature[] feats) { // if (feats == null) { // return true; // } // if (features == null && feats.length > 0) { //We definitely don't have the feature // return false; // } // for (Feature f : feats) { // if (!hasFeature(f)) { // return false; // } // } // return true; // } // // public boolean hasFeaturesSorted(Feature[] feats) { // return Util.isSubsetSorted(feats, features); // } // // public double colorDist2From(CIELabColor other) { // return other.distance2To(color); // } // // public CIELabColor getColor() { // return color; // } // // public final String id; // public final Category category; // public final Feature[] features; // public final int quality; // public final CIELabColor color; // public final int cost; // // public int compareTo(Item o) { // if (quality != o.quality) { // return (o.quality - quality); // } // return id.compareTo(o.id); // } // // private static final Logger log = LoggerFactory.getLogger(Item.class); // } // Path: benchmarks/HasFeaturesBenchmark.java import org.styloot.hobo.*; import org.styloot.hobo.Item; import java.util.*; public class HasFeaturesBenchmark { public static final int NUM_RUNS = 100000; public static final int FEATURES_PER_ITEM = 10; public static final int FEATURES_PER_QUERY = 4; private static Vector<String> randomFeatureSet(int numFeatures) { Vector<String> f = new Vector<String>(); for (int j=0;j<numFeatures;j++) { if (Math.random() > 0.5) { f.add("feature-" + j); } } return f; }
private static Item[] getItems(int numItems) {
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/data/PersistentObjectStorage.java
// Path: core/src/main/java/com/fenlisproject/elf/core/io/KeyBasedObjectIO.java // public interface KeyBasedObjectIO { // ObjectInput getObjectInput(String key) throws IOException; // // ObjectOutput getObjectOutput(String key) throws IOException; // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/SecurityUtils.java // public class SecurityUtils { // // public static String md5(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // digest.update(str.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) { // h = "0" + h; // } // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // // public static String base64Encode(String text) { // try { // byte[] data = text.getBytes("UTF-8"); // return Base64.encodeToString(data, Base64.NO_WRAP); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // // public static String base64Decode(String text) { // byte[] data = Base64.decode(text, Base64.NO_WRAP); // try { // return new String(data, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // }
import android.content.Context; import com.fenlisproject.elf.core.io.KeyBasedObjectIO; import com.fenlisproject.elf.core.util.SecurityUtils; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable;
/* * Copyright (C) 2015 Steven Lewi * * 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.fenlisproject.elf.core.data; public class PersistentObjectStorage implements DataStorage<Serializable>, KeyBasedObjectIO { protected Context mContext; public PersistentObjectStorage(Context context) { this.mContext = context.getApplicationContext(); } @Override public Serializable get(String key) { return get(key, Serializable.class); } public <V extends Serializable> V get(String key, Class<V> vClass) { synchronized (this) {
// Path: core/src/main/java/com/fenlisproject/elf/core/io/KeyBasedObjectIO.java // public interface KeyBasedObjectIO { // ObjectInput getObjectInput(String key) throws IOException; // // ObjectOutput getObjectOutput(String key) throws IOException; // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/SecurityUtils.java // public class SecurityUtils { // // public static String md5(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // digest.update(str.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) { // h = "0" + h; // } // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // // public static String base64Encode(String text) { // try { // byte[] data = text.getBytes("UTF-8"); // return Base64.encodeToString(data, Base64.NO_WRAP); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // // public static String base64Decode(String text) { // byte[] data = Base64.decode(text, Base64.NO_WRAP); // try { // return new String(data, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/data/PersistentObjectStorage.java import android.content.Context; import com.fenlisproject.elf.core.io.KeyBasedObjectIO; import com.fenlisproject.elf.core.util.SecurityUtils; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; /* * Copyright (C) 2015 Steven Lewi * * 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.fenlisproject.elf.core.data; public class PersistentObjectStorage implements DataStorage<Serializable>, KeyBasedObjectIO { protected Context mContext; public PersistentObjectStorage(Context context) { this.mContext = context.getApplicationContext(); } @Override public Serializable get(String key) { return get(key, Serializable.class); } public <V extends Serializable> V get(String key, Class<V> vClass) { synchronized (this) {
String hashedKey = SecurityUtils.md5(key);
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/data/PreferencesStorage.java
// Path: core/src/main/java/com/fenlisproject/elf/core/util/SecurityUtils.java // public class SecurityUtils { // // public static String md5(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // digest.update(str.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) { // h = "0" + h; // } // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // // public static String base64Encode(String text) { // try { // byte[] data = text.getBytes("UTF-8"); // return Base64.encodeToString(data, Base64.NO_WRAP); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // // public static String base64Decode(String text) { // byte[] data = Base64.decode(text, Base64.NO_WRAP); // try { // return new String(data, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // }
import android.content.Context; import android.content.SharedPreferences; import com.fenlisproject.elf.core.util.SecurityUtils; import java.io.Serializable;
/* * Copyright (C) 2015 Steven Lewi * * 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.fenlisproject.elf.core.data; public class PreferencesStorage implements DataStorage<Serializable> { private Context mContext; private String mBundleName; private SharedPreferences mPreferences; public PreferencesStorage(Context context, String bundleName) { this(context, bundleName, Context.MODE_PRIVATE); } public PreferencesStorage(Context context, String bundleName, int mode) { this.mContext = context.getApplicationContext(); this.mBundleName = bundleName; this.mPreferences = mContext.getSharedPreferences(bundleName, mode); } public <V extends Serializable> V get(String key, Class<V> vClass) { synchronized (this) {
// Path: core/src/main/java/com/fenlisproject/elf/core/util/SecurityUtils.java // public class SecurityUtils { // // public static String md5(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // digest.update(str.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) { // h = "0" + h; // } // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // // public static String base64Encode(String text) { // try { // byte[] data = text.getBytes("UTF-8"); // return Base64.encodeToString(data, Base64.NO_WRAP); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // // public static String base64Decode(String text) { // byte[] data = Base64.decode(text, Base64.NO_WRAP); // try { // return new String(data, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/data/PreferencesStorage.java import android.content.Context; import android.content.SharedPreferences; import com.fenlisproject.elf.core.util.SecurityUtils; import java.io.Serializable; /* * Copyright (C) 2015 Steven Lewi * * 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.fenlisproject.elf.core.data; public class PreferencesStorage implements DataStorage<Serializable> { private Context mContext; private String mBundleName; private SharedPreferences mPreferences; public PreferencesStorage(Context context, String bundleName) { this(context, bundleName, Context.MODE_PRIVATE); } public PreferencesStorage(Context context, String bundleName, int mode) { this.mContext = context.getApplicationContext(); this.mBundleName = bundleName; this.mPreferences = mContext.getSharedPreferences(bundleName, mode); } public <V extends Serializable> V get(String key, Class<V> vClass) { synchronized (this) {
String hashedKey = SecurityUtils.md5(mBundleName + "." + key);
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedCheckBox.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatCheckBox; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage;
package com.fenlisproject.elf.core.widget; public class ExtendedCheckBox extends AppCompatCheckBox implements FontFace, ExtendedAttributes { private String mFontName; private String mFontFormat; public ExtendedCheckBox(Context context) { this(context, null); } public ExtendedCheckBox(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.checkboxStyle); } public ExtendedCheckBox(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) {
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedCheckBox.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatCheckBox; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; package com.fenlisproject.elf.core.widget; public class ExtendedCheckBox extends AppCompatCheckBox implements FontFace, ExtendedAttributes { private String mFontName; private String mFontFormat; public ExtendedCheckBox(Context context) { this(context, null); } public ExtendedCheckBox(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.checkboxStyle); } public ExtendedCheckBox(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) {
if (getContext().getApplicationContext() instanceof BaseApplication) {
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedCheckBox.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatCheckBox; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage;
if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) { if (getContext().getApplicationContext() instanceof BaseApplication) { if (attrs != null) { TypedArray style = getContext().obtainStyledAttributes( attrs, R.styleable.ExtendedTextView, 0, 0); String fontName = style.getString(R.styleable.ExtendedTextView_fontName); String fontFormat = style.getString(R.styleable.ExtendedTextView_fontFormat); style.recycle(); setFontFace(fontName, fontFormat != null ? fontFormat : FontFace.FORMAT_TTF); } } else { throw new RuntimeException("Your application class must extends BaseApplication"); } } @Override public void setFontFace(String fontName) { setFontFace(fontName, FontFace.FORMAT_TTF); } @Override public void setFontFace(String fontName, String fontFormat) { this.mFontName = fontName; this.mFontFormat = fontFormat; BaseApplication app = ((BaseApplication) getContext().getApplicationContext());
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedCheckBox.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatCheckBox; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) { if (getContext().getApplicationContext() instanceof BaseApplication) { if (attrs != null) { TypedArray style = getContext().obtainStyledAttributes( attrs, R.styleable.ExtendedTextView, 0, 0); String fontName = style.getString(R.styleable.ExtendedTextView_fontName); String fontFormat = style.getString(R.styleable.ExtendedTextView_fontFormat); style.recycle(); setFontFace(fontName, fontFormat != null ? fontFormat : FontFace.FORMAT_TTF); } } else { throw new RuntimeException("Your application class must extends BaseApplication"); } } @Override public void setFontFace(String fontName) { setFontFace(fontName, FontFace.FORMAT_TTF); } @Override public void setFontFace(String fontName, String fontFormat) { this.mFontName = fontName; this.mFontFormat = fontFormat; BaseApplication app = ((BaseApplication) getContext().getApplicationContext());
MemoryStorage<Typeface> fontCache = app.getFontCache();
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedRadioButton.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatRadioButton; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage;
package com.fenlisproject.elf.core.widget; public class ExtendedRadioButton extends AppCompatRadioButton implements FontFace, ExtendedAttributes { private String mFontName; private String mFontFormat; public ExtendedRadioButton(Context context) { this(context, null); } public ExtendedRadioButton(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.radioButtonStyle); } public ExtendedRadioButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) {
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedRadioButton.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatRadioButton; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; package com.fenlisproject.elf.core.widget; public class ExtendedRadioButton extends AppCompatRadioButton implements FontFace, ExtendedAttributes { private String mFontName; private String mFontFormat; public ExtendedRadioButton(Context context) { this(context, null); } public ExtendedRadioButton(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.radioButtonStyle); } public ExtendedRadioButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) {
if (getContext().getApplicationContext() instanceof BaseApplication) {
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedRadioButton.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatRadioButton; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage;
if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) { if (getContext().getApplicationContext() instanceof BaseApplication) { if (attrs != null) { TypedArray style = getContext().obtainStyledAttributes( attrs, R.styleable.ExtendedTextView, 0, 0); String fontName = style.getString(R.styleable.ExtendedTextView_fontName); String fontFormat = style.getString(R.styleable.ExtendedTextView_fontFormat); style.recycle(); setFontFace(fontName, fontFormat != null ? fontFormat : FontFace.FORMAT_TTF); } } else { throw new RuntimeException("Your application class must extends BaseApplication"); } } @Override public void setFontFace(String fontName) { setFontFace(fontName, FontFace.FORMAT_TTF); } @Override public void setFontFace(String fontName, String fontFormat) { this.mFontName = fontName; this.mFontFormat = fontFormat; BaseApplication app = ((BaseApplication) getContext().getApplicationContext());
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedRadioButton.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatRadioButton; import android.util.AttributeSet; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; if (!isInEditMode()) { initExtendedAttributes(attrs); } } public void initExtendedAttributes(AttributeSet attrs) { if (getContext().getApplicationContext() instanceof BaseApplication) { if (attrs != null) { TypedArray style = getContext().obtainStyledAttributes( attrs, R.styleable.ExtendedTextView, 0, 0); String fontName = style.getString(R.styleable.ExtendedTextView_fontName); String fontFormat = style.getString(R.styleable.ExtendedTextView_fontFormat); style.recycle(); setFontFace(fontName, fontFormat != null ? fontFormat : FontFace.FORMAT_TTF); } } else { throw new RuntimeException("Your application class must extends BaseApplication"); } } @Override public void setFontFace(String fontName) { setFontFace(fontName, FontFace.FORMAT_TTF); } @Override public void setFontFace(String fontName, String fontFormat) { this.mFontName = fontName; this.mFontFormat = fontFormat; BaseApplication app = ((BaseApplication) getContext().getApplicationContext());
MemoryStorage<Typeface> fontCache = app.getFontCache();
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/net/HttpRequest.java
// Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/FileFormData.java // public class FileFormData implements MultipartFormData { // // private final String key; // private final File value; // // public FileFormData(String key, File value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public File getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/MultipartFormData.java // public interface MultipartFormData { // // String getKey(); // // Object getValue(); // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/StringFormData.java // public class StringFormData implements MultipartFormData { // // private final String key; // private final String value; // // public StringFormData(String key, String value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static boolean writeStreamToFile(InputStream in, String outFileName) { // OutputStream out = null; // try { // out = new FileOutputStream(outFileName); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean copy(String source, String destination) { // InputStream in = null; // OutputStream out = null; // try { // in = new FileInputStream(source); // out = new FileOutputStream(destination); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean delete(String fileName) { // File file = new File(fileName); // return file.delete(); // } // // public static boolean isExist(String fileName) { // return new File(fileName).exists(); // } // // public static void createDirsIfNotExist(String path) { // File file = new File(path); // if (!file.exists()) { // file.mkdirs(); // } // } // // public static String getMimeType(File file) { // String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath()); // if (extension != null) { // MimeTypeMap mime = MimeTypeMap.getSingleton(); // return mime.getMimeTypeFromExtension(extension); // } // return null; // } // // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.fenlisproject.elf.core.net.entity.FileFormData; import com.fenlisproject.elf.core.net.entity.MultipartFormData; import com.fenlisproject.elf.core.net.entity.StringFormData; import com.fenlisproject.elf.core.util.FileUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List;
public String getTextContent() { try { BufferedReader r = new BufferedReader(getStreamReader()); StringBuilder sb = new StringBuilder(); String line; while ((line = r.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } public static class Builder { public static final int DEFAULT_CONNECTION_TIMEOUT = 12000; public static final int DEFAULT_READ_TIMEOUT = 30000; public static final String CRLF = "\r\n"; public static final String TWO_HYPHENS = "--"; private static final String BOUNDARY = "ElfHttpRequestBoundary"; private int mConnectionTimeout; private int mReadTimeout; private boolean isUseCache; private String mRequestUrl; private RequestMethod mRequestMethod; private List<NameValuePair> mUrlParams; private List<NameValuePair> mUrlEncodedFormData;
// Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/FileFormData.java // public class FileFormData implements MultipartFormData { // // private final String key; // private final File value; // // public FileFormData(String key, File value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public File getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/MultipartFormData.java // public interface MultipartFormData { // // String getKey(); // // Object getValue(); // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/StringFormData.java // public class StringFormData implements MultipartFormData { // // private final String key; // private final String value; // // public StringFormData(String key, String value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static boolean writeStreamToFile(InputStream in, String outFileName) { // OutputStream out = null; // try { // out = new FileOutputStream(outFileName); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean copy(String source, String destination) { // InputStream in = null; // OutputStream out = null; // try { // in = new FileInputStream(source); // out = new FileOutputStream(destination); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean delete(String fileName) { // File file = new File(fileName); // return file.delete(); // } // // public static boolean isExist(String fileName) { // return new File(fileName).exists(); // } // // public static void createDirsIfNotExist(String path) { // File file = new File(path); // if (!file.exists()) { // file.mkdirs(); // } // } // // public static String getMimeType(File file) { // String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath()); // if (extension != null) { // MimeTypeMap mime = MimeTypeMap.getSingleton(); // return mime.getMimeTypeFromExtension(extension); // } // return null; // } // // } // Path: core/src/main/java/com/fenlisproject/elf/core/net/HttpRequest.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.fenlisproject.elf.core.net.entity.FileFormData; import com.fenlisproject.elf.core.net.entity.MultipartFormData; import com.fenlisproject.elf.core.net.entity.StringFormData; import com.fenlisproject.elf.core.util.FileUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; public String getTextContent() { try { BufferedReader r = new BufferedReader(getStreamReader()); StringBuilder sb = new StringBuilder(); String line; while ((line = r.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } public static class Builder { public static final int DEFAULT_CONNECTION_TIMEOUT = 12000; public static final int DEFAULT_READ_TIMEOUT = 30000; public static final String CRLF = "\r\n"; public static final String TWO_HYPHENS = "--"; private static final String BOUNDARY = "ElfHttpRequestBoundary"; private int mConnectionTimeout; private int mReadTimeout; private boolean isUseCache; private String mRequestUrl; private RequestMethod mRequestMethod; private List<NameValuePair> mUrlParams; private List<NameValuePair> mUrlEncodedFormData;
private List<MultipartFormData> mFormData;
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/net/HttpRequest.java
// Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/FileFormData.java // public class FileFormData implements MultipartFormData { // // private final String key; // private final File value; // // public FileFormData(String key, File value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public File getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/MultipartFormData.java // public interface MultipartFormData { // // String getKey(); // // Object getValue(); // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/StringFormData.java // public class StringFormData implements MultipartFormData { // // private final String key; // private final String value; // // public StringFormData(String key, String value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static boolean writeStreamToFile(InputStream in, String outFileName) { // OutputStream out = null; // try { // out = new FileOutputStream(outFileName); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean copy(String source, String destination) { // InputStream in = null; // OutputStream out = null; // try { // in = new FileInputStream(source); // out = new FileOutputStream(destination); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean delete(String fileName) { // File file = new File(fileName); // return file.delete(); // } // // public static boolean isExist(String fileName) { // return new File(fileName).exists(); // } // // public static void createDirsIfNotExist(String path) { // File file = new File(path); // if (!file.exists()) { // file.mkdirs(); // } // } // // public static String getMimeType(File file) { // String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath()); // if (extension != null) { // MimeTypeMap mime = MimeTypeMap.getSingleton(); // return mime.getMimeTypeFromExtension(extension); // } // return null; // } // // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.fenlisproject.elf.core.net.entity.FileFormData; import com.fenlisproject.elf.core.net.entity.MultipartFormData; import com.fenlisproject.elf.core.net.entity.StringFormData; import com.fenlisproject.elf.core.util.FileUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List;
public Builder(String url) { this.mRequestUrl = url; this.isUseCache = false; this.isForceUseCache = false; this.mRequestMethod = RequestMethod.GET; this.mUrlParams = new ArrayList<>(); this.mUrlEncodedFormData = new ArrayList<>(); this.mFormData = new ArrayList<>(); this.mHeaders = new ArrayList<>(); this.mConnectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.mReadTimeout = DEFAULT_READ_TIMEOUT; this.mRetryCount = 1; } public Builder addRequestHeader(String key, String value) { this.mHeaders.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlParams(String key, String value) { this.mUrlParams.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlEncodedFormData(String key, String value) { this.mUrlEncodedFormData.add(new BasicNameValuePair(key, value)); return this; } public Builder addFormData(String key, String value) {
// Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/FileFormData.java // public class FileFormData implements MultipartFormData { // // private final String key; // private final File value; // // public FileFormData(String key, File value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public File getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/MultipartFormData.java // public interface MultipartFormData { // // String getKey(); // // Object getValue(); // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/StringFormData.java // public class StringFormData implements MultipartFormData { // // private final String key; // private final String value; // // public StringFormData(String key, String value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static boolean writeStreamToFile(InputStream in, String outFileName) { // OutputStream out = null; // try { // out = new FileOutputStream(outFileName); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean copy(String source, String destination) { // InputStream in = null; // OutputStream out = null; // try { // in = new FileInputStream(source); // out = new FileOutputStream(destination); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean delete(String fileName) { // File file = new File(fileName); // return file.delete(); // } // // public static boolean isExist(String fileName) { // return new File(fileName).exists(); // } // // public static void createDirsIfNotExist(String path) { // File file = new File(path); // if (!file.exists()) { // file.mkdirs(); // } // } // // public static String getMimeType(File file) { // String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath()); // if (extension != null) { // MimeTypeMap mime = MimeTypeMap.getSingleton(); // return mime.getMimeTypeFromExtension(extension); // } // return null; // } // // } // Path: core/src/main/java/com/fenlisproject/elf/core/net/HttpRequest.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.fenlisproject.elf.core.net.entity.FileFormData; import com.fenlisproject.elf.core.net.entity.MultipartFormData; import com.fenlisproject.elf.core.net.entity.StringFormData; import com.fenlisproject.elf.core.util.FileUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; public Builder(String url) { this.mRequestUrl = url; this.isUseCache = false; this.isForceUseCache = false; this.mRequestMethod = RequestMethod.GET; this.mUrlParams = new ArrayList<>(); this.mUrlEncodedFormData = new ArrayList<>(); this.mFormData = new ArrayList<>(); this.mHeaders = new ArrayList<>(); this.mConnectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.mReadTimeout = DEFAULT_READ_TIMEOUT; this.mRetryCount = 1; } public Builder addRequestHeader(String key, String value) { this.mHeaders.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlParams(String key, String value) { this.mUrlParams.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlEncodedFormData(String key, String value) { this.mUrlEncodedFormData.add(new BasicNameValuePair(key, value)); return this; } public Builder addFormData(String key, String value) {
this.mFormData.add(new StringFormData(key, value));
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/net/HttpRequest.java
// Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/FileFormData.java // public class FileFormData implements MultipartFormData { // // private final String key; // private final File value; // // public FileFormData(String key, File value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public File getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/MultipartFormData.java // public interface MultipartFormData { // // String getKey(); // // Object getValue(); // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/StringFormData.java // public class StringFormData implements MultipartFormData { // // private final String key; // private final String value; // // public StringFormData(String key, String value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static boolean writeStreamToFile(InputStream in, String outFileName) { // OutputStream out = null; // try { // out = new FileOutputStream(outFileName); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean copy(String source, String destination) { // InputStream in = null; // OutputStream out = null; // try { // in = new FileInputStream(source); // out = new FileOutputStream(destination); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean delete(String fileName) { // File file = new File(fileName); // return file.delete(); // } // // public static boolean isExist(String fileName) { // return new File(fileName).exists(); // } // // public static void createDirsIfNotExist(String path) { // File file = new File(path); // if (!file.exists()) { // file.mkdirs(); // } // } // // public static String getMimeType(File file) { // String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath()); // if (extension != null) { // MimeTypeMap mime = MimeTypeMap.getSingleton(); // return mime.getMimeTypeFromExtension(extension); // } // return null; // } // // }
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.fenlisproject.elf.core.net.entity.FileFormData; import com.fenlisproject.elf.core.net.entity.MultipartFormData; import com.fenlisproject.elf.core.net.entity.StringFormData; import com.fenlisproject.elf.core.util.FileUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List;
this.mUrlParams = new ArrayList<>(); this.mUrlEncodedFormData = new ArrayList<>(); this.mFormData = new ArrayList<>(); this.mHeaders = new ArrayList<>(); this.mConnectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.mReadTimeout = DEFAULT_READ_TIMEOUT; this.mRetryCount = 1; } public Builder addRequestHeader(String key, String value) { this.mHeaders.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlParams(String key, String value) { this.mUrlParams.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlEncodedFormData(String key, String value) { this.mUrlEncodedFormData.add(new BasicNameValuePair(key, value)); return this; } public Builder addFormData(String key, String value) { this.mFormData.add(new StringFormData(key, value)); return this; } public Builder addFormData(String key, File value) {
// Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/FileFormData.java // public class FileFormData implements MultipartFormData { // // private final String key; // private final File value; // // public FileFormData(String key, File value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public File getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/MultipartFormData.java // public interface MultipartFormData { // // String getKey(); // // Object getValue(); // } // // Path: core/src/main/java/com/fenlisproject/elf/core/net/entity/StringFormData.java // public class StringFormData implements MultipartFormData { // // private final String key; // private final String value; // // public StringFormData(String key, String value) { // this.key = key; // this.value = value; // } // // @Override // public String getKey() { // return key; // } // // @Override // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/util/FileUtils.java // public class FileUtils { // // private FileUtils() { // } // // public static boolean writeStreamToFile(InputStream in, String outFileName) { // OutputStream out = null; // try { // out = new FileOutputStream(outFileName); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean copy(String source, String destination) { // InputStream in = null; // OutputStream out = null; // try { // in = new FileInputStream(source); // out = new FileOutputStream(destination); // byte[] buf = new byte[1024]; // int len; // while ((len = in.read(buf)) > 0) { // out.write(buf, 0, len); // } // in.close(); // out.close(); // return true; // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // in.close(); // } catch (Exception e) { // e.printStackTrace(); // } // try { // out.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // return false; // } // // public static boolean delete(String fileName) { // File file = new File(fileName); // return file.delete(); // } // // public static boolean isExist(String fileName) { // return new File(fileName).exists(); // } // // public static void createDirsIfNotExist(String path) { // File file = new File(path); // if (!file.exists()) { // file.mkdirs(); // } // } // // public static String getMimeType(File file) { // String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath()); // if (extension != null) { // MimeTypeMap mime = MimeTypeMap.getSingleton(); // return mime.getMimeTypeFromExtension(extension); // } // return null; // } // // } // Path: core/src/main/java/com/fenlisproject/elf/core/net/HttpRequest.java import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.fenlisproject.elf.core.net.entity.FileFormData; import com.fenlisproject.elf.core.net.entity.MultipartFormData; import com.fenlisproject.elf.core.net.entity.StringFormData; import com.fenlisproject.elf.core.util.FileUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; this.mUrlParams = new ArrayList<>(); this.mUrlEncodedFormData = new ArrayList<>(); this.mFormData = new ArrayList<>(); this.mHeaders = new ArrayList<>(); this.mConnectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.mReadTimeout = DEFAULT_READ_TIMEOUT; this.mRetryCount = 1; } public Builder addRequestHeader(String key, String value) { this.mHeaders.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlParams(String key, String value) { this.mUrlParams.add(new BasicNameValuePair(key, value)); return this; } public Builder addUrlEncodedFormData(String key, String value) { this.mUrlEncodedFormData.add(new BasicNameValuePair(key, value)); return this; } public Builder addFormData(String key, String value) { this.mFormData.add(new StringFormData(key, value)); return this; } public Builder addFormData(String key, File value) {
this.mFormData.add(new FileFormData(key, value));
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // }
import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List;
} public boolean isMustValidEmail() { return mustValidEmail; } public void setMustValidEmail(boolean mustValidEmail) { this.mustValidEmail = mustValidEmail; } public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); }
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List; } public boolean isMustValidEmail() { return mustValidEmail; } public void setMustValidEmail(boolean mustValidEmail) { this.mustValidEmail = mustValidEmail; } public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); }
public List<Rule> getRules() {
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // }
import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List;
} public void setMustValidEmail(boolean mustValidEmail) { this.mustValidEmail = mustValidEmail; } public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); } public List<Rule> getRules() { Context c = getContext(); List<Rule> rules = new ArrayList<>(); if (isTrimmed) {
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List; } public void setMustValidEmail(boolean mustValidEmail) { this.mustValidEmail = mustValidEmail; } public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); } public List<Rule> getRules() { Context c = getContext(); List<Rule> rules = new ArrayList<>(); if (isTrimmed) {
rules.add(new Trimmed());
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // }
import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List;
this.mustValidEmail = mustValidEmail; } public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); } public List<Rule> getRules() { Context c = getContext(); List<Rule> rules = new ArrayList<>(); if (isTrimmed) { rules.add(new Trimmed()); } if (isRequired) {
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List; this.mustValidEmail = mustValidEmail; } public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); } public List<Rule> getRules() { Context c = getContext(); List<Rule> rules = new ArrayList<>(); if (isTrimmed) { rules.add(new Trimmed()); } if (isRequired) {
rules.add(new Required(c.getString(R.string.required_validation_message)));
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // }
import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List;
public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); } public List<Rule> getRules() { Context c = getContext(); List<Rule> rules = new ArrayList<>(); if (isTrimmed) { rules.add(new Trimmed()); } if (isRequired) { rules.add(new Required(c.getString(R.string.required_validation_message))); } if (mustValidEmail) {
// Path: core/src/main/java/com/fenlisproject/elf/core/base/BaseApplication.java // public class BaseApplication extends Application { // // private AppEnvironment mAppEnvironment; // private PreferencesStorage mDefaultPreferencesStorage; // private SessionStorage mDefaultSessionStorage; // private MemoryStorage<Typeface> fontCache; // // @Override // public void onCreate() { // super.onCreate(); // mAppEnvironment = new AppEnvironment(this); // mDefaultPreferencesStorage = new PreferencesStorage(this, Configs.DEFAULT_PREFERENCES_NAME); // mDefaultSessionStorage = new SessionStorage(this, mAppEnvironment.getSessionDirectory()); // fontCache = new MemoryStorage<>(Configs.DEFAULT_FONT_CACHE_SIZE); // } // // public AppEnvironment getAppEnvironment() { // return mAppEnvironment; // } // // public PreferencesStorage getDefaultPreferencesStorage() { // return mDefaultPreferencesStorage; // } // // public SessionStorage getDefaultSessionStorage() { // return mDefaultSessionStorage; // } // // public MemoryStorage<Typeface> getFontCache() { // return fontCache; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/data/MemoryStorage.java // public class MemoryStorage<T> implements DataStorage<T> { // // private final LruCache<String, T> cache; // // public MemoryStorage(int maxSize) { // cache = new LruCache<>(maxSize); // } // // @Override // public T get(String key) { // return cache.get(key); // } // // @Override // public boolean put(String key, T value) { // return cache.put(key, value) != null; // } // // @Override // public boolean remove(String key) { // return cache.remove(key) != null; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/Rule.java // public abstract class Rule { // // private String mValidationMessage; // // public Rule(String mValidationMessage) { // this.mValidationMessage = mValidationMessage; // } // // public abstract boolean validate(TextView view); // // public void apply(TextView view) { // if (view.getError() == null) { // view.setError(getValidationMessage()); // } else { // String errorValue = view.getError().toString(); // view.setError(errorValue + "\n" + getValidationMessage()); // } // } // // public String getValidationMessage() { // return mValidationMessage; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Match.java // public class Match extends Rule { // // private TextView compared; // // public Match(String message, TextView compared) { // super(message); // this.compared = compared; // } // // @Override // public boolean validate(TextView view) { // return view.getText().toString().equals(compared.getText().toString()); // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/MinimumLength.java // public class MinimumLength extends Rule { // // private int minLength; // // public MinimumLength(String message, int minLength) { // super(message); // this.minLength = minLength; // } // // @Override // public boolean validate(TextView view) { // return view.length() >= minLength; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Required.java // public class Required extends Rule { // // public Required(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return view.length() > 0; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/Trimmed.java // public class Trimmed extends Rule { // // public Trimmed() { // super(null); // } // // @Override // public boolean validate(TextView view) { // view.setText(view.getText().toString().trim()); // return true; // } // } // // Path: core/src/main/java/com/fenlisproject/elf/core/validator/rule/ValidEmail.java // public class ValidEmail extends Rule { // // public ValidEmail(String message) { // super(message); // } // // @Override // public boolean validate(TextView view) { // return Patterns.EMAIL_ADDRESS.matcher(view.getText()).matches(); // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/widget/ExtendedTextView.java import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.res.TypedArray; import android.graphics.Typeface; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.widget.TextView; import com.fenlisproject.elf.R; import com.fenlisproject.elf.core.base.BaseApplication; import com.fenlisproject.elf.core.data.MemoryStorage; import com.fenlisproject.elf.core.validator.Rule; import com.fenlisproject.elf.core.validator.rule.Match; import com.fenlisproject.elf.core.validator.rule.MinimumLength; import com.fenlisproject.elf.core.validator.rule.Required; import com.fenlisproject.elf.core.validator.rule.Trimmed; import com.fenlisproject.elf.core.validator.rule.ValidEmail; import java.util.ArrayList; import java.util.List; public int getMinLength() { return mMinLength; } public void setMinLength(int mMinLength) { this.mMinLength = mMinLength; } public int getMatchValueOf() { return mMatchValueOf; } public void setMatchValueOf(int mMatchValueOf) { this.mMatchValueOf = mMatchValueOf; } public String getValue() { return isTrimmed ? getText().toString().trim() : getText().toString(); } public List<Rule> getRules() { Context c = getContext(); List<Rule> rules = new ArrayList<>(); if (isTrimmed) { rules.add(new Trimmed()); } if (isRequired) { rules.add(new Required(c.getString(R.string.required_validation_message))); } if (mustValidEmail) {
rules.add(new ValidEmail(c.getString(R.string.email_validation_message)));
fenli/elf
core/src/main/java/com/fenlisproject/elf/core/data/SessionStorage.java
// Path: core/src/main/java/com/fenlisproject/elf/core/util/SecurityUtils.java // public class SecurityUtils { // // public static String md5(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // digest.update(str.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) { // h = "0" + h; // } // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // // public static String base64Encode(String text) { // try { // byte[] data = text.getBytes("UTF-8"); // return Base64.encodeToString(data, Base64.NO_WRAP); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // // public static String base64Decode(String text) { // byte[] data = Base64.decode(text, Base64.NO_WRAP); // try { // return new String(data, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // }
import android.content.Context; import com.fenlisproject.elf.core.util.SecurityUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable;
/* * Copyright (C) 2015 Steven Lewi * * 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.fenlisproject.elf.core.data; public class SessionStorage extends PersistentObjectStorage { protected String mStoragePath; public SessionStorage(Context context, String path) { super(context); this.mStoragePath = path; } public <V extends Serializable> SessionDataWrapper<V> getSessionData(String key, Class<V> vClass) { SessionDataWrapper<V> object = (SessionDataWrapper<V>) get(key, SessionDataWrapper.class); return object; } public boolean putSessionData(String key, Serializable value) { SessionDataWrapper object = new SessionDataWrapper(value); return put(key, object); } public boolean putSessionData(String key, Serializable value, long lifeSpan) { SessionDataWrapper object = new SessionDataWrapper(value, lifeSpan); return put(key, object); } @Override public boolean remove(String key) { synchronized (this) {
// Path: core/src/main/java/com/fenlisproject/elf/core/util/SecurityUtils.java // public class SecurityUtils { // // public static String md5(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // digest.update(str.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuffer hexString = new StringBuffer(); // for (int i = 0; i < messageDigest.length; i++) { // String h = Integer.toHexString(0xFF & messageDigest[i]); // while (h.length() < 2) { // h = "0" + h; // } // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // // public static String base64Encode(String text) { // try { // byte[] data = text.getBytes("UTF-8"); // return Base64.encodeToString(data, Base64.NO_WRAP); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // // public static String base64Decode(String text) { // byte[] data = Base64.decode(text, Base64.NO_WRAP); // try { // return new String(data, "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return null; // } // } // Path: core/src/main/java/com/fenlisproject/elf/core/data/SessionStorage.java import android.content.Context; import com.fenlisproject.elf.core.util.SecurityUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; /* * Copyright (C) 2015 Steven Lewi * * 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.fenlisproject.elf.core.data; public class SessionStorage extends PersistentObjectStorage { protected String mStoragePath; public SessionStorage(Context context, String path) { super(context); this.mStoragePath = path; } public <V extends Serializable> SessionDataWrapper<V> getSessionData(String key, Class<V> vClass) { SessionDataWrapper<V> object = (SessionDataWrapper<V>) get(key, SessionDataWrapper.class); return object; } public boolean putSessionData(String key, Serializable value) { SessionDataWrapper object = new SessionDataWrapper(value); return put(key, object); } public boolean putSessionData(String key, Serializable value, long lifeSpan) { SessionDataWrapper object = new SessionDataWrapper(value, lifeSpan); return put(key, object); } @Override public boolean remove(String key) { synchronized (this) {
String hashedKey = SecurityUtils.md5(key);
davidmoten/logan
src/test/java/com/github/davidmoten/logan/watcher/TestingUtil.java
// Path: src/main/java/com/github/davidmoten/logan/MessageSplitter.java // public class MessageSplitter { // // public static final String MESSAGE_PATTERN_DEFAULT = "(\\b[a-zA-Z](?:\\w| )*)=([^;|,]*)(;|\\||,|$)"; // private final Pattern pattern; // private final List<String> pairs; // // /** // * Constructor. // */ // public MessageSplitter() { // this(Pattern.compile(MESSAGE_PATTERN_DEFAULT)); // } // // /** // * Constructor. // * // * @param pattern // * pattern // */ // public MessageSplitter(Pattern pattern) { // this.pattern = pattern; // this.pairs = new ArrayList<>(); // } // // /** // * Extracts key value pairs using regex pattern defined in the constructor. // * // * @param s // * string to split // * @return map of key value pairs // */ // public Map<String, String> splitAsMap(String s) { // Map<String, String> map = Maps.newHashMap(); // split(s); // for (int i = 0; i < pairs.size(); i += 2) { // map.put(pairs.get(i), pairs.get(i + 1)); // } // return map; // } // // // not concurrency safe // // do this instead of creating a map to save allocations // public List<String> split(String s) { // pairs.clear(); // if (s != null && s.length() > 0) { // Matcher matcher = pattern.matcher(s); // while (matcher.find()) { // String value = matcher.group(2).trim(); // pairs.add(matcher.group(1).trim()); // pairs.add(value); // } // } // return pairs; // } // } // // Path: src/main/java/com/github/davidmoten/logan/config/Parser.java // public class Parser { // // @XmlElement(required = false) // public String sourcePattern; // @XmlElement(required = true) // public String pattern; // @XmlElement(required = true) // public String patternGroups; // @XmlElement(defaultValue = MessageSplitter.MESSAGE_PATTERN_DEFAULT) // public String messagePattern = MessageSplitter.MESSAGE_PATTERN_DEFAULT; // @XmlElement(required = true) // public List<String> timestampFormat; // @XmlElement(defaultValue = "UTC") // public String timezone = "UTC"; // @XmlElement(required = false, defaultValue = "false") // public boolean multiline; // // public Parser(String pattern, String patternGroups, String messagePattern, // List<String> timestampFormat, String timezone, boolean multiline, // String sourcePattern) { // super(); // this.pattern = pattern; // this.patternGroups = patternGroups; // this.messagePattern = messagePattern; // this.timestampFormat = timestampFormat; // this.timezone = timezone; // this.multiline = multiline; // this.sourcePattern = sourcePattern; // } // // /** // * Constructor. // */ // public Parser() { // // required for jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Parser [pattern="); // builder.append(pattern); // builder.append(", patternGroups="); // builder.append(patternGroups); // builder.append(", messagePattern="); // builder.append(messagePattern); // builder.append(", timestampFormat="); // builder.append(timestampFormat); // builder.append(", timezone="); // builder.append(timezone); // builder.append(", multiline="); // builder.append(multiline); // builder.append("]"); // return builder.toString(); // } // // }
import com.github.davidmoten.logan.MessageSplitter; import com.github.davidmoten.logan.config.Parser; import com.google.common.collect.Lists;
package com.github.davidmoten.logan.watcher; public class TestingUtil { static Parser createDefaultParser() { String pattern = "^(\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d\\.\\d\\d\\d) +(\\S+) +(\\S+) +(\\S+)? ?- (.*)$"; String patternGroups = "logTimestamp,logLevel,logLogger,threadName,logMsg"; String timestampFormat = "yyyy-MM-dd HH:mm:ss.SSS"; String timezone = "UTC"; String sourcePattern = "^[a-zA-Z][^\\.]*"; boolean multiline = false; return new Parser(pattern, patternGroups,
// Path: src/main/java/com/github/davidmoten/logan/MessageSplitter.java // public class MessageSplitter { // // public static final String MESSAGE_PATTERN_DEFAULT = "(\\b[a-zA-Z](?:\\w| )*)=([^;|,]*)(;|\\||,|$)"; // private final Pattern pattern; // private final List<String> pairs; // // /** // * Constructor. // */ // public MessageSplitter() { // this(Pattern.compile(MESSAGE_PATTERN_DEFAULT)); // } // // /** // * Constructor. // * // * @param pattern // * pattern // */ // public MessageSplitter(Pattern pattern) { // this.pattern = pattern; // this.pairs = new ArrayList<>(); // } // // /** // * Extracts key value pairs using regex pattern defined in the constructor. // * // * @param s // * string to split // * @return map of key value pairs // */ // public Map<String, String> splitAsMap(String s) { // Map<String, String> map = Maps.newHashMap(); // split(s); // for (int i = 0; i < pairs.size(); i += 2) { // map.put(pairs.get(i), pairs.get(i + 1)); // } // return map; // } // // // not concurrency safe // // do this instead of creating a map to save allocations // public List<String> split(String s) { // pairs.clear(); // if (s != null && s.length() > 0) { // Matcher matcher = pattern.matcher(s); // while (matcher.find()) { // String value = matcher.group(2).trim(); // pairs.add(matcher.group(1).trim()); // pairs.add(value); // } // } // return pairs; // } // } // // Path: src/main/java/com/github/davidmoten/logan/config/Parser.java // public class Parser { // // @XmlElement(required = false) // public String sourcePattern; // @XmlElement(required = true) // public String pattern; // @XmlElement(required = true) // public String patternGroups; // @XmlElement(defaultValue = MessageSplitter.MESSAGE_PATTERN_DEFAULT) // public String messagePattern = MessageSplitter.MESSAGE_PATTERN_DEFAULT; // @XmlElement(required = true) // public List<String> timestampFormat; // @XmlElement(defaultValue = "UTC") // public String timezone = "UTC"; // @XmlElement(required = false, defaultValue = "false") // public boolean multiline; // // public Parser(String pattern, String patternGroups, String messagePattern, // List<String> timestampFormat, String timezone, boolean multiline, // String sourcePattern) { // super(); // this.pattern = pattern; // this.patternGroups = patternGroups; // this.messagePattern = messagePattern; // this.timestampFormat = timestampFormat; // this.timezone = timezone; // this.multiline = multiline; // this.sourcePattern = sourcePattern; // } // // /** // * Constructor. // */ // public Parser() { // // required for jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Parser [pattern="); // builder.append(pattern); // builder.append(", patternGroups="); // builder.append(patternGroups); // builder.append(", messagePattern="); // builder.append(messagePattern); // builder.append(", timestampFormat="); // builder.append(timestampFormat); // builder.append(", timezone="); // builder.append(timezone); // builder.append(", multiline="); // builder.append(multiline); // builder.append("]"); // return builder.toString(); // } // // } // Path: src/test/java/com/github/davidmoten/logan/watcher/TestingUtil.java import com.github.davidmoten.logan.MessageSplitter; import com.github.davidmoten.logan.config.Parser; import com.google.common.collect.Lists; package com.github.davidmoten.logan.watcher; public class TestingUtil { static Parser createDefaultParser() { String pattern = "^(\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d\\.\\d\\d\\d) +(\\S+) +(\\S+) +(\\S+)? ?- (.*)$"; String patternGroups = "logTimestamp,logLevel,logLogger,threadName,logMsg"; String timestampFormat = "yyyy-MM-dd HH:mm:ss.SSS"; String timezone = "UTC"; String sourcePattern = "^[a-zA-Z][^\\.]*"; boolean multiline = false; return new Parser(pattern, patternGroups,
MessageSplitter.MESSAGE_PATTERN_DEFAULT,
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParser.java
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp";
import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps;
* @return parsed LogEntry */ public synchronized LogEntry parse(String source, String line) { if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups();
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp"; // Path: src/main/java/com/github/davidmoten/logan/LogParser.java import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; * @return parsed LogEntry */ public synchronized LogEntry parse(String source, String line) { if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups();
String timestamp = getGroup(matcher, map.get(TIMESTAMP));
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParser.java
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp";
import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps;
*/ public synchronized LogEntry parse(String source, String line) { if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP));
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp"; // Path: src/main/java/com/github/davidmoten/logan/LogParser.java import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; */ public synchronized LogEntry parse(String source, String line) { if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP));
String level = getGroup(matcher, map.get(LEVEL));
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParser.java
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp";
import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps;
public synchronized LogEntry parse(String source, String line) { if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL));
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp"; // Path: src/main/java/com/github/davidmoten/logan/LogParser.java import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; public synchronized LogEntry parse(String source, String line) { if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL));
String logger = getGroup(matcher, map.get(LOGGER));
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParser.java
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp";
import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps;
if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL)); String logger = getGroup(matcher, map.get(LOGGER));
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp"; // Path: src/main/java/com/github/davidmoten/logan/LogParser.java import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; if (line == null) return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL)); String logger = getGroup(matcher, map.get(LOGGER));
String threadName = getGroup(matcher, map.get(THREAD_NAME));
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParser.java
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp";
import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps;
return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL)); String logger = getGroup(matcher, map.get(LOGGER)); String threadName = getGroup(matcher, map.get(THREAD_NAME));
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp"; // Path: src/main/java/com/github/davidmoten/logan/LogParser.java import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; return null; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL)); String logger = getGroup(matcher, map.get(LOGGER)); String threadName = getGroup(matcher, map.get(THREAD_NAME));
String msg = getGroup(matcher, map.get(MSG));
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParser.java
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp";
import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps;
else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL)); String logger = getGroup(matcher, map.get(LOGGER)); String threadName = getGroup(matcher, map.get(THREAD_NAME)); String msg = getGroup(matcher, map.get(MSG));
// Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LEVEL = "logLevel"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String LOGGER = "logLogger"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String METHOD = "logMethod"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String MSG = "logMsg"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String THREAD_NAME = "threadName"; // // Path: src/main/java/com/github/davidmoten/logan/Field.java // public static final String TIMESTAMP = "logTimestamp"; // Path: src/main/java/com/github/davidmoten/logan/LogParser.java import static com.github.davidmoten.logan.Field.LEVEL; import static com.github.davidmoten.logan.Field.LOGGER; import static com.github.davidmoten.logan.Field.METHOD; import static com.github.davidmoten.logan.Field.MSG; import static com.github.davidmoten.logan.Field.THREAD_NAME; import static com.github.davidmoten.logan.Field.TIMESTAMP; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import com.google.common.collect.BiMap; import com.google.common.collect.Maps; else { if (options.isMultiline() && (previousLine == null)) { previousLine = line; return null; } else { StringBuilder candidate = new StringBuilder(line); if (options.isMultiline()) { candidate.insert(0, "ZZZ"); candidate.insert(0, previousLine); } Matcher matcher = options.getPattern().matcher(candidate); if (matcher.find()) { previousLine = null; return createLogEntry(source, matcher, line); } else { previousLine = line; return null; } } } } private LogEntry createLogEntry(String source, Matcher matcher, String line) { BiMap<String, Integer> map = options.getPatternGroups(); String timestamp = getGroup(matcher, map.get(TIMESTAMP)); String level = getGroup(matcher, map.get(LEVEL)); String logger = getGroup(matcher, map.get(LOGGER)); String threadName = getGroup(matcher, map.get(THREAD_NAME)); String msg = getGroup(matcher, map.get(MSG));
String method = getGroup(matcher, map.get(METHOD));
davidmoten/logan
src/main/java/com/github/davidmoten/logan/TailerNonFollowing.java
// Path: src/main/java/org/apache/commons/io/input/TailerListener2.java // public interface TailerListener2 { // // /** // * The tailer will call this method during construction, // * giving the listener a method of stopping the tailer. // * @param tailer the tailer. // */ // void init(Tailer2 tailer); // // /** // * This method is called if the tailed file is not found. // * <p> // * <b>Note:</b> this is called from the tailer thread. // */ // void fileNotFound(); // // /** // * Called if a file rotation is detected. // * // * This method is called before the file is reopened, and fileNotFound may // * be called if the new file has not yet been created. // * <p> // * <b>Note:</b> this is called from the tailer thread. // */ // void fileRotated(); // // /** // * Handles a line from a Tailer. // * <p> // * <b>Note:</b> this is called from the tailer thread. // * @param line the line. // */ // void handle(String line); // // /** // * Handles an Exception . // * <p> // * <b>Note:</b> this is called from the tailer thread. // * @param ex the exception. // */ // void handle(Exception ex); // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.input.TailerListener2;
package com.github.davidmoten.logan; public class TailerNonFollowing implements Runnable { private volatile boolean keepGoing = true; private final File file;
// Path: src/main/java/org/apache/commons/io/input/TailerListener2.java // public interface TailerListener2 { // // /** // * The tailer will call this method during construction, // * giving the listener a method of stopping the tailer. // * @param tailer the tailer. // */ // void init(Tailer2 tailer); // // /** // * This method is called if the tailed file is not found. // * <p> // * <b>Note:</b> this is called from the tailer thread. // */ // void fileNotFound(); // // /** // * Called if a file rotation is detected. // * // * This method is called before the file is reopened, and fileNotFound may // * be called if the new file has not yet been created. // * <p> // * <b>Note:</b> this is called from the tailer thread. // */ // void fileRotated(); // // /** // * Handles a line from a Tailer. // * <p> // * <b>Note:</b> this is called from the tailer thread. // * @param line the line. // */ // void handle(String line); // // /** // * Handles an Exception . // * <p> // * <b>Note:</b> this is called from the tailer thread. // * @param ex the exception. // */ // void handle(Exception ex); // // } // Path: src/main/java/com/github/davidmoten/logan/TailerNonFollowing.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.input.TailerListener2; package com.github.davidmoten.logan; public class TailerNonFollowing implements Runnable { private volatile boolean keepGoing = true; private final File file;
private final TailerListener2 listener;
davidmoten/logan
src/main/java/com/github/davidmoten/logan/servlet/LogServlet.java
// Path: src/main/java/com/github/davidmoten/logan/servlet/ServletUtil.java // public static long getMandatoryLong(HttpServletRequest req, String name) { // if (req.getParameter(name) == null) // throw new RuntimeException("parameter '" + name + "' is mandatory"); // else // try { // return Long.parseLong(req.getParameter(name)); // } catch (NumberFormatException e) { // throw new RuntimeException( // "parameter '" + name + "' could not be parsed as a Long: " + req.getParameter(name), e); // } // }
import static com.github.davidmoten.logan.servlet.ServletUtil.getMandatoryLong; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
package com.github.davidmoten.logan.servlet; //@WebServlet(urlPatterns = { "/log" }) public class LogServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Path: src/main/java/com/github/davidmoten/logan/servlet/ServletUtil.java // public static long getMandatoryLong(HttpServletRequest req, String name) { // if (req.getParameter(name) == null) // throw new RuntimeException("parameter '" + name + "' is mandatory"); // else // try { // return Long.parseLong(req.getParameter(name)); // } catch (NumberFormatException e) { // throw new RuntimeException( // "parameter '" + name + "' could not be parsed as a Long: " + req.getParameter(name), e); // } // } // Path: src/main/java/com/github/davidmoten/logan/servlet/LogServlet.java import static com.github.davidmoten.logan.servlet.ServletUtil.getMandatoryLong; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; package com.github.davidmoten.logan.servlet; //@WebServlet(urlPatterns = { "/log" }) public class LogServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
long startTime = getMandatoryLong(req, "start");
davidmoten/logan
src/main/java/com/github/davidmoten/logan/config/Parser.java
// Path: src/main/java/com/github/davidmoten/logan/MessageSplitter.java // public class MessageSplitter { // // public static final String MESSAGE_PATTERN_DEFAULT = "(\\b[a-zA-Z](?:\\w| )*)=([^;|,]*)(;|\\||,|$)"; // private final Pattern pattern; // private final List<String> pairs; // // /** // * Constructor. // */ // public MessageSplitter() { // this(Pattern.compile(MESSAGE_PATTERN_DEFAULT)); // } // // /** // * Constructor. // * // * @param pattern // * pattern // */ // public MessageSplitter(Pattern pattern) { // this.pattern = pattern; // this.pairs = new ArrayList<>(); // } // // /** // * Extracts key value pairs using regex pattern defined in the constructor. // * // * @param s // * string to split // * @return map of key value pairs // */ // public Map<String, String> splitAsMap(String s) { // Map<String, String> map = Maps.newHashMap(); // split(s); // for (int i = 0; i < pairs.size(); i += 2) { // map.put(pairs.get(i), pairs.get(i + 1)); // } // return map; // } // // // not concurrency safe // // do this instead of creating a map to save allocations // public List<String> split(String s) { // pairs.clear(); // if (s != null && s.length() > 0) { // Matcher matcher = pattern.matcher(s); // while (matcher.find()) { // String value = matcher.group(2).trim(); // pairs.add(matcher.group(1).trim()); // pairs.add(value); // } // } // return pairs; // } // }
import java.util.List; import javax.xml.bind.annotation.XmlElement; import com.github.davidmoten.logan.MessageSplitter;
package com.github.davidmoten.logan.config; /** * * Parser options. * */ public class Parser { @XmlElement(required = false) public String sourcePattern; @XmlElement(required = true) public String pattern; @XmlElement(required = true) public String patternGroups;
// Path: src/main/java/com/github/davidmoten/logan/MessageSplitter.java // public class MessageSplitter { // // public static final String MESSAGE_PATTERN_DEFAULT = "(\\b[a-zA-Z](?:\\w| )*)=([^;|,]*)(;|\\||,|$)"; // private final Pattern pattern; // private final List<String> pairs; // // /** // * Constructor. // */ // public MessageSplitter() { // this(Pattern.compile(MESSAGE_PATTERN_DEFAULT)); // } // // /** // * Constructor. // * // * @param pattern // * pattern // */ // public MessageSplitter(Pattern pattern) { // this.pattern = pattern; // this.pairs = new ArrayList<>(); // } // // /** // * Extracts key value pairs using regex pattern defined in the constructor. // * // * @param s // * string to split // * @return map of key value pairs // */ // public Map<String, String> splitAsMap(String s) { // Map<String, String> map = Maps.newHashMap(); // split(s); // for (int i = 0; i < pairs.size(); i += 2) { // map.put(pairs.get(i), pairs.get(i + 1)); // } // return map; // } // // // not concurrency safe // // do this instead of creating a map to save allocations // public List<String> split(String s) { // pairs.clear(); // if (s != null && s.length() > 0) { // Matcher matcher = pattern.matcher(s); // while (matcher.find()) { // String value = matcher.group(2).trim(); // pairs.add(matcher.group(1).trim()); // pairs.add(value); // } // } // return pairs; // } // } // Path: src/main/java/com/github/davidmoten/logan/config/Parser.java import java.util.List; import javax.xml.bind.annotation.XmlElement; import com.github.davidmoten.logan.MessageSplitter; package com.github.davidmoten.logan.config; /** * * Parser options. * */ public class Parser { @XmlElement(required = false) public String sourcePattern; @XmlElement(required = true) public String pattern; @XmlElement(required = true) public String patternGroups;
@XmlElement(defaultValue = MessageSplitter.MESSAGE_PATTERN_DEFAULT)
davidmoten/logan
src/main/java/com/github/davidmoten/logan/watcher/FileTailerStandard.java
// Path: src/main/java/com/github/davidmoten/logan/Data.java // public interface Data { // // Buckets execute(BucketQuery query); // // Stream<String> getLogs(long startTime, long finishTime); // // Stream<LogEntry> find(long startTime, long finishTime); // // /** // * Adds a {@link LogEntry} to the data. // * // * @param entry entry // * @return this this // */ // Data add(LogEntry entry); // // long getNumEntries(); // // /** // * Returns total number of entries added so far (older entries may have been // * discarded so this is not the same as the current number of entries). // * // * @return total number of entries added so far // */ // long getNumEntriesAdded(); // // NavigableSet<String> getKeys(); // // NavigableSet<String> getSources(); // // void close() throws Exception; // // } // // Path: src/main/java/com/github/davidmoten/logan/LogFile.java // public class LogFile { // // private static Logger log = Logger.getLogger(LogFile.class.getName()); // // private final File file; // private final long checkIntervalMs; // private Runnable tailer; // private final LogParser parser; // private final ExecutorService executor; // private final String source; // // public LogFile(File file, String source, long checkIntervalMs, LogParser parser, ExecutorService executor) { // this.file = file; // this.source = source; // this.checkIntervalMs = checkIntervalMs; // this.parser = parser; // this.executor = executor; // createFileIfDoesntExist(file); // } // // @VisibleForTesting // static void createFileIfDoesntExist(File file) { // if (!file.exists()) // try { // if (!file.createNewFile()) // throw new RuntimeException("could not create file: " + file); // } catch (IOException e) { // throw new RuntimeException("could not create file: " + file, e); // } // } // // private static int BUFFER_SIZE = 2 * 4096; // // /** // * Starts a thread that tails a file from the start and reports extracted info // * from the lines to the database. // * // * @param data // * data // * @param follow // * follow // */ // public void tail(Data data, boolean follow) { // // TailerListener2 listener = createListener(data); // // if (follow) // // tail from the start of the file and watch for future changes // tailer = new Tailer2(file, listener, checkIntervalMs, false, BUFFER_SIZE); // // else // tailer = new TailerNonFollowing(file, listener, BUFFER_SIZE); // // // start in separate thread // log.info("starting tailer thread"); // executor.execute(tailer); // } // // public static class SampleResult { // // private final LinkedHashMap<LogEntry, List<String>> entries; // private final List<String> unparsedLines; // // public SampleResult(LinkedHashMap<LogEntry, List<String>> entries, List<String> unparsedLines) { // this.entries = entries; // this.unparsedLines = unparsedLines; // } // // public List<String> getUnparsedLines() { // return unparsedLines; // } // // public LinkedHashMap<LogEntry, List<String>> getEntries() { // return entries; // } // // } // // public SampleResult sample(int numLines) { // // try { // FileInputStream fis = new FileInputStream(file); // BufferedReader br = new BufferedReader(new InputStreamReader(fis)); // // String line; // List<String> lines = Lists.newArrayList(); // LinkedHashMap<LogEntry, List<String>> entries = new LinkedHashMap<LogEntry, List<String>>(); // int lineCount = 0; // while (lineCount < numLines && (line = br.readLine()) != null) { // LogEntry entry = parser.parse(source, line); // lines.add(line); // if (entry != null) { // entries.put(entry, lines); // lines = Lists.newArrayList(); // } // lineCount++; // } // br.close(); // return new SampleResult(entries, lines); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Stops the tailer (and thus its thread). // */ // public void stop() { // if (tailer != null) // if (tailer instanceof Tailer) // ((Tailer) tailer).stop(); // else if (tailer instanceof TailerNonFollowing) // ((TailerNonFollowing) tailer).stop(); // } // // private TailerListener2 createListener(final Data data) { // return new TailerListener2() { // private final Data db = data; // // @Override // public void fileNotFound() { // log.warning("file not found"); // } // // @Override // public void fileRotated() { // log.info("file rotated"); // } // // @Override // public synchronized void handle(String line) { // try { // LogEntry entry = parser.parse(source, line); // if (entry != null) { // db.add(entry); // log.fine("added"); // } // } catch (Throwable e) { // log.log(Level.WARNING, e.getMessage(), e); // } // } // // @Override // public void handle(Exception e) { // log.log(Level.WARNING, "handle exception " + e.getMessage(), e); // } // // @Override // public void init(Tailer2 tailer) { // log.info("init"); // } // }; // } // // public File getFile() { // return file; // } // }
import com.github.davidmoten.logan.Data; import com.github.davidmoten.logan.LogFile;
package com.github.davidmoten.logan.watcher; public class FileTailerStandard implements FileTailer { public enum Singleton { INSTANCE; private final FileTailerStandard instance = new FileTailerStandard(); public FileTailerStandard instance() { return instance; } } @Override
// Path: src/main/java/com/github/davidmoten/logan/Data.java // public interface Data { // // Buckets execute(BucketQuery query); // // Stream<String> getLogs(long startTime, long finishTime); // // Stream<LogEntry> find(long startTime, long finishTime); // // /** // * Adds a {@link LogEntry} to the data. // * // * @param entry entry // * @return this this // */ // Data add(LogEntry entry); // // long getNumEntries(); // // /** // * Returns total number of entries added so far (older entries may have been // * discarded so this is not the same as the current number of entries). // * // * @return total number of entries added so far // */ // long getNumEntriesAdded(); // // NavigableSet<String> getKeys(); // // NavigableSet<String> getSources(); // // void close() throws Exception; // // } // // Path: src/main/java/com/github/davidmoten/logan/LogFile.java // public class LogFile { // // private static Logger log = Logger.getLogger(LogFile.class.getName()); // // private final File file; // private final long checkIntervalMs; // private Runnable tailer; // private final LogParser parser; // private final ExecutorService executor; // private final String source; // // public LogFile(File file, String source, long checkIntervalMs, LogParser parser, ExecutorService executor) { // this.file = file; // this.source = source; // this.checkIntervalMs = checkIntervalMs; // this.parser = parser; // this.executor = executor; // createFileIfDoesntExist(file); // } // // @VisibleForTesting // static void createFileIfDoesntExist(File file) { // if (!file.exists()) // try { // if (!file.createNewFile()) // throw new RuntimeException("could not create file: " + file); // } catch (IOException e) { // throw new RuntimeException("could not create file: " + file, e); // } // } // // private static int BUFFER_SIZE = 2 * 4096; // // /** // * Starts a thread that tails a file from the start and reports extracted info // * from the lines to the database. // * // * @param data // * data // * @param follow // * follow // */ // public void tail(Data data, boolean follow) { // // TailerListener2 listener = createListener(data); // // if (follow) // // tail from the start of the file and watch for future changes // tailer = new Tailer2(file, listener, checkIntervalMs, false, BUFFER_SIZE); // // else // tailer = new TailerNonFollowing(file, listener, BUFFER_SIZE); // // // start in separate thread // log.info("starting tailer thread"); // executor.execute(tailer); // } // // public static class SampleResult { // // private final LinkedHashMap<LogEntry, List<String>> entries; // private final List<String> unparsedLines; // // public SampleResult(LinkedHashMap<LogEntry, List<String>> entries, List<String> unparsedLines) { // this.entries = entries; // this.unparsedLines = unparsedLines; // } // // public List<String> getUnparsedLines() { // return unparsedLines; // } // // public LinkedHashMap<LogEntry, List<String>> getEntries() { // return entries; // } // // } // // public SampleResult sample(int numLines) { // // try { // FileInputStream fis = new FileInputStream(file); // BufferedReader br = new BufferedReader(new InputStreamReader(fis)); // // String line; // List<String> lines = Lists.newArrayList(); // LinkedHashMap<LogEntry, List<String>> entries = new LinkedHashMap<LogEntry, List<String>>(); // int lineCount = 0; // while (lineCount < numLines && (line = br.readLine()) != null) { // LogEntry entry = parser.parse(source, line); // lines.add(line); // if (entry != null) { // entries.put(entry, lines); // lines = Lists.newArrayList(); // } // lineCount++; // } // br.close(); // return new SampleResult(entries, lines); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Stops the tailer (and thus its thread). // */ // public void stop() { // if (tailer != null) // if (tailer instanceof Tailer) // ((Tailer) tailer).stop(); // else if (tailer instanceof TailerNonFollowing) // ((TailerNonFollowing) tailer).stop(); // } // // private TailerListener2 createListener(final Data data) { // return new TailerListener2() { // private final Data db = data; // // @Override // public void fileNotFound() { // log.warning("file not found"); // } // // @Override // public void fileRotated() { // log.info("file rotated"); // } // // @Override // public synchronized void handle(String line) { // try { // LogEntry entry = parser.parse(source, line); // if (entry != null) { // db.add(entry); // log.fine("added"); // } // } catch (Throwable e) { // log.log(Level.WARNING, e.getMessage(), e); // } // } // // @Override // public void handle(Exception e) { // log.log(Level.WARNING, "handle exception " + e.getMessage(), e); // } // // @Override // public void init(Tailer2 tailer) { // log.info("init"); // } // }; // } // // public File getFile() { // return file; // } // } // Path: src/main/java/com/github/davidmoten/logan/watcher/FileTailerStandard.java import com.github.davidmoten.logan.Data; import com.github.davidmoten.logan.LogFile; package com.github.davidmoten.logan.watcher; public class FileTailerStandard implements FileTailer { public enum Singleton { INSTANCE; private final FileTailerStandard instance = new FileTailerStandard(); public FileTailerStandard instance() { return instance; } } @Override
public void tail(LogFile logFile, Data data, boolean follow) {
davidmoten/logan
src/main/java/com/github/davidmoten/logan/watcher/FileTailerStandard.java
// Path: src/main/java/com/github/davidmoten/logan/Data.java // public interface Data { // // Buckets execute(BucketQuery query); // // Stream<String> getLogs(long startTime, long finishTime); // // Stream<LogEntry> find(long startTime, long finishTime); // // /** // * Adds a {@link LogEntry} to the data. // * // * @param entry entry // * @return this this // */ // Data add(LogEntry entry); // // long getNumEntries(); // // /** // * Returns total number of entries added so far (older entries may have been // * discarded so this is not the same as the current number of entries). // * // * @return total number of entries added so far // */ // long getNumEntriesAdded(); // // NavigableSet<String> getKeys(); // // NavigableSet<String> getSources(); // // void close() throws Exception; // // } // // Path: src/main/java/com/github/davidmoten/logan/LogFile.java // public class LogFile { // // private static Logger log = Logger.getLogger(LogFile.class.getName()); // // private final File file; // private final long checkIntervalMs; // private Runnable tailer; // private final LogParser parser; // private final ExecutorService executor; // private final String source; // // public LogFile(File file, String source, long checkIntervalMs, LogParser parser, ExecutorService executor) { // this.file = file; // this.source = source; // this.checkIntervalMs = checkIntervalMs; // this.parser = parser; // this.executor = executor; // createFileIfDoesntExist(file); // } // // @VisibleForTesting // static void createFileIfDoesntExist(File file) { // if (!file.exists()) // try { // if (!file.createNewFile()) // throw new RuntimeException("could not create file: " + file); // } catch (IOException e) { // throw new RuntimeException("could not create file: " + file, e); // } // } // // private static int BUFFER_SIZE = 2 * 4096; // // /** // * Starts a thread that tails a file from the start and reports extracted info // * from the lines to the database. // * // * @param data // * data // * @param follow // * follow // */ // public void tail(Data data, boolean follow) { // // TailerListener2 listener = createListener(data); // // if (follow) // // tail from the start of the file and watch for future changes // tailer = new Tailer2(file, listener, checkIntervalMs, false, BUFFER_SIZE); // // else // tailer = new TailerNonFollowing(file, listener, BUFFER_SIZE); // // // start in separate thread // log.info("starting tailer thread"); // executor.execute(tailer); // } // // public static class SampleResult { // // private final LinkedHashMap<LogEntry, List<String>> entries; // private final List<String> unparsedLines; // // public SampleResult(LinkedHashMap<LogEntry, List<String>> entries, List<String> unparsedLines) { // this.entries = entries; // this.unparsedLines = unparsedLines; // } // // public List<String> getUnparsedLines() { // return unparsedLines; // } // // public LinkedHashMap<LogEntry, List<String>> getEntries() { // return entries; // } // // } // // public SampleResult sample(int numLines) { // // try { // FileInputStream fis = new FileInputStream(file); // BufferedReader br = new BufferedReader(new InputStreamReader(fis)); // // String line; // List<String> lines = Lists.newArrayList(); // LinkedHashMap<LogEntry, List<String>> entries = new LinkedHashMap<LogEntry, List<String>>(); // int lineCount = 0; // while (lineCount < numLines && (line = br.readLine()) != null) { // LogEntry entry = parser.parse(source, line); // lines.add(line); // if (entry != null) { // entries.put(entry, lines); // lines = Lists.newArrayList(); // } // lineCount++; // } // br.close(); // return new SampleResult(entries, lines); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Stops the tailer (and thus its thread). // */ // public void stop() { // if (tailer != null) // if (tailer instanceof Tailer) // ((Tailer) tailer).stop(); // else if (tailer instanceof TailerNonFollowing) // ((TailerNonFollowing) tailer).stop(); // } // // private TailerListener2 createListener(final Data data) { // return new TailerListener2() { // private final Data db = data; // // @Override // public void fileNotFound() { // log.warning("file not found"); // } // // @Override // public void fileRotated() { // log.info("file rotated"); // } // // @Override // public synchronized void handle(String line) { // try { // LogEntry entry = parser.parse(source, line); // if (entry != null) { // db.add(entry); // log.fine("added"); // } // } catch (Throwable e) { // log.log(Level.WARNING, e.getMessage(), e); // } // } // // @Override // public void handle(Exception e) { // log.log(Level.WARNING, "handle exception " + e.getMessage(), e); // } // // @Override // public void init(Tailer2 tailer) { // log.info("init"); // } // }; // } // // public File getFile() { // return file; // } // }
import com.github.davidmoten.logan.Data; import com.github.davidmoten.logan.LogFile;
package com.github.davidmoten.logan.watcher; public class FileTailerStandard implements FileTailer { public enum Singleton { INSTANCE; private final FileTailerStandard instance = new FileTailerStandard(); public FileTailerStandard instance() { return instance; } } @Override
// Path: src/main/java/com/github/davidmoten/logan/Data.java // public interface Data { // // Buckets execute(BucketQuery query); // // Stream<String> getLogs(long startTime, long finishTime); // // Stream<LogEntry> find(long startTime, long finishTime); // // /** // * Adds a {@link LogEntry} to the data. // * // * @param entry entry // * @return this this // */ // Data add(LogEntry entry); // // long getNumEntries(); // // /** // * Returns total number of entries added so far (older entries may have been // * discarded so this is not the same as the current number of entries). // * // * @return total number of entries added so far // */ // long getNumEntriesAdded(); // // NavigableSet<String> getKeys(); // // NavigableSet<String> getSources(); // // void close() throws Exception; // // } // // Path: src/main/java/com/github/davidmoten/logan/LogFile.java // public class LogFile { // // private static Logger log = Logger.getLogger(LogFile.class.getName()); // // private final File file; // private final long checkIntervalMs; // private Runnable tailer; // private final LogParser parser; // private final ExecutorService executor; // private final String source; // // public LogFile(File file, String source, long checkIntervalMs, LogParser parser, ExecutorService executor) { // this.file = file; // this.source = source; // this.checkIntervalMs = checkIntervalMs; // this.parser = parser; // this.executor = executor; // createFileIfDoesntExist(file); // } // // @VisibleForTesting // static void createFileIfDoesntExist(File file) { // if (!file.exists()) // try { // if (!file.createNewFile()) // throw new RuntimeException("could not create file: " + file); // } catch (IOException e) { // throw new RuntimeException("could not create file: " + file, e); // } // } // // private static int BUFFER_SIZE = 2 * 4096; // // /** // * Starts a thread that tails a file from the start and reports extracted info // * from the lines to the database. // * // * @param data // * data // * @param follow // * follow // */ // public void tail(Data data, boolean follow) { // // TailerListener2 listener = createListener(data); // // if (follow) // // tail from the start of the file and watch for future changes // tailer = new Tailer2(file, listener, checkIntervalMs, false, BUFFER_SIZE); // // else // tailer = new TailerNonFollowing(file, listener, BUFFER_SIZE); // // // start in separate thread // log.info("starting tailer thread"); // executor.execute(tailer); // } // // public static class SampleResult { // // private final LinkedHashMap<LogEntry, List<String>> entries; // private final List<String> unparsedLines; // // public SampleResult(LinkedHashMap<LogEntry, List<String>> entries, List<String> unparsedLines) { // this.entries = entries; // this.unparsedLines = unparsedLines; // } // // public List<String> getUnparsedLines() { // return unparsedLines; // } // // public LinkedHashMap<LogEntry, List<String>> getEntries() { // return entries; // } // // } // // public SampleResult sample(int numLines) { // // try { // FileInputStream fis = new FileInputStream(file); // BufferedReader br = new BufferedReader(new InputStreamReader(fis)); // // String line; // List<String> lines = Lists.newArrayList(); // LinkedHashMap<LogEntry, List<String>> entries = new LinkedHashMap<LogEntry, List<String>>(); // int lineCount = 0; // while (lineCount < numLines && (line = br.readLine()) != null) { // LogEntry entry = parser.parse(source, line); // lines.add(line); // if (entry != null) { // entries.put(entry, lines); // lines = Lists.newArrayList(); // } // lineCount++; // } // br.close(); // return new SampleResult(entries, lines); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // /** // * Stops the tailer (and thus its thread). // */ // public void stop() { // if (tailer != null) // if (tailer instanceof Tailer) // ((Tailer) tailer).stop(); // else if (tailer instanceof TailerNonFollowing) // ((TailerNonFollowing) tailer).stop(); // } // // private TailerListener2 createListener(final Data data) { // return new TailerListener2() { // private final Data db = data; // // @Override // public void fileNotFound() { // log.warning("file not found"); // } // // @Override // public void fileRotated() { // log.info("file rotated"); // } // // @Override // public synchronized void handle(String line) { // try { // LogEntry entry = parser.parse(source, line); // if (entry != null) { // db.add(entry); // log.fine("added"); // } // } catch (Throwable e) { // log.log(Level.WARNING, e.getMessage(), e); // } // } // // @Override // public void handle(Exception e) { // log.log(Level.WARNING, "handle exception " + e.getMessage(), e); // } // // @Override // public void init(Tailer2 tailer) { // log.info("init"); // } // }; // } // // public File getFile() { // return file; // } // } // Path: src/main/java/com/github/davidmoten/logan/watcher/FileTailerStandard.java import com.github.davidmoten.logan.Data; import com.github.davidmoten.logan.LogFile; package com.github.davidmoten.logan.watcher; public class FileTailerStandard implements FileTailer { public enum Singleton { INSTANCE; private final FileTailerStandard instance = new FileTailerStandard(); public FileTailerStandard instance() { return instance; } } @Override
public void tail(LogFile logFile, Data data, boolean follow) {
davidmoten/logan
src/test/java/com/github/davidmoten/logan/watcher/ConfigurationLoadTest.java
// Path: src/main/java/com/github/davidmoten/logan/config/Configuration.java // public class Configuration { // // private static final String DEFAULT_CONFIGURATION_LOCATION = "/logan-configuration.xml"; // // private static Logger log = Logger.getLogger(Configuration.class.getName()); // // /** // * Maximum number of log entries to keep in memory. Oldest are discarded // * first once size reaches maxSize. // */ // @XmlElement(required = false, defaultValue = "1000000") // public int maxSize; // // @XmlElement(required = false) // public String scanDelimiterPattern; // // @XmlElement(required = false) // public PersistenceType persistenceType; // /** // * Default parser for log lines for all log files where the parser is not // * specified. // */ // @XmlElement(required = false) // public Parser parser; // /** // * Groups of Parser and Log items. // */ // @XmlElement(required = true) // public List<Group> group = Lists.newArrayList(); // // /** // * Constructor. // * // * @param parser // * parser // * @param group // * group // */ // public Configuration(Parser parser, List<Group> group) { // super(); // this.parser = parser; // this.group = group; // } // // /** // * Constructor. // */ // public Configuration() { // // no-args constructor required by jaxb // } // // /** // * <p> // * Returns {@link Configuration} based on the value of the system property // * <code>logan.config</code>. // * </p> // * // * <p> // * If <code>logan.config</code> property not set then assumed to be // * <code>/logan-configuration.xml</code>. // * </p> // * // * <p> // * Configuration is loaded from the file pointed to by // * <code>logan.config</code>. The classpath is checked first then the // * filesystem. If the file is not found in neither path then a // * {@link RuntimeException} is thrown. // * </p> // * // * <p> // * Any properties specified in the configuration.xml file in the format // * <code>${property.name}</code> will be replaced with system properties if // * set. // * </p> // * // * @return loaded configuration // */ // // public static synchronized Configuration getConfiguration() { // String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); // log.info("config=" + configLocation); // InputStream is = Main.class.getResourceAsStream(configLocation); // if (is == null) { // File file = new File(configLocation); // if (file.exists()) // try { // is = new FileInputStream(configLocation); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // else // throw new RuntimeException( // "configuration xml not found. Set property logan.config to a file on classpath or filesystem."); // } // InputStream is2 = PropertyReplacer.replaceSystemProperties(is); // Configuration configuration = new Marshaller().unmarshal(is2); // return configuration; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Configuration ["); // builder.append("parser="); // builder.append(parser); // builder.append("maxSize="); // builder.append(maxSize); // builder.append(", group="); // builder.append(group); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Marshaller.java // public class Marshaller { // // public static final String NAMESPACE = "http://github.com/davidmoten/logan/configuration"; // // private final javax.xml.bind.Marshaller marshaller; // // private final Unmarshaller unmarshaller; // // /** // * Constructor. // */ // public Marshaller() { // try { // JAXBContext jc = JAXBContext.newInstance(Configuration.class); // marshaller = jc.createMarshaller(); // marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); // unmarshaller = jc.createUnmarshaller(); // } catch (PropertyException e) { // throw new RuntimeException(e); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // /** // * Marshals {@link Configuration} to xml. // * // * @param configuration // * configuration // * @param os // * output stream // */ // public synchronized void marshal(Configuration configuration, OutputStream os) { // try { // JAXBElement<Configuration> element = new JAXBElement<Configuration>( // new QName(NAMESPACE, "configuration"), Configuration.class, configuration); // marshaller.marshal(element, os); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // public synchronized String marshal(Configuration configuration) { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // marshal(configuration, bytes); // return bytes.toString(StandardCharsets.UTF_8); // } // // /** // * Unmarshals xml to {@link Configuration}. // * // * @param is // * input stream // * @return configuration // */ // public synchronized Configuration unmarshal(InputStream is) { // StreamSource xml = new StreamSource(is); // JAXBElement<Configuration> element; // try { // element = unmarshaller.unmarshal(xml, Configuration.class); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // return element.getValue(); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.github.davidmoten.logan.config.Configuration; import com.github.davidmoten.logan.config.Marshaller;
package com.github.davidmoten.logan.watcher; public class ConfigurationLoadTest { @Test public void testLoadOfSampleConfiguration() {
// Path: src/main/java/com/github/davidmoten/logan/config/Configuration.java // public class Configuration { // // private static final String DEFAULT_CONFIGURATION_LOCATION = "/logan-configuration.xml"; // // private static Logger log = Logger.getLogger(Configuration.class.getName()); // // /** // * Maximum number of log entries to keep in memory. Oldest are discarded // * first once size reaches maxSize. // */ // @XmlElement(required = false, defaultValue = "1000000") // public int maxSize; // // @XmlElement(required = false) // public String scanDelimiterPattern; // // @XmlElement(required = false) // public PersistenceType persistenceType; // /** // * Default parser for log lines for all log files where the parser is not // * specified. // */ // @XmlElement(required = false) // public Parser parser; // /** // * Groups of Parser and Log items. // */ // @XmlElement(required = true) // public List<Group> group = Lists.newArrayList(); // // /** // * Constructor. // * // * @param parser // * parser // * @param group // * group // */ // public Configuration(Parser parser, List<Group> group) { // super(); // this.parser = parser; // this.group = group; // } // // /** // * Constructor. // */ // public Configuration() { // // no-args constructor required by jaxb // } // // /** // * <p> // * Returns {@link Configuration} based on the value of the system property // * <code>logan.config</code>. // * </p> // * // * <p> // * If <code>logan.config</code> property not set then assumed to be // * <code>/logan-configuration.xml</code>. // * </p> // * // * <p> // * Configuration is loaded from the file pointed to by // * <code>logan.config</code>. The classpath is checked first then the // * filesystem. If the file is not found in neither path then a // * {@link RuntimeException} is thrown. // * </p> // * // * <p> // * Any properties specified in the configuration.xml file in the format // * <code>${property.name}</code> will be replaced with system properties if // * set. // * </p> // * // * @return loaded configuration // */ // // public static synchronized Configuration getConfiguration() { // String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); // log.info("config=" + configLocation); // InputStream is = Main.class.getResourceAsStream(configLocation); // if (is == null) { // File file = new File(configLocation); // if (file.exists()) // try { // is = new FileInputStream(configLocation); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // else // throw new RuntimeException( // "configuration xml not found. Set property logan.config to a file on classpath or filesystem."); // } // InputStream is2 = PropertyReplacer.replaceSystemProperties(is); // Configuration configuration = new Marshaller().unmarshal(is2); // return configuration; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Configuration ["); // builder.append("parser="); // builder.append(parser); // builder.append("maxSize="); // builder.append(maxSize); // builder.append(", group="); // builder.append(group); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Marshaller.java // public class Marshaller { // // public static final String NAMESPACE = "http://github.com/davidmoten/logan/configuration"; // // private final javax.xml.bind.Marshaller marshaller; // // private final Unmarshaller unmarshaller; // // /** // * Constructor. // */ // public Marshaller() { // try { // JAXBContext jc = JAXBContext.newInstance(Configuration.class); // marshaller = jc.createMarshaller(); // marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); // unmarshaller = jc.createUnmarshaller(); // } catch (PropertyException e) { // throw new RuntimeException(e); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // /** // * Marshals {@link Configuration} to xml. // * // * @param configuration // * configuration // * @param os // * output stream // */ // public synchronized void marshal(Configuration configuration, OutputStream os) { // try { // JAXBElement<Configuration> element = new JAXBElement<Configuration>( // new QName(NAMESPACE, "configuration"), Configuration.class, configuration); // marshaller.marshal(element, os); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // public synchronized String marshal(Configuration configuration) { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // marshal(configuration, bytes); // return bytes.toString(StandardCharsets.UTF_8); // } // // /** // * Unmarshals xml to {@link Configuration}. // * // * @param is // * input stream // * @return configuration // */ // public synchronized Configuration unmarshal(InputStream is) { // StreamSource xml = new StreamSource(is); // JAXBElement<Configuration> element; // try { // element = unmarshaller.unmarshal(xml, Configuration.class); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // return element.getValue(); // } // // } // Path: src/test/java/com/github/davidmoten/logan/watcher/ConfigurationLoadTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.github.davidmoten.logan.config.Configuration; import com.github.davidmoten.logan.config.Marshaller; package com.github.davidmoten.logan.watcher; public class ConfigurationLoadTest { @Test public void testLoadOfSampleConfiguration() {
Configuration configuration = new Marshaller()
davidmoten/logan
src/test/java/com/github/davidmoten/logan/watcher/ConfigurationLoadTest.java
// Path: src/main/java/com/github/davidmoten/logan/config/Configuration.java // public class Configuration { // // private static final String DEFAULT_CONFIGURATION_LOCATION = "/logan-configuration.xml"; // // private static Logger log = Logger.getLogger(Configuration.class.getName()); // // /** // * Maximum number of log entries to keep in memory. Oldest are discarded // * first once size reaches maxSize. // */ // @XmlElement(required = false, defaultValue = "1000000") // public int maxSize; // // @XmlElement(required = false) // public String scanDelimiterPattern; // // @XmlElement(required = false) // public PersistenceType persistenceType; // /** // * Default parser for log lines for all log files where the parser is not // * specified. // */ // @XmlElement(required = false) // public Parser parser; // /** // * Groups of Parser and Log items. // */ // @XmlElement(required = true) // public List<Group> group = Lists.newArrayList(); // // /** // * Constructor. // * // * @param parser // * parser // * @param group // * group // */ // public Configuration(Parser parser, List<Group> group) { // super(); // this.parser = parser; // this.group = group; // } // // /** // * Constructor. // */ // public Configuration() { // // no-args constructor required by jaxb // } // // /** // * <p> // * Returns {@link Configuration} based on the value of the system property // * <code>logan.config</code>. // * </p> // * // * <p> // * If <code>logan.config</code> property not set then assumed to be // * <code>/logan-configuration.xml</code>. // * </p> // * // * <p> // * Configuration is loaded from the file pointed to by // * <code>logan.config</code>. The classpath is checked first then the // * filesystem. If the file is not found in neither path then a // * {@link RuntimeException} is thrown. // * </p> // * // * <p> // * Any properties specified in the configuration.xml file in the format // * <code>${property.name}</code> will be replaced with system properties if // * set. // * </p> // * // * @return loaded configuration // */ // // public static synchronized Configuration getConfiguration() { // String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); // log.info("config=" + configLocation); // InputStream is = Main.class.getResourceAsStream(configLocation); // if (is == null) { // File file = new File(configLocation); // if (file.exists()) // try { // is = new FileInputStream(configLocation); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // else // throw new RuntimeException( // "configuration xml not found. Set property logan.config to a file on classpath or filesystem."); // } // InputStream is2 = PropertyReplacer.replaceSystemProperties(is); // Configuration configuration = new Marshaller().unmarshal(is2); // return configuration; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Configuration ["); // builder.append("parser="); // builder.append(parser); // builder.append("maxSize="); // builder.append(maxSize); // builder.append(", group="); // builder.append(group); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Marshaller.java // public class Marshaller { // // public static final String NAMESPACE = "http://github.com/davidmoten/logan/configuration"; // // private final javax.xml.bind.Marshaller marshaller; // // private final Unmarshaller unmarshaller; // // /** // * Constructor. // */ // public Marshaller() { // try { // JAXBContext jc = JAXBContext.newInstance(Configuration.class); // marshaller = jc.createMarshaller(); // marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); // unmarshaller = jc.createUnmarshaller(); // } catch (PropertyException e) { // throw new RuntimeException(e); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // /** // * Marshals {@link Configuration} to xml. // * // * @param configuration // * configuration // * @param os // * output stream // */ // public synchronized void marshal(Configuration configuration, OutputStream os) { // try { // JAXBElement<Configuration> element = new JAXBElement<Configuration>( // new QName(NAMESPACE, "configuration"), Configuration.class, configuration); // marshaller.marshal(element, os); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // public synchronized String marshal(Configuration configuration) { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // marshal(configuration, bytes); // return bytes.toString(StandardCharsets.UTF_8); // } // // /** // * Unmarshals xml to {@link Configuration}. // * // * @param is // * input stream // * @return configuration // */ // public synchronized Configuration unmarshal(InputStream is) { // StreamSource xml = new StreamSource(is); // JAXBElement<Configuration> element; // try { // element = unmarshaller.unmarshal(xml, Configuration.class); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // return element.getValue(); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.github.davidmoten.logan.config.Configuration; import com.github.davidmoten.logan.config.Marshaller;
package com.github.davidmoten.logan.watcher; public class ConfigurationLoadTest { @Test public void testLoadOfSampleConfiguration() {
// Path: src/main/java/com/github/davidmoten/logan/config/Configuration.java // public class Configuration { // // private static final String DEFAULT_CONFIGURATION_LOCATION = "/logan-configuration.xml"; // // private static Logger log = Logger.getLogger(Configuration.class.getName()); // // /** // * Maximum number of log entries to keep in memory. Oldest are discarded // * first once size reaches maxSize. // */ // @XmlElement(required = false, defaultValue = "1000000") // public int maxSize; // // @XmlElement(required = false) // public String scanDelimiterPattern; // // @XmlElement(required = false) // public PersistenceType persistenceType; // /** // * Default parser for log lines for all log files where the parser is not // * specified. // */ // @XmlElement(required = false) // public Parser parser; // /** // * Groups of Parser and Log items. // */ // @XmlElement(required = true) // public List<Group> group = Lists.newArrayList(); // // /** // * Constructor. // * // * @param parser // * parser // * @param group // * group // */ // public Configuration(Parser parser, List<Group> group) { // super(); // this.parser = parser; // this.group = group; // } // // /** // * Constructor. // */ // public Configuration() { // // no-args constructor required by jaxb // } // // /** // * <p> // * Returns {@link Configuration} based on the value of the system property // * <code>logan.config</code>. // * </p> // * // * <p> // * If <code>logan.config</code> property not set then assumed to be // * <code>/logan-configuration.xml</code>. // * </p> // * // * <p> // * Configuration is loaded from the file pointed to by // * <code>logan.config</code>. The classpath is checked first then the // * filesystem. If the file is not found in neither path then a // * {@link RuntimeException} is thrown. // * </p> // * // * <p> // * Any properties specified in the configuration.xml file in the format // * <code>${property.name}</code> will be replaced with system properties if // * set. // * </p> // * // * @return loaded configuration // */ // // public static synchronized Configuration getConfiguration() { // String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); // log.info("config=" + configLocation); // InputStream is = Main.class.getResourceAsStream(configLocation); // if (is == null) { // File file = new File(configLocation); // if (file.exists()) // try { // is = new FileInputStream(configLocation); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // else // throw new RuntimeException( // "configuration xml not found. Set property logan.config to a file on classpath or filesystem."); // } // InputStream is2 = PropertyReplacer.replaceSystemProperties(is); // Configuration configuration = new Marshaller().unmarshal(is2); // return configuration; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Configuration ["); // builder.append("parser="); // builder.append(parser); // builder.append("maxSize="); // builder.append(maxSize); // builder.append(", group="); // builder.append(group); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Marshaller.java // public class Marshaller { // // public static final String NAMESPACE = "http://github.com/davidmoten/logan/configuration"; // // private final javax.xml.bind.Marshaller marshaller; // // private final Unmarshaller unmarshaller; // // /** // * Constructor. // */ // public Marshaller() { // try { // JAXBContext jc = JAXBContext.newInstance(Configuration.class); // marshaller = jc.createMarshaller(); // marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); // unmarshaller = jc.createUnmarshaller(); // } catch (PropertyException e) { // throw new RuntimeException(e); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // /** // * Marshals {@link Configuration} to xml. // * // * @param configuration // * configuration // * @param os // * output stream // */ // public synchronized void marshal(Configuration configuration, OutputStream os) { // try { // JAXBElement<Configuration> element = new JAXBElement<Configuration>( // new QName(NAMESPACE, "configuration"), Configuration.class, configuration); // marshaller.marshal(element, os); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // } // // public synchronized String marshal(Configuration configuration) { // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // marshal(configuration, bytes); // return bytes.toString(StandardCharsets.UTF_8); // } // // /** // * Unmarshals xml to {@link Configuration}. // * // * @param is // * input stream // * @return configuration // */ // public synchronized Configuration unmarshal(InputStream is) { // StreamSource xml = new StreamSource(is); // JAXBElement<Configuration> element; // try { // element = unmarshaller.unmarshal(xml, Configuration.class); // } catch (JAXBException e) { // throw new RuntimeException(e); // } // return element.getValue(); // } // // } // Path: src/test/java/com/github/davidmoten/logan/watcher/ConfigurationLoadTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.github.davidmoten.logan.config.Configuration; import com.github.davidmoten.logan.config.Marshaller; package com.github.davidmoten.logan.watcher; public class ConfigurationLoadTest { @Test public void testLoadOfSampleConfiguration() {
Configuration configuration = new Marshaller()
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParserOptions.java
// Path: src/main/java/com/github/davidmoten/logan/config/Group.java // public class Group { // // @XmlAttribute(required = false) // public boolean enabled = true; // // @XmlElement(required = false) // public Parser parser; // // @XmlElement(required = false) // public List<Log> log = Lists.newArrayList(); // // /** // * Constructor. // * // * @param log // * log // * @param parser // * parser // */ // public Group(List<Log> log, Parser parser) { // super(); // this.log = log; // this.parser = parser; // } // // /** // * Constructor. // * // * @param log // * log // */ // public Group(List<Log> log) { // this(log, null); // } // // /** // * Constructor. // */ // public Group() { // // no-args constructor required by jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Group [log="); // builder.append(log); // builder.append(", parser="); // builder.append(parser); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Parser.java // public class Parser { // // @XmlElement(required = false) // public String sourcePattern; // @XmlElement(required = true) // public String pattern; // @XmlElement(required = true) // public String patternGroups; // @XmlElement(defaultValue = MessageSplitter.MESSAGE_PATTERN_DEFAULT) // public String messagePattern = MessageSplitter.MESSAGE_PATTERN_DEFAULT; // @XmlElement(required = true) // public List<String> timestampFormat; // @XmlElement(defaultValue = "UTC") // public String timezone = "UTC"; // @XmlElement(required = false, defaultValue = "false") // public boolean multiline; // // public Parser(String pattern, String patternGroups, String messagePattern, // List<String> timestampFormat, String timezone, boolean multiline, // String sourcePattern) { // super(); // this.pattern = pattern; // this.patternGroups = patternGroups; // this.messagePattern = messagePattern; // this.timestampFormat = timestampFormat; // this.timezone = timezone; // this.multiline = multiline; // this.sourcePattern = sourcePattern; // } // // /** // * Constructor. // */ // public Parser() { // // required for jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Parser [pattern="); // builder.append(pattern); // builder.append(", patternGroups="); // builder.append(patternGroups); // builder.append(", messagePattern="); // builder.append(messagePattern); // builder.append(", timestampFormat="); // builder.append(timestampFormat); // builder.append(", timezone="); // builder.append(timezone); // builder.append(", multiline="); // builder.append(multiline); // builder.append("]"); // return builder.toString(); // } // // }
import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import com.github.davidmoten.logan.config.Group; import com.github.davidmoten.logan.config.Parser; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Lists;
} /** * Returns true if and only if the logs are split over lines like for * instance default java.util.logging logs. * * @return multiline */ public boolean isMultiline() { return multiline; } /** * Returns the message regex {@link Pattern} used to extract keys and values * from the log line message. * * @return message pattern */ public Pattern getMessagePattern() { return messagePattern; } private static BiMap<String, Integer> createGroupMap(String list) { BiMap<String, Integer> map = HashBiMap.create(5); String[] items = list.split(","); for (int i = 0; i < items.length; i++) map.put(items[i], i + 1); return map; }
// Path: src/main/java/com/github/davidmoten/logan/config/Group.java // public class Group { // // @XmlAttribute(required = false) // public boolean enabled = true; // // @XmlElement(required = false) // public Parser parser; // // @XmlElement(required = false) // public List<Log> log = Lists.newArrayList(); // // /** // * Constructor. // * // * @param log // * log // * @param parser // * parser // */ // public Group(List<Log> log, Parser parser) { // super(); // this.log = log; // this.parser = parser; // } // // /** // * Constructor. // * // * @param log // * log // */ // public Group(List<Log> log) { // this(log, null); // } // // /** // * Constructor. // */ // public Group() { // // no-args constructor required by jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Group [log="); // builder.append(log); // builder.append(", parser="); // builder.append(parser); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Parser.java // public class Parser { // // @XmlElement(required = false) // public String sourcePattern; // @XmlElement(required = true) // public String pattern; // @XmlElement(required = true) // public String patternGroups; // @XmlElement(defaultValue = MessageSplitter.MESSAGE_PATTERN_DEFAULT) // public String messagePattern = MessageSplitter.MESSAGE_PATTERN_DEFAULT; // @XmlElement(required = true) // public List<String> timestampFormat; // @XmlElement(defaultValue = "UTC") // public String timezone = "UTC"; // @XmlElement(required = false, defaultValue = "false") // public boolean multiline; // // public Parser(String pattern, String patternGroups, String messagePattern, // List<String> timestampFormat, String timezone, boolean multiline, // String sourcePattern) { // super(); // this.pattern = pattern; // this.patternGroups = patternGroups; // this.messagePattern = messagePattern; // this.timestampFormat = timestampFormat; // this.timezone = timezone; // this.multiline = multiline; // this.sourcePattern = sourcePattern; // } // // /** // * Constructor. // */ // public Parser() { // // required for jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Parser [pattern="); // builder.append(pattern); // builder.append(", patternGroups="); // builder.append(patternGroups); // builder.append(", messagePattern="); // builder.append(messagePattern); // builder.append(", timestampFormat="); // builder.append(timestampFormat); // builder.append(", timezone="); // builder.append(timezone); // builder.append(", multiline="); // builder.append(multiline); // builder.append("]"); // return builder.toString(); // } // // } // Path: src/main/java/com/github/davidmoten/logan/LogParserOptions.java import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import com.github.davidmoten.logan.config.Group; import com.github.davidmoten.logan.config.Parser; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Lists; } /** * Returns true if and only if the logs are split over lines like for * instance default java.util.logging logs. * * @return multiline */ public boolean isMultiline() { return multiline; } /** * Returns the message regex {@link Pattern} used to extract keys and values * from the log line message. * * @return message pattern */ public Pattern getMessagePattern() { return messagePattern; } private static BiMap<String, Integer> createGroupMap(String list) { BiMap<String, Integer> map = HashBiMap.create(5); String[] items = list.split(","); for (int i = 0; i < items.length; i++) map.put(items[i], i + 1); return map; }
public static LogParserOptions load(Parser defaultParser, Group group) {
davidmoten/logan
src/main/java/com/github/davidmoten/logan/LogParserOptions.java
// Path: src/main/java/com/github/davidmoten/logan/config/Group.java // public class Group { // // @XmlAttribute(required = false) // public boolean enabled = true; // // @XmlElement(required = false) // public Parser parser; // // @XmlElement(required = false) // public List<Log> log = Lists.newArrayList(); // // /** // * Constructor. // * // * @param log // * log // * @param parser // * parser // */ // public Group(List<Log> log, Parser parser) { // super(); // this.log = log; // this.parser = parser; // } // // /** // * Constructor. // * // * @param log // * log // */ // public Group(List<Log> log) { // this(log, null); // } // // /** // * Constructor. // */ // public Group() { // // no-args constructor required by jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Group [log="); // builder.append(log); // builder.append(", parser="); // builder.append(parser); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Parser.java // public class Parser { // // @XmlElement(required = false) // public String sourcePattern; // @XmlElement(required = true) // public String pattern; // @XmlElement(required = true) // public String patternGroups; // @XmlElement(defaultValue = MessageSplitter.MESSAGE_PATTERN_DEFAULT) // public String messagePattern = MessageSplitter.MESSAGE_PATTERN_DEFAULT; // @XmlElement(required = true) // public List<String> timestampFormat; // @XmlElement(defaultValue = "UTC") // public String timezone = "UTC"; // @XmlElement(required = false, defaultValue = "false") // public boolean multiline; // // public Parser(String pattern, String patternGroups, String messagePattern, // List<String> timestampFormat, String timezone, boolean multiline, // String sourcePattern) { // super(); // this.pattern = pattern; // this.patternGroups = patternGroups; // this.messagePattern = messagePattern; // this.timestampFormat = timestampFormat; // this.timezone = timezone; // this.multiline = multiline; // this.sourcePattern = sourcePattern; // } // // /** // * Constructor. // */ // public Parser() { // // required for jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Parser [pattern="); // builder.append(pattern); // builder.append(", patternGroups="); // builder.append(patternGroups); // builder.append(", messagePattern="); // builder.append(messagePattern); // builder.append(", timestampFormat="); // builder.append(timestampFormat); // builder.append(", timezone="); // builder.append(timezone); // builder.append(", multiline="); // builder.append(multiline); // builder.append("]"); // return builder.toString(); // } // // }
import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import com.github.davidmoten.logan.config.Group; import com.github.davidmoten.logan.config.Parser; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Lists;
} /** * Returns true if and only if the logs are split over lines like for * instance default java.util.logging logs. * * @return multiline */ public boolean isMultiline() { return multiline; } /** * Returns the message regex {@link Pattern} used to extract keys and values * from the log line message. * * @return message pattern */ public Pattern getMessagePattern() { return messagePattern; } private static BiMap<String, Integer> createGroupMap(String list) { BiMap<String, Integer> map = HashBiMap.create(5); String[] items = list.split(","); for (int i = 0; i < items.length; i++) map.put(items[i], i + 1); return map; }
// Path: src/main/java/com/github/davidmoten/logan/config/Group.java // public class Group { // // @XmlAttribute(required = false) // public boolean enabled = true; // // @XmlElement(required = false) // public Parser parser; // // @XmlElement(required = false) // public List<Log> log = Lists.newArrayList(); // // /** // * Constructor. // * // * @param log // * log // * @param parser // * parser // */ // public Group(List<Log> log, Parser parser) { // super(); // this.log = log; // this.parser = parser; // } // // /** // * Constructor. // * // * @param log // * log // */ // public Group(List<Log> log) { // this(log, null); // } // // /** // * Constructor. // */ // public Group() { // // no-args constructor required by jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Group [log="); // builder.append(log); // builder.append(", parser="); // builder.append(parser); // builder.append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/github/davidmoten/logan/config/Parser.java // public class Parser { // // @XmlElement(required = false) // public String sourcePattern; // @XmlElement(required = true) // public String pattern; // @XmlElement(required = true) // public String patternGroups; // @XmlElement(defaultValue = MessageSplitter.MESSAGE_PATTERN_DEFAULT) // public String messagePattern = MessageSplitter.MESSAGE_PATTERN_DEFAULT; // @XmlElement(required = true) // public List<String> timestampFormat; // @XmlElement(defaultValue = "UTC") // public String timezone = "UTC"; // @XmlElement(required = false, defaultValue = "false") // public boolean multiline; // // public Parser(String pattern, String patternGroups, String messagePattern, // List<String> timestampFormat, String timezone, boolean multiline, // String sourcePattern) { // super(); // this.pattern = pattern; // this.patternGroups = patternGroups; // this.messagePattern = messagePattern; // this.timestampFormat = timestampFormat; // this.timezone = timezone; // this.multiline = multiline; // this.sourcePattern = sourcePattern; // } // // /** // * Constructor. // */ // public Parser() { // // required for jaxb // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("Parser [pattern="); // builder.append(pattern); // builder.append(", patternGroups="); // builder.append(patternGroups); // builder.append(", messagePattern="); // builder.append(messagePattern); // builder.append(", timestampFormat="); // builder.append(timestampFormat); // builder.append(", timezone="); // builder.append(timezone); // builder.append(", multiline="); // builder.append(multiline); // builder.append("]"); // return builder.toString(); // } // // } // Path: src/main/java/com/github/davidmoten/logan/LogParserOptions.java import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import com.github.davidmoten.logan.config.Group; import com.github.davidmoten.logan.config.Parser; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Lists; } /** * Returns true if and only if the logs are split over lines like for * instance default java.util.logging logs. * * @return multiline */ public boolean isMultiline() { return multiline; } /** * Returns the message regex {@link Pattern} used to extract keys and values * from the log line message. * * @return message pattern */ public Pattern getMessagePattern() { return messagePattern; } private static BiMap<String, Integer> createGroupMap(String list) { BiMap<String, Integer> map = HashBiMap.create(5); String[] items = list.split(","); for (int i = 0; i < items.length; i++) map.put(items[i], i + 1); return map; }
public static LogParserOptions load(Parser defaultParser, Group group) {
davidmoten/logan
src/main/java/com/github/davidmoten/logan/config/Configuration.java
// Path: src/main/java/com/github/davidmoten/logan/util/PropertyReplacer.java // public class PropertyReplacer { // // private PropertyReplacer() { // // prevent instantiation // } // // public static InputStream replaceSystemProperties(InputStream is) { // try { // List<String> lines = IOUtils.readLines(is, StandardCharsets.UTF_8); // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // PrintWriter out = new PrintWriter(bytes); // Pattern p = Pattern.compile("\\$\\{[^\\$]*\\}"); // boolean firstLine = true; // for (String line : lines) { // if (!firstLine) // out.println(); // Matcher m = p.matcher(line); // while (m.find()) { // String name = m.group() // .substring(2, m.group().length() - 1); // String property = System.getProperty(name); // if (property != null) // line = line.replace(m.group(), property); // } // out.print(line); // firstLine = false; // } // out.close(); // return new ByteArrayInputStream(bytes.toByteArray()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/github/davidmoten/logan/watcher/Main.java // public class Main { // // private static Logger log = Logger.getLogger(Main.class.getName()); // // /** // * Main method to start the persister. // * // * @param args // * args // * @throws IOException // * exception // */ // public static void main(String[] args) throws IOException { // // Configuration configuration = Configuration.getConfiguration(); // setupLogging(); // // Watcher w = new Watcher(new DataMemory(), configuration); // log.info("starting watcher"); // w.start(); // log.info("started"); // } // // private static void setupLogging() throws IOException { // LogManager.getLogManager() // .readConfiguration(Main.class.getResourceAsStream("/my-logging.properties")); // } // // }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; import java.util.logging.Logger; import javax.xml.bind.annotation.XmlElement; import com.github.davidmoten.logan.util.PropertyReplacer; import com.github.davidmoten.logan.watcher.Main; import com.google.common.collect.Lists;
package com.github.davidmoten.logan.config; /** * Configuration for log watching. * */ public class Configuration { private static final String DEFAULT_CONFIGURATION_LOCATION = "/logan-configuration.xml"; private static Logger log = Logger.getLogger(Configuration.class.getName()); /** * Maximum number of log entries to keep in memory. Oldest are discarded * first once size reaches maxSize. */ @XmlElement(required = false, defaultValue = "1000000") public int maxSize; @XmlElement(required = false) public String scanDelimiterPattern; @XmlElement(required = false) public PersistenceType persistenceType; /** * Default parser for log lines for all log files where the parser is not * specified. */ @XmlElement(required = false) public Parser parser; /** * Groups of Parser and Log items. */ @XmlElement(required = true) public List<Group> group = Lists.newArrayList(); /** * Constructor. * * @param parser * parser * @param group * group */ public Configuration(Parser parser, List<Group> group) { super(); this.parser = parser; this.group = group; } /** * Constructor. */ public Configuration() { // no-args constructor required by jaxb } /** * <p> * Returns {@link Configuration} based on the value of the system property * <code>logan.config</code>. * </p> * * <p> * If <code>logan.config</code> property not set then assumed to be * <code>/logan-configuration.xml</code>. * </p> * * <p> * Configuration is loaded from the file pointed to by * <code>logan.config</code>. The classpath is checked first then the * filesystem. If the file is not found in neither path then a * {@link RuntimeException} is thrown. * </p> * * <p> * Any properties specified in the configuration.xml file in the format * <code>${property.name}</code> will be replaced with system properties if * set. * </p> * * @return loaded configuration */ public static synchronized Configuration getConfiguration() { String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); log.info("config=" + configLocation);
// Path: src/main/java/com/github/davidmoten/logan/util/PropertyReplacer.java // public class PropertyReplacer { // // private PropertyReplacer() { // // prevent instantiation // } // // public static InputStream replaceSystemProperties(InputStream is) { // try { // List<String> lines = IOUtils.readLines(is, StandardCharsets.UTF_8); // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // PrintWriter out = new PrintWriter(bytes); // Pattern p = Pattern.compile("\\$\\{[^\\$]*\\}"); // boolean firstLine = true; // for (String line : lines) { // if (!firstLine) // out.println(); // Matcher m = p.matcher(line); // while (m.find()) { // String name = m.group() // .substring(2, m.group().length() - 1); // String property = System.getProperty(name); // if (property != null) // line = line.replace(m.group(), property); // } // out.print(line); // firstLine = false; // } // out.close(); // return new ByteArrayInputStream(bytes.toByteArray()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/github/davidmoten/logan/watcher/Main.java // public class Main { // // private static Logger log = Logger.getLogger(Main.class.getName()); // // /** // * Main method to start the persister. // * // * @param args // * args // * @throws IOException // * exception // */ // public static void main(String[] args) throws IOException { // // Configuration configuration = Configuration.getConfiguration(); // setupLogging(); // // Watcher w = new Watcher(new DataMemory(), configuration); // log.info("starting watcher"); // w.start(); // log.info("started"); // } // // private static void setupLogging() throws IOException { // LogManager.getLogManager() // .readConfiguration(Main.class.getResourceAsStream("/my-logging.properties")); // } // // } // Path: src/main/java/com/github/davidmoten/logan/config/Configuration.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; import java.util.logging.Logger; import javax.xml.bind.annotation.XmlElement; import com.github.davidmoten.logan.util.PropertyReplacer; import com.github.davidmoten.logan.watcher.Main; import com.google.common.collect.Lists; package com.github.davidmoten.logan.config; /** * Configuration for log watching. * */ public class Configuration { private static final String DEFAULT_CONFIGURATION_LOCATION = "/logan-configuration.xml"; private static Logger log = Logger.getLogger(Configuration.class.getName()); /** * Maximum number of log entries to keep in memory. Oldest are discarded * first once size reaches maxSize. */ @XmlElement(required = false, defaultValue = "1000000") public int maxSize; @XmlElement(required = false) public String scanDelimiterPattern; @XmlElement(required = false) public PersistenceType persistenceType; /** * Default parser for log lines for all log files where the parser is not * specified. */ @XmlElement(required = false) public Parser parser; /** * Groups of Parser and Log items. */ @XmlElement(required = true) public List<Group> group = Lists.newArrayList(); /** * Constructor. * * @param parser * parser * @param group * group */ public Configuration(Parser parser, List<Group> group) { super(); this.parser = parser; this.group = group; } /** * Constructor. */ public Configuration() { // no-args constructor required by jaxb } /** * <p> * Returns {@link Configuration} based on the value of the system property * <code>logan.config</code>. * </p> * * <p> * If <code>logan.config</code> property not set then assumed to be * <code>/logan-configuration.xml</code>. * </p> * * <p> * Configuration is loaded from the file pointed to by * <code>logan.config</code>. The classpath is checked first then the * filesystem. If the file is not found in neither path then a * {@link RuntimeException} is thrown. * </p> * * <p> * Any properties specified in the configuration.xml file in the format * <code>${property.name}</code> will be replaced with system properties if * set. * </p> * * @return loaded configuration */ public static synchronized Configuration getConfiguration() { String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); log.info("config=" + configLocation);
InputStream is = Main.class.getResourceAsStream(configLocation);
davidmoten/logan
src/main/java/com/github/davidmoten/logan/config/Configuration.java
// Path: src/main/java/com/github/davidmoten/logan/util/PropertyReplacer.java // public class PropertyReplacer { // // private PropertyReplacer() { // // prevent instantiation // } // // public static InputStream replaceSystemProperties(InputStream is) { // try { // List<String> lines = IOUtils.readLines(is, StandardCharsets.UTF_8); // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // PrintWriter out = new PrintWriter(bytes); // Pattern p = Pattern.compile("\\$\\{[^\\$]*\\}"); // boolean firstLine = true; // for (String line : lines) { // if (!firstLine) // out.println(); // Matcher m = p.matcher(line); // while (m.find()) { // String name = m.group() // .substring(2, m.group().length() - 1); // String property = System.getProperty(name); // if (property != null) // line = line.replace(m.group(), property); // } // out.print(line); // firstLine = false; // } // out.close(); // return new ByteArrayInputStream(bytes.toByteArray()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/github/davidmoten/logan/watcher/Main.java // public class Main { // // private static Logger log = Logger.getLogger(Main.class.getName()); // // /** // * Main method to start the persister. // * // * @param args // * args // * @throws IOException // * exception // */ // public static void main(String[] args) throws IOException { // // Configuration configuration = Configuration.getConfiguration(); // setupLogging(); // // Watcher w = new Watcher(new DataMemory(), configuration); // log.info("starting watcher"); // w.start(); // log.info("started"); // } // // private static void setupLogging() throws IOException { // LogManager.getLogManager() // .readConfiguration(Main.class.getResourceAsStream("/my-logging.properties")); // } // // }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; import java.util.logging.Logger; import javax.xml.bind.annotation.XmlElement; import com.github.davidmoten.logan.util.PropertyReplacer; import com.github.davidmoten.logan.watcher.Main; import com.google.common.collect.Lists;
* <code>logan.config</code>. The classpath is checked first then the * filesystem. If the file is not found in neither path then a * {@link RuntimeException} is thrown. * </p> * * <p> * Any properties specified in the configuration.xml file in the format * <code>${property.name}</code> will be replaced with system properties if * set. * </p> * * @return loaded configuration */ public static synchronized Configuration getConfiguration() { String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); log.info("config=" + configLocation); InputStream is = Main.class.getResourceAsStream(configLocation); if (is == null) { File file = new File(configLocation); if (file.exists()) try { is = new FileInputStream(configLocation); } catch (FileNotFoundException e) { throw new RuntimeException(e); } else throw new RuntimeException( "configuration xml not found. Set property logan.config to a file on classpath or filesystem."); }
// Path: src/main/java/com/github/davidmoten/logan/util/PropertyReplacer.java // public class PropertyReplacer { // // private PropertyReplacer() { // // prevent instantiation // } // // public static InputStream replaceSystemProperties(InputStream is) { // try { // List<String> lines = IOUtils.readLines(is, StandardCharsets.UTF_8); // ByteArrayOutputStream bytes = new ByteArrayOutputStream(); // PrintWriter out = new PrintWriter(bytes); // Pattern p = Pattern.compile("\\$\\{[^\\$]*\\}"); // boolean firstLine = true; // for (String line : lines) { // if (!firstLine) // out.println(); // Matcher m = p.matcher(line); // while (m.find()) { // String name = m.group() // .substring(2, m.group().length() - 1); // String property = System.getProperty(name); // if (property != null) // line = line.replace(m.group(), property); // } // out.print(line); // firstLine = false; // } // out.close(); // return new ByteArrayInputStream(bytes.toByteArray()); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/github/davidmoten/logan/watcher/Main.java // public class Main { // // private static Logger log = Logger.getLogger(Main.class.getName()); // // /** // * Main method to start the persister. // * // * @param args // * args // * @throws IOException // * exception // */ // public static void main(String[] args) throws IOException { // // Configuration configuration = Configuration.getConfiguration(); // setupLogging(); // // Watcher w = new Watcher(new DataMemory(), configuration); // log.info("starting watcher"); // w.start(); // log.info("started"); // } // // private static void setupLogging() throws IOException { // LogManager.getLogManager() // .readConfiguration(Main.class.getResourceAsStream("/my-logging.properties")); // } // // } // Path: src/main/java/com/github/davidmoten/logan/config/Configuration.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; import java.util.logging.Logger; import javax.xml.bind.annotation.XmlElement; import com.github.davidmoten.logan.util.PropertyReplacer; import com.github.davidmoten.logan.watcher.Main; import com.google.common.collect.Lists; * <code>logan.config</code>. The classpath is checked first then the * filesystem. If the file is not found in neither path then a * {@link RuntimeException} is thrown. * </p> * * <p> * Any properties specified in the configuration.xml file in the format * <code>${property.name}</code> will be replaced with system properties if * set. * </p> * * @return loaded configuration */ public static synchronized Configuration getConfiguration() { String configLocation = System.getProperty("logan.config", DEFAULT_CONFIGURATION_LOCATION); log.info("config=" + configLocation); InputStream is = Main.class.getResourceAsStream(configLocation); if (is == null) { File file = new File(configLocation); if (file.exists()) try { is = new FileInputStream(configLocation); } catch (FileNotFoundException e) { throw new RuntimeException(e); } else throw new RuntimeException( "configuration xml not found. Set property logan.config to a file on classpath or filesystem."); }
InputStream is2 = PropertyReplacer.replaceSystemProperties(is);
sdenier/GecoSI
src/net/gecosi/internal/SiDriver.java
// Path: src/net/gecosi/CommStatus.java // public enum CommStatus { // // OFF, STARTING, READY, ON, PROCESSING, PROCESSING_ERROR, FATAL_ERROR // // } // // Path: src/net/gecosi/SiHandler.java // public class SiHandler implements Runnable { // // private ArrayBlockingQueue<SiDataFrame> dataQueue; // // private SiListener siListener; // // private long zerohour; // // private SiDriver driver; // // private Thread thread; // // // public SiHandler(SiListener siListener) { // this.dataQueue = new ArrayBlockingQueue<SiDataFrame>(5); // this.siListener = siListener; // } // // public void setZeroHour(long zerohour) { // this.zerohour = zerohour; // } // // public void connect(String portname) throws IOException, TooManyListenersException { // try { // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portname); // if( portId.isCurrentlyOwned() ) { // siListener.notify(CommStatus.FATAL_ERROR, "Port owned by other app"); // } else { // GecoSILogger.open("######"); // GecoSILogger.logTime("Start " + portname); // start(); // SerialPort port = (SerialPort) portId.open("GecoSI", 2000); // driver = new SiDriver(new RxtxPort(port), this).start(); // } // } catch (NoSuchPortException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port unknowned"); // } catch (PortInUseException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port in use"); // } // } // // public void readLog(String logFilename) throws IOException { // try { // GecoSILogger.openOutStreamLogger(); // start(); // driver = new SiDriver(new LogFilePort(logFilename), this).start(); // } catch (TooManyListenersException e) { // e.printStackTrace(); // } // } // // public void start() { // thread = new Thread(this); // thread.start(); // } // // public Thread stop() { // if( driver != null ){ // driver.interrupt(); // } // if( thread != null ){ // thread.interrupt(); // } // return thread; // } // // public boolean isAlive() { // return thread != null && thread.isAlive(); // } // // public void notify(SiDataFrame data) { // data.startingAt(zerohour); // dataQueue.offer(data); // TODO check true // } // // public void notify(CommStatus status) { // GecoSILogger.log("!", status.name()); // siListener.notify(status); // } // // public void notifyError(CommStatus errorStatus, String errorMessage) { // GecoSILogger.error(errorMessage); // siListener.notify(errorStatus, errorMessage); // } // // public void run() { // try { // SiDataFrame dataFrame; // while( (dataFrame = dataQueue.take()) != null ) { // siListener.handleEcard(dataFrame); // } // } catch (InterruptedException e) { // dataQueue.clear(); // } // } // // public static void main(String[] args) { // if( args.length == 0 ){ // printUsage(); // System.exit(0); // } // // SiHandler handler = new SiHandler(new SiListener() { // public void handleEcard(SiDataFrame dataFrame) { // dataFrame.printString(); // } // public void notify(CommStatus status) { // System.out.println("Status -> " + status); // } // public void notify(CommStatus errorStatus, String errorMessage) { // System.out.println("Error -> " + errorStatus + " " + errorMessage); // } // }); // // if( args.length == 1 ){ // try { // handler.connect(args[0]); // } catch (Exception e) { // e.printStackTrace(); // } // } // else if( args.length == 2 && args[0].equals("--file") ){ // try { // handler.readLog(args[1]); // } catch (IOException e) { // e.printStackTrace(); // } // } else { // System.err.println("Unknown command line option"); // printUsage(); // System.exit(1); // } // } // // private static void printUsage() { // System.out.println("Usage: java net.gecosi.SiHandler <serial portname> | --file <log filename>"); // } // // }
import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import java.util.concurrent.TimeoutException; import net.gecosi.CommStatus; import net.gecosi.SiHandler;
/** * Copyright (c) 2013 Simon Denier */ package net.gecosi.internal; /** * @author Simon Denier * @since Feb 13, 2013 * */ public class SiDriver implements Runnable { private SiPort siPort; private CommWriter writer; private SiMessageQueue messageQueue; private Thread thread;
// Path: src/net/gecosi/CommStatus.java // public enum CommStatus { // // OFF, STARTING, READY, ON, PROCESSING, PROCESSING_ERROR, FATAL_ERROR // // } // // Path: src/net/gecosi/SiHandler.java // public class SiHandler implements Runnable { // // private ArrayBlockingQueue<SiDataFrame> dataQueue; // // private SiListener siListener; // // private long zerohour; // // private SiDriver driver; // // private Thread thread; // // // public SiHandler(SiListener siListener) { // this.dataQueue = new ArrayBlockingQueue<SiDataFrame>(5); // this.siListener = siListener; // } // // public void setZeroHour(long zerohour) { // this.zerohour = zerohour; // } // // public void connect(String portname) throws IOException, TooManyListenersException { // try { // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portname); // if( portId.isCurrentlyOwned() ) { // siListener.notify(CommStatus.FATAL_ERROR, "Port owned by other app"); // } else { // GecoSILogger.open("######"); // GecoSILogger.logTime("Start " + portname); // start(); // SerialPort port = (SerialPort) portId.open("GecoSI", 2000); // driver = new SiDriver(new RxtxPort(port), this).start(); // } // } catch (NoSuchPortException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port unknowned"); // } catch (PortInUseException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port in use"); // } // } // // public void readLog(String logFilename) throws IOException { // try { // GecoSILogger.openOutStreamLogger(); // start(); // driver = new SiDriver(new LogFilePort(logFilename), this).start(); // } catch (TooManyListenersException e) { // e.printStackTrace(); // } // } // // public void start() { // thread = new Thread(this); // thread.start(); // } // // public Thread stop() { // if( driver != null ){ // driver.interrupt(); // } // if( thread != null ){ // thread.interrupt(); // } // return thread; // } // // public boolean isAlive() { // return thread != null && thread.isAlive(); // } // // public void notify(SiDataFrame data) { // data.startingAt(zerohour); // dataQueue.offer(data); // TODO check true // } // // public void notify(CommStatus status) { // GecoSILogger.log("!", status.name()); // siListener.notify(status); // } // // public void notifyError(CommStatus errorStatus, String errorMessage) { // GecoSILogger.error(errorMessage); // siListener.notify(errorStatus, errorMessage); // } // // public void run() { // try { // SiDataFrame dataFrame; // while( (dataFrame = dataQueue.take()) != null ) { // siListener.handleEcard(dataFrame); // } // } catch (InterruptedException e) { // dataQueue.clear(); // } // } // // public static void main(String[] args) { // if( args.length == 0 ){ // printUsage(); // System.exit(0); // } // // SiHandler handler = new SiHandler(new SiListener() { // public void handleEcard(SiDataFrame dataFrame) { // dataFrame.printString(); // } // public void notify(CommStatus status) { // System.out.println("Status -> " + status); // } // public void notify(CommStatus errorStatus, String errorMessage) { // System.out.println("Error -> " + errorStatus + " " + errorMessage); // } // }); // // if( args.length == 1 ){ // try { // handler.connect(args[0]); // } catch (Exception e) { // e.printStackTrace(); // } // } // else if( args.length == 2 && args[0].equals("--file") ){ // try { // handler.readLog(args[1]); // } catch (IOException e) { // e.printStackTrace(); // } // } else { // System.err.println("Unknown command line option"); // printUsage(); // System.exit(1); // } // } // // private static void printUsage() { // System.out.println("Usage: java net.gecosi.SiHandler <serial portname> | --file <log filename>"); // } // // } // Path: src/net/gecosi/internal/SiDriver.java import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import java.util.concurrent.TimeoutException; import net.gecosi.CommStatus; import net.gecosi.SiHandler; /** * Copyright (c) 2013 Simon Denier */ package net.gecosi.internal; /** * @author Simon Denier * @since Feb 13, 2013 * */ public class SiDriver implements Runnable { private SiPort siPort; private CommWriter writer; private SiMessageQueue messageQueue; private Thread thread;
private SiHandler siHandler;
sdenier/GecoSI
src/net/gecosi/internal/SiDriver.java
// Path: src/net/gecosi/CommStatus.java // public enum CommStatus { // // OFF, STARTING, READY, ON, PROCESSING, PROCESSING_ERROR, FATAL_ERROR // // } // // Path: src/net/gecosi/SiHandler.java // public class SiHandler implements Runnable { // // private ArrayBlockingQueue<SiDataFrame> dataQueue; // // private SiListener siListener; // // private long zerohour; // // private SiDriver driver; // // private Thread thread; // // // public SiHandler(SiListener siListener) { // this.dataQueue = new ArrayBlockingQueue<SiDataFrame>(5); // this.siListener = siListener; // } // // public void setZeroHour(long zerohour) { // this.zerohour = zerohour; // } // // public void connect(String portname) throws IOException, TooManyListenersException { // try { // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portname); // if( portId.isCurrentlyOwned() ) { // siListener.notify(CommStatus.FATAL_ERROR, "Port owned by other app"); // } else { // GecoSILogger.open("######"); // GecoSILogger.logTime("Start " + portname); // start(); // SerialPort port = (SerialPort) portId.open("GecoSI", 2000); // driver = new SiDriver(new RxtxPort(port), this).start(); // } // } catch (NoSuchPortException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port unknowned"); // } catch (PortInUseException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port in use"); // } // } // // public void readLog(String logFilename) throws IOException { // try { // GecoSILogger.openOutStreamLogger(); // start(); // driver = new SiDriver(new LogFilePort(logFilename), this).start(); // } catch (TooManyListenersException e) { // e.printStackTrace(); // } // } // // public void start() { // thread = new Thread(this); // thread.start(); // } // // public Thread stop() { // if( driver != null ){ // driver.interrupt(); // } // if( thread != null ){ // thread.interrupt(); // } // return thread; // } // // public boolean isAlive() { // return thread != null && thread.isAlive(); // } // // public void notify(SiDataFrame data) { // data.startingAt(zerohour); // dataQueue.offer(data); // TODO check true // } // // public void notify(CommStatus status) { // GecoSILogger.log("!", status.name()); // siListener.notify(status); // } // // public void notifyError(CommStatus errorStatus, String errorMessage) { // GecoSILogger.error(errorMessage); // siListener.notify(errorStatus, errorMessage); // } // // public void run() { // try { // SiDataFrame dataFrame; // while( (dataFrame = dataQueue.take()) != null ) { // siListener.handleEcard(dataFrame); // } // } catch (InterruptedException e) { // dataQueue.clear(); // } // } // // public static void main(String[] args) { // if( args.length == 0 ){ // printUsage(); // System.exit(0); // } // // SiHandler handler = new SiHandler(new SiListener() { // public void handleEcard(SiDataFrame dataFrame) { // dataFrame.printString(); // } // public void notify(CommStatus status) { // System.out.println("Status -> " + status); // } // public void notify(CommStatus errorStatus, String errorMessage) { // System.out.println("Error -> " + errorStatus + " " + errorMessage); // } // }); // // if( args.length == 1 ){ // try { // handler.connect(args[0]); // } catch (Exception e) { // e.printStackTrace(); // } // } // else if( args.length == 2 && args[0].equals("--file") ){ // try { // handler.readLog(args[1]); // } catch (IOException e) { // e.printStackTrace(); // } // } else { // System.err.println("Unknown command line option"); // printUsage(); // System.exit(1); // } // } // // private static void printUsage() { // System.out.println("Usage: java net.gecosi.SiHandler <serial portname> | --file <log filename>"); // } // // }
import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import java.util.concurrent.TimeoutException; import net.gecosi.CommStatus; import net.gecosi.SiHandler;
/** * Copyright (c) 2013 Simon Denier */ package net.gecosi.internal; /** * @author Simon Denier * @since Feb 13, 2013 * */ public class SiDriver implements Runnable { private SiPort siPort; private CommWriter writer; private SiMessageQueue messageQueue; private Thread thread; private SiHandler siHandler; public SiDriver(SiPort siPort, SiHandler siHandler) throws TooManyListenersException, IOException { this.siPort = siPort; this.messageQueue = siPort.createMessageQueue(); this.writer = siPort.createWriter(); this.siHandler = siHandler; } public SiDriver start() { thread = new Thread(this); thread.start(); return this; } public void interrupt() { thread.interrupt(); } public void run() { try { SiDriverState currentState = startupBootstrap(); while( isAlive(currentState) ) { GecoSILogger.stateChanged(currentState.name()); currentState = currentState.receive(messageQueue, writer, siHandler); } if( currentState.isError() ) {
// Path: src/net/gecosi/CommStatus.java // public enum CommStatus { // // OFF, STARTING, READY, ON, PROCESSING, PROCESSING_ERROR, FATAL_ERROR // // } // // Path: src/net/gecosi/SiHandler.java // public class SiHandler implements Runnable { // // private ArrayBlockingQueue<SiDataFrame> dataQueue; // // private SiListener siListener; // // private long zerohour; // // private SiDriver driver; // // private Thread thread; // // // public SiHandler(SiListener siListener) { // this.dataQueue = new ArrayBlockingQueue<SiDataFrame>(5); // this.siListener = siListener; // } // // public void setZeroHour(long zerohour) { // this.zerohour = zerohour; // } // // public void connect(String portname) throws IOException, TooManyListenersException { // try { // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portname); // if( portId.isCurrentlyOwned() ) { // siListener.notify(CommStatus.FATAL_ERROR, "Port owned by other app"); // } else { // GecoSILogger.open("######"); // GecoSILogger.logTime("Start " + portname); // start(); // SerialPort port = (SerialPort) portId.open("GecoSI", 2000); // driver = new SiDriver(new RxtxPort(port), this).start(); // } // } catch (NoSuchPortException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port unknowned"); // } catch (PortInUseException e) { // siListener.notify(CommStatus.FATAL_ERROR, "Port in use"); // } // } // // public void readLog(String logFilename) throws IOException { // try { // GecoSILogger.openOutStreamLogger(); // start(); // driver = new SiDriver(new LogFilePort(logFilename), this).start(); // } catch (TooManyListenersException e) { // e.printStackTrace(); // } // } // // public void start() { // thread = new Thread(this); // thread.start(); // } // // public Thread stop() { // if( driver != null ){ // driver.interrupt(); // } // if( thread != null ){ // thread.interrupt(); // } // return thread; // } // // public boolean isAlive() { // return thread != null && thread.isAlive(); // } // // public void notify(SiDataFrame data) { // data.startingAt(zerohour); // dataQueue.offer(data); // TODO check true // } // // public void notify(CommStatus status) { // GecoSILogger.log("!", status.name()); // siListener.notify(status); // } // // public void notifyError(CommStatus errorStatus, String errorMessage) { // GecoSILogger.error(errorMessage); // siListener.notify(errorStatus, errorMessage); // } // // public void run() { // try { // SiDataFrame dataFrame; // while( (dataFrame = dataQueue.take()) != null ) { // siListener.handleEcard(dataFrame); // } // } catch (InterruptedException e) { // dataQueue.clear(); // } // } // // public static void main(String[] args) { // if( args.length == 0 ){ // printUsage(); // System.exit(0); // } // // SiHandler handler = new SiHandler(new SiListener() { // public void handleEcard(SiDataFrame dataFrame) { // dataFrame.printString(); // } // public void notify(CommStatus status) { // System.out.println("Status -> " + status); // } // public void notify(CommStatus errorStatus, String errorMessage) { // System.out.println("Error -> " + errorStatus + " " + errorMessage); // } // }); // // if( args.length == 1 ){ // try { // handler.connect(args[0]); // } catch (Exception e) { // e.printStackTrace(); // } // } // else if( args.length == 2 && args[0].equals("--file") ){ // try { // handler.readLog(args[1]); // } catch (IOException e) { // e.printStackTrace(); // } // } else { // System.err.println("Unknown command line option"); // printUsage(); // System.exit(1); // } // } // // private static void printUsage() { // System.out.println("Usage: java net.gecosi.SiHandler <serial portname> | --file <log filename>"); // } // // } // Path: src/net/gecosi/internal/SiDriver.java import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import java.util.concurrent.TimeoutException; import net.gecosi.CommStatus; import net.gecosi.SiHandler; /** * Copyright (c) 2013 Simon Denier */ package net.gecosi.internal; /** * @author Simon Denier * @since Feb 13, 2013 * */ public class SiDriver implements Runnable { private SiPort siPort; private CommWriter writer; private SiMessageQueue messageQueue; private Thread thread; private SiHandler siHandler; public SiDriver(SiPort siPort, SiHandler siHandler) throws TooManyListenersException, IOException { this.siPort = siPort; this.messageQueue = siPort.createMessageQueue(); this.writer = siPort.createWriter(); this.siHandler = siHandler; } public SiDriver start() { thread = new Thread(this); thread.start(); return this; } public void interrupt() { thread.interrupt(); } public void run() { try { SiDriverState currentState = startupBootstrap(); while( isAlive(currentState) ) { GecoSILogger.stateChanged(currentState.name()); currentState = currentState.receive(messageQueue, writer, siHandler); } if( currentState.isError() ) {
siHandler.notifyError(CommStatus.FATAL_ERROR, currentState.status());
sdenier/GecoSI
src/net/gecosi/adapter/logfile/LogFilePort.java
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // }
import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort;
/** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.logfile; /** * @author Simon Denier * @since Apr 28, 2013 * */ public class LogFilePort implements SiPort { private String logFilename; public LogFilePort(String logFilename) { this.logFilename = logFilename; } @Override
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // } // Path: src/net/gecosi/adapter/logfile/LogFilePort.java import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort; /** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.logfile; /** * @author Simon Denier * @since Apr 28, 2013 * */ public class LogFilePort implements SiPort { private String logFilename; public LogFilePort(String logFilename) { this.logFilename = logFilename; } @Override
public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException {
sdenier/GecoSI
src/net/gecosi/adapter/logfile/LogFilePort.java
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // }
import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort;
/** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.logfile; /** * @author Simon Denier * @since Apr 28, 2013 * */ public class LogFilePort implements SiPort { private String logFilename; public LogFilePort(String logFilename) { this.logFilename = logFilename; } @Override public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException { return new LogFileCommReader(logFilename).createMessageQueue(); } @Override
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // } // Path: src/net/gecosi/adapter/logfile/LogFilePort.java import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort; /** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.logfile; /** * @author Simon Denier * @since Apr 28, 2013 * */ public class LogFilePort implements SiPort { private String logFilename; public LogFilePort(String logFilename) { this.logFilename = logFilename; } @Override public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException { return new LogFileCommReader(logFilename).createMessageQueue(); } @Override
public CommWriter createWriter() throws IOException {
sdenier/GecoSI
src/net/gecosi/adapter/rxtx/RxtxPort.java
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // }
import gnu.io.SerialPort; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort;
/** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.rxtx; /** * @author Simon Denier * @since Mar 10, 2013 * */ public class RxtxPort implements SiPort { private SerialPort port; public RxtxPort(SerialPort port) { this.port = port; } public SerialPort getPort() { return port; }
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // } // Path: src/net/gecosi/adapter/rxtx/RxtxPort.java import gnu.io.SerialPort; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort; /** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.rxtx; /** * @author Simon Denier * @since Mar 10, 2013 * */ public class RxtxPort implements SiPort { private SerialPort port; public RxtxPort(SerialPort port) { this.port = port; } public SerialPort getPort() { return port; }
public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException {
sdenier/GecoSI
src/net/gecosi/adapter/rxtx/RxtxPort.java
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // }
import gnu.io.SerialPort; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort;
/** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.rxtx; /** * @author Simon Denier * @since Mar 10, 2013 * */ public class RxtxPort implements SiPort { private SerialPort port; public RxtxPort(SerialPort port) { this.port = port; } public SerialPort getPort() { return port; } public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException { SiMessageQueue messageQueue = new SiMessageQueue(10); port.addEventListener(new RxtxCommReader(port.getInputStream(), messageQueue)); port.notifyOnDataAvailable(true); return messageQueue; }
// Path: src/net/gecosi/internal/CommWriter.java // public interface CommWriter { // // public void write(SiMessage message) throws IOException; // // } // // Path: src/net/gecosi/internal/SiMessageQueue.java // public class SiMessageQueue extends ArrayBlockingQueue<SiMessage> { // // private long defaultTimeout; // // public SiMessageQueue(int capacity) { // this(capacity, 2000); // } // // public SiMessageQueue(int capacity, long defaultTimeout) { // super(capacity); // this.defaultTimeout = defaultTimeout; // } // // public SiMessage timeoutPoll() throws InterruptedException, TimeoutException { // SiMessage message = poll(defaultTimeout, TimeUnit.MILLISECONDS); // if( message != null ){ // return message; // } else { // throw new TimeoutException(); // } // } // // } // // Path: src/net/gecosi/internal/SiPort.java // public interface SiPort { // // public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException; // // public CommWriter createWriter() throws IOException; // // public void setupHighSpeed() throws UnsupportedCommOperationException; // // public void setupLowSpeed() throws UnsupportedCommOperationException; // // public void close(); // // } // Path: src/net/gecosi/adapter/rxtx/RxtxPort.java import gnu.io.SerialPort; import gnu.io.UnsupportedCommOperationException; import java.io.IOException; import java.util.TooManyListenersException; import net.gecosi.internal.CommWriter; import net.gecosi.internal.SiMessageQueue; import net.gecosi.internal.SiPort; /** * Copyright (c) 2013 Simon Denier */ package net.gecosi.adapter.rxtx; /** * @author Simon Denier * @since Mar 10, 2013 * */ public class RxtxPort implements SiPort { private SerialPort port; public RxtxPort(SerialPort port) { this.port = port; } public SerialPort getPort() { return port; } public SiMessageQueue createMessageQueue() throws TooManyListenersException, IOException { SiMessageQueue messageQueue = new SiMessageQueue(10); port.addEventListener(new RxtxCommReader(port.getInputStream(), messageQueue)); port.notifyOnDataAvailable(true); return messageQueue; }
public CommWriter createWriter() throws IOException {
sbrosinski/RegexTester
src/com/brosinski/eclipse/regex/view/RegExPreferencePage.java
// Path: src/com/brosinski/eclipse/regex/RegExPlugin.java // public class RegExPlugin extends AbstractUIPlugin { // // private static RegExPlugin plugin; // // //Resource bundle. // private ResourceBundle resourceBundle; // // /** // * The constructor. // */ // public RegExPlugin() { // } // // /** // * This method is called upon plug-in activation // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // try { // resourceBundle = ResourceBundle.getBundle("com.brosinski.eclipse.regex.PluginResources"); // } catch (MissingResourceException x) { // resourceBundle = null; // } // } // // /** // * This method is called when the plug-in is stopped // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // resourceBundle = null; // super.stop(context); // } // // /** // * Returns the shared instance. // */ // public static RegExPlugin getDefault() { // return plugin; // } // // /** // * Returns the string from the plugin's resource bundle, // * or 'key' if not found. // */ // public static String getResourceString(String key) { // ResourceBundle bundle = RegExPlugin.getDefault().getResourceBundle(); // try { // return (bundle != null) ? bundle.getString(key) : key; // } catch (MissingResourceException e) { // return key; // } // } // // /** // * Returns the plugin's resource bundle, // */ // public ResourceBundle getResourceBundle() { // return resourceBundle; // } // // // // protected void initializeDefaultPluginPreferences() { // getPreferenceStore().setDefault("Pattern.CANON_EQ",false); // getPreferenceStore().setDefault("Pattern.CASE_INSENSITIVE",false); // getPreferenceStore().setDefault("Pattern.COMMENTS",false); // getPreferenceStore().setDefault("Pattern.DOTALL",false); // getPreferenceStore().setDefault("Pattern.MULTILINE",false); // getPreferenceStore().setDefault("Pattern.UNICODE_CASE",false); // getPreferenceStore().setDefault("Pattern.UNIX_LINES",false); // getPreferenceStore().setDefault("EvalRegEx",false); // getPreferenceStore().setDefault("EvalSearch",false); // getPreferenceStore().setDefault("EvalBoth",true); // getPreferenceStore().setDefault("EvalSwitch",false); // // FontData systemFont = Display.getCurrent().getSystemFont().getFontData()[0]; // // getPreferenceStore().setDefault("font.regex.name", systemFont.getName()); // getPreferenceStore().setDefault("font.regex.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.regex.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.searchtext.name", systemFont.getName()); // getPreferenceStore().setDefault("font.searchtext.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.searchtext.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.result.name", systemFont.getName()); // getPreferenceStore().setDefault("font.result.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.result.style", systemFont.getStyle()); // } // // // public ImageDescriptor getImageDescriptor(String imageName) { // return imageDescriptorFromPlugin("com.brosinski.eclipse.regex", "icons/" + imageName); // } // // // }
import java.util.regex.Pattern; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.brosinski.eclipse.regex.RegExPlugin;
/******************************************************************************* * Copyright (c) 2012 Stephan Brosinski * * All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stephan Brosinski - initial API and implementation ******************************************************************************/ package com.brosinski.eclipse.regex.view; public class RegExPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private Button btn_CanonicalEquivalence; private Button btn_CaseInsensitive; private Button btn_Comments; private Button btn_DotallMode; private Button btn_MultilineMode; private Button btn_UnicodeCase; private Button btn_UnixLines; private Button btn_EvalRegEx; private Button btn_EvalSearch; private Button btn_EvalBoth; private Button btn_EvalSwitch; public RegExPreferencePage() { } public void init(IWorkbench workbench) {
// Path: src/com/brosinski/eclipse/regex/RegExPlugin.java // public class RegExPlugin extends AbstractUIPlugin { // // private static RegExPlugin plugin; // // //Resource bundle. // private ResourceBundle resourceBundle; // // /** // * The constructor. // */ // public RegExPlugin() { // } // // /** // * This method is called upon plug-in activation // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // try { // resourceBundle = ResourceBundle.getBundle("com.brosinski.eclipse.regex.PluginResources"); // } catch (MissingResourceException x) { // resourceBundle = null; // } // } // // /** // * This method is called when the plug-in is stopped // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // resourceBundle = null; // super.stop(context); // } // // /** // * Returns the shared instance. // */ // public static RegExPlugin getDefault() { // return plugin; // } // // /** // * Returns the string from the plugin's resource bundle, // * or 'key' if not found. // */ // public static String getResourceString(String key) { // ResourceBundle bundle = RegExPlugin.getDefault().getResourceBundle(); // try { // return (bundle != null) ? bundle.getString(key) : key; // } catch (MissingResourceException e) { // return key; // } // } // // /** // * Returns the plugin's resource bundle, // */ // public ResourceBundle getResourceBundle() { // return resourceBundle; // } // // // // protected void initializeDefaultPluginPreferences() { // getPreferenceStore().setDefault("Pattern.CANON_EQ",false); // getPreferenceStore().setDefault("Pattern.CASE_INSENSITIVE",false); // getPreferenceStore().setDefault("Pattern.COMMENTS",false); // getPreferenceStore().setDefault("Pattern.DOTALL",false); // getPreferenceStore().setDefault("Pattern.MULTILINE",false); // getPreferenceStore().setDefault("Pattern.UNICODE_CASE",false); // getPreferenceStore().setDefault("Pattern.UNIX_LINES",false); // getPreferenceStore().setDefault("EvalRegEx",false); // getPreferenceStore().setDefault("EvalSearch",false); // getPreferenceStore().setDefault("EvalBoth",true); // getPreferenceStore().setDefault("EvalSwitch",false); // // FontData systemFont = Display.getCurrent().getSystemFont().getFontData()[0]; // // getPreferenceStore().setDefault("font.regex.name", systemFont.getName()); // getPreferenceStore().setDefault("font.regex.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.regex.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.searchtext.name", systemFont.getName()); // getPreferenceStore().setDefault("font.searchtext.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.searchtext.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.result.name", systemFont.getName()); // getPreferenceStore().setDefault("font.result.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.result.style", systemFont.getStyle()); // } // // // public ImageDescriptor getImageDescriptor(String imageName) { // return imageDescriptorFromPlugin("com.brosinski.eclipse.regex", "icons/" + imageName); // } // // // } // Path: src/com/brosinski/eclipse/regex/view/RegExPreferencePage.java import java.util.regex.Pattern; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.brosinski.eclipse.regex.RegExPlugin; /******************************************************************************* * Copyright (c) 2012 Stephan Brosinski * * All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stephan Brosinski - initial API and implementation ******************************************************************************/ package com.brosinski.eclipse.regex.view; public class RegExPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private Button btn_CanonicalEquivalence; private Button btn_CaseInsensitive; private Button btn_Comments; private Button btn_DotallMode; private Button btn_MultilineMode; private Button btn_UnicodeCase; private Button btn_UnixLines; private Button btn_EvalRegEx; private Button btn_EvalSearch; private Button btn_EvalBoth; private Button btn_EvalSwitch; public RegExPreferencePage() { } public void init(IWorkbench workbench) {
this.setPreferenceStore(RegExPlugin.getDefault().getPreferenceStore());
sbrosinski/RegexTester
src/com/brosinski/eclipse/regex/view/LiveEval.java
// Path: src/com/brosinski/eclipse/regex/RegExPlugin.java // public class RegExPlugin extends AbstractUIPlugin { // // private static RegExPlugin plugin; // // //Resource bundle. // private ResourceBundle resourceBundle; // // /** // * The constructor. // */ // public RegExPlugin() { // } // // /** // * This method is called upon plug-in activation // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // try { // resourceBundle = ResourceBundle.getBundle("com.brosinski.eclipse.regex.PluginResources"); // } catch (MissingResourceException x) { // resourceBundle = null; // } // } // // /** // * This method is called when the plug-in is stopped // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // resourceBundle = null; // super.stop(context); // } // // /** // * Returns the shared instance. // */ // public static RegExPlugin getDefault() { // return plugin; // } // // /** // * Returns the string from the plugin's resource bundle, // * or 'key' if not found. // */ // public static String getResourceString(String key) { // ResourceBundle bundle = RegExPlugin.getDefault().getResourceBundle(); // try { // return (bundle != null) ? bundle.getString(key) : key; // } catch (MissingResourceException e) { // return key; // } // } // // /** // * Returns the plugin's resource bundle, // */ // public ResourceBundle getResourceBundle() { // return resourceBundle; // } // // // // protected void initializeDefaultPluginPreferences() { // getPreferenceStore().setDefault("Pattern.CANON_EQ",false); // getPreferenceStore().setDefault("Pattern.CASE_INSENSITIVE",false); // getPreferenceStore().setDefault("Pattern.COMMENTS",false); // getPreferenceStore().setDefault("Pattern.DOTALL",false); // getPreferenceStore().setDefault("Pattern.MULTILINE",false); // getPreferenceStore().setDefault("Pattern.UNICODE_CASE",false); // getPreferenceStore().setDefault("Pattern.UNIX_LINES",false); // getPreferenceStore().setDefault("EvalRegEx",false); // getPreferenceStore().setDefault("EvalSearch",false); // getPreferenceStore().setDefault("EvalBoth",true); // getPreferenceStore().setDefault("EvalSwitch",false); // // FontData systemFont = Display.getCurrent().getSystemFont().getFontData()[0]; // // getPreferenceStore().setDefault("font.regex.name", systemFont.getName()); // getPreferenceStore().setDefault("font.regex.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.regex.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.searchtext.name", systemFont.getName()); // getPreferenceStore().setDefault("font.searchtext.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.searchtext.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.result.name", systemFont.getName()); // getPreferenceStore().setDefault("font.result.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.result.style", systemFont.getStyle()); // } // // // public ImageDescriptor getImageDescriptor(String imageName) { // return imageDescriptorFromPlugin("com.brosinski.eclipse.regex", "icons/" + imageName); // } // // // }
import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.custom.ExtendedModifyEvent; import org.eclipse.swt.custom.ExtendedModifyListener; import org.eclipse.swt.custom.StyledText; import com.brosinski.eclipse.regex.RegExPlugin;
/******************************************************************************* * Copyright (c) 2012 Stephan Brosinski * * All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stephan Brosinski - initial API and implementation ******************************************************************************/ package com.brosinski.eclipse.regex.view; public class LiveEval { private LiveEvalListenerManager liveEvalListenerManager; class LiveEvalListener implements ExtendedModifyListener { public void modifyText(ExtendedModifyEvent event) { if (LiveEval.this.isLiveEval()) LiveEval.this.doEval(); } } private boolean isLiveEval; private LiveEvalListener liveEvalListener; private StyledText regEx, searchText;
// Path: src/com/brosinski/eclipse/regex/RegExPlugin.java // public class RegExPlugin extends AbstractUIPlugin { // // private static RegExPlugin plugin; // // //Resource bundle. // private ResourceBundle resourceBundle; // // /** // * The constructor. // */ // public RegExPlugin() { // } // // /** // * This method is called upon plug-in activation // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // try { // resourceBundle = ResourceBundle.getBundle("com.brosinski.eclipse.regex.PluginResources"); // } catch (MissingResourceException x) { // resourceBundle = null; // } // } // // /** // * This method is called when the plug-in is stopped // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // resourceBundle = null; // super.stop(context); // } // // /** // * Returns the shared instance. // */ // public static RegExPlugin getDefault() { // return plugin; // } // // /** // * Returns the string from the plugin's resource bundle, // * or 'key' if not found. // */ // public static String getResourceString(String key) { // ResourceBundle bundle = RegExPlugin.getDefault().getResourceBundle(); // try { // return (bundle != null) ? bundle.getString(key) : key; // } catch (MissingResourceException e) { // return key; // } // } // // /** // * Returns the plugin's resource bundle, // */ // public ResourceBundle getResourceBundle() { // return resourceBundle; // } // // // // protected void initializeDefaultPluginPreferences() { // getPreferenceStore().setDefault("Pattern.CANON_EQ",false); // getPreferenceStore().setDefault("Pattern.CASE_INSENSITIVE",false); // getPreferenceStore().setDefault("Pattern.COMMENTS",false); // getPreferenceStore().setDefault("Pattern.DOTALL",false); // getPreferenceStore().setDefault("Pattern.MULTILINE",false); // getPreferenceStore().setDefault("Pattern.UNICODE_CASE",false); // getPreferenceStore().setDefault("Pattern.UNIX_LINES",false); // getPreferenceStore().setDefault("EvalRegEx",false); // getPreferenceStore().setDefault("EvalSearch",false); // getPreferenceStore().setDefault("EvalBoth",true); // getPreferenceStore().setDefault("EvalSwitch",false); // // FontData systemFont = Display.getCurrent().getSystemFont().getFontData()[0]; // // getPreferenceStore().setDefault("font.regex.name", systemFont.getName()); // getPreferenceStore().setDefault("font.regex.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.regex.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.searchtext.name", systemFont.getName()); // getPreferenceStore().setDefault("font.searchtext.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.searchtext.style", systemFont.getStyle()); // getPreferenceStore().setDefault("font.result.name", systemFont.getName()); // getPreferenceStore().setDefault("font.result.height", systemFont.getHeight()); // getPreferenceStore().setDefault("font.result.style", systemFont.getStyle()); // } // // // public ImageDescriptor getImageDescriptor(String imageName) { // return imageDescriptorFromPlugin("com.brosinski.eclipse.regex", "icons/" + imageName); // } // // // } // Path: src/com/brosinski/eclipse/regex/view/LiveEval.java import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.swt.custom.ExtendedModifyEvent; import org.eclipse.swt.custom.ExtendedModifyListener; import org.eclipse.swt.custom.StyledText; import com.brosinski.eclipse.regex.RegExPlugin; /******************************************************************************* * Copyright (c) 2012 Stephan Brosinski * * All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stephan Brosinski - initial API and implementation ******************************************************************************/ package com.brosinski.eclipse.regex.view; public class LiveEval { private LiveEvalListenerManager liveEvalListenerManager; class LiveEvalListener implements ExtendedModifyListener { public void modifyText(ExtendedModifyEvent event) { if (LiveEval.this.isLiveEval()) LiveEval.this.doEval(); } } private boolean isLiveEval; private LiveEvalListener liveEvalListener; private StyledText regEx, searchText;
private IPreferenceStore prefs = RegExPlugin.getDefault()
yangshuai0711/dingding-app-server
dingding-app-server-web/src/main/java/com/mocoder/dingding/web/exception/ParameterValidateException.java
// Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/enums/ErrorTypeEnum.java // public enum ErrorTypeEnum { // // SYSTEM_EXCEPTION(10,"后台程序异常","系统繁忙,请重试"), // SYSTEM_ENV_EXCEPTION(11,"系统环境异常","系统繁忙,请重试"), // // INPUT_PARAMETER_VALIDATE_ERROR(20,"参数校验错误","系统繁忙,请重试"), // INPUT_PARAMETER_SESSION_ERROR(-20,"参数sessionId为空","系统繁忙,请重试"), // INPUT_PARAMETER_PARSE_ERROR(21,"入参解析错误","系统繁忙,请重试"), // // VALIDATE_CODE_ERROR(30,"验证码不正确","验证码输入有误,请重试"), // VALIDATE_CODE_RETRY_ERROR(-30,"验证码不正确","验证码输入错误次数超过限制,请重新获取验证码"), // NOT_LOGIN(-31,"未登录","您的登录信息已过期,请重新登录"), // LOGIN_DUPLICATE_ERROR(31,"重复登录,session未过期,无需登录" ,"您已经在线,无需再次登录" ), // REG_DUPLICATE_ERROR(32,"重复注册,手机号码已注册" ,"您的手机号码已注册" ), // PASS_LOGIN_ERROR(33,"密码错误","账号或密码错误"), // ACCOUNT_NOT_EXISTS(35,"手机号不存在","该手机号还没有注册"), // NOT_LOG_OUT_ERROR(36,"需要退出登录状态","请先退出登录"), // // SMS_SEND_ERROR(40,"短信发送失败","短信发送失败,请稍后再试"), // // USER_OPERATE_NOT_PERMIT(50,"用户没有权限进行此操作","您没有权限进行此操作") // ; // // private Integer code; // private String msg; // private String uiMsg; // // ErrorTypeEnum(Integer code, String msg, String uiMsg) { // this.code = code; // this.msg = msg; // this.uiMsg = uiMsg; // } // // public Integer getCode() { // return code; // } // // public String getMsg() { // return msg; // } // // public String getUiMsg() { // return uiMsg; // } // } // // Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/vo/CommonResponse.java // public class CommonResponse<T> implements Serializable { // private String code; // private String msg; // private T data; // // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public void resolveErrorInfo(ErrorTypeEnum errorType) { // this.code=String.valueOf(errorType.getCode()); // this.msg =errorType.getUiMsg(); // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // }
import com.mocoder.dingding.enums.ErrorTypeEnum; import com.mocoder.dingding.vo.CommonResponse;
package com.mocoder.dingding.web.exception; /** * Created by yangshuai3 on 2016/2/4. */ public class ParameterValidateException extends Exception{ private CommonResponse response = new CommonResponse(); public ParameterValidateException(Throwable cause) { super(cause);
// Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/enums/ErrorTypeEnum.java // public enum ErrorTypeEnum { // // SYSTEM_EXCEPTION(10,"后台程序异常","系统繁忙,请重试"), // SYSTEM_ENV_EXCEPTION(11,"系统环境异常","系统繁忙,请重试"), // // INPUT_PARAMETER_VALIDATE_ERROR(20,"参数校验错误","系统繁忙,请重试"), // INPUT_PARAMETER_SESSION_ERROR(-20,"参数sessionId为空","系统繁忙,请重试"), // INPUT_PARAMETER_PARSE_ERROR(21,"入参解析错误","系统繁忙,请重试"), // // VALIDATE_CODE_ERROR(30,"验证码不正确","验证码输入有误,请重试"), // VALIDATE_CODE_RETRY_ERROR(-30,"验证码不正确","验证码输入错误次数超过限制,请重新获取验证码"), // NOT_LOGIN(-31,"未登录","您的登录信息已过期,请重新登录"), // LOGIN_DUPLICATE_ERROR(31,"重复登录,session未过期,无需登录" ,"您已经在线,无需再次登录" ), // REG_DUPLICATE_ERROR(32,"重复注册,手机号码已注册" ,"您的手机号码已注册" ), // PASS_LOGIN_ERROR(33,"密码错误","账号或密码错误"), // ACCOUNT_NOT_EXISTS(35,"手机号不存在","该手机号还没有注册"), // NOT_LOG_OUT_ERROR(36,"需要退出登录状态","请先退出登录"), // // SMS_SEND_ERROR(40,"短信发送失败","短信发送失败,请稍后再试"), // // USER_OPERATE_NOT_PERMIT(50,"用户没有权限进行此操作","您没有权限进行此操作") // ; // // private Integer code; // private String msg; // private String uiMsg; // // ErrorTypeEnum(Integer code, String msg, String uiMsg) { // this.code = code; // this.msg = msg; // this.uiMsg = uiMsg; // } // // public Integer getCode() { // return code; // } // // public String getMsg() { // return msg; // } // // public String getUiMsg() { // return uiMsg; // } // } // // Path: dingding-app-server-model/src/main/java/com/mocoder/dingding/vo/CommonResponse.java // public class CommonResponse<T> implements Serializable { // private String code; // private String msg; // private T data; // // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public void resolveErrorInfo(ErrorTypeEnum errorType) { // this.code=String.valueOf(errorType.getCode()); // this.msg =errorType.getUiMsg(); // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // Path: dingding-app-server-web/src/main/java/com/mocoder/dingding/web/exception/ParameterValidateException.java import com.mocoder.dingding.enums.ErrorTypeEnum; import com.mocoder.dingding.vo.CommonResponse; package com.mocoder.dingding.web.exception; /** * Created by yangshuai3 on 2016/2/4. */ public class ParameterValidateException extends Exception{ private CommonResponse response = new CommonResponse(); public ParameterValidateException(Throwable cause) { super(cause);
response.resolveErrorInfo(ErrorTypeEnum.INPUT_PARAMETER_VALIDATE_ERROR);
yangshuai0711/dingding-app-server
dingding-app-server-web/src/test/java/com/mocoder/dingding/test/client/HttpClientUtil.java
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/encryp/EncryptUtils.java // public class EncryptUtils { // // private static final BASE64Encoder base64Encoder = new BASE64Encoder(); // private static final BASE64Decoder base64Decoder = new BASE64Decoder(); // // // public static String md5(String sourceStr) { // return DigestUtils.md5Hex(sourceStr); // } // // public static String sha1(String src) { // return DigestUtils.sha1Hex(src); // } // // public static String base64Encode(String src) { // return base64Encoder.encode(StringUtils.getBytesUtf8(src)); // } // // public static String base64Decode(String src) throws IOException { // return StringUtils.newStringUtf8(base64Decoder.decodeBuffer(src)); // } // // /** // * DES算法,加密 // * // * @param data 待加密字符串 // * @param key 加密私钥,长度不能够小于8位 // * @return 加密后字符串 // * @throws Exception // */ // public static String desEncode(String key, String data) { // if (data == null) // return null; // try { // DESKeySpec dks = new DESKeySpec(StringUtils.getBytesUtf8(key)); // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // //key的长度不能够小于8位字节 // Key secretKey = keyFactory.generateSecret(dks); // Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // IvParameterSpec iv = new IvParameterSpec(StringUtils.getBytesUtf8("12345678")); // AlgorithmParameterSpec paramSpec = iv; // cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); // byte[] bytes = cipher.doFinal(StringUtils.getBytesUtf8(data)); // return Hex.encodeHexString(bytes); // } catch (Exception e) { // throw new RuntimeException("des加密失败", e); // } // } // // /** // * DES算法,解密 // * // * @param data 待解密字符串 // * @param key 解密私钥,长度不能够小于8位 // * @return 解密后的字符串 // * @throws Exception 异常 // */ // public static String desDecode(String key, String data) { // if (data == null) // return null; // try { // DESKeySpec dks = new DESKeySpec(StringUtils.getBytesUtf8(key)); // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // //key的长度不能够小于8位字节 // Key secretKey = keyFactory.generateSecret(dks); // Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // IvParameterSpec iv = new IvParameterSpec(StringUtils.getBytesUtf8("12345678")); // AlgorithmParameterSpec paramSpec = iv; // cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec); // byte[] bytes = Hex.decodeHex(data.toCharArray()); // return StringUtils.newStringUtf8(cipher.doFinal(bytes)); // } catch (Exception e) { // throw new RuntimeException("des解密失败", e); // } // } // // public static void main(String[] args) throws DecoderException { // String str = base64Encode("[{\"mobile\":\"1565230哈哈60\",\"age\":3]}"); // System.out.println(str); // try { // System.out.println(base64Decode(str)); // } catch (IOException e) { // } // String str2 = desEncode("123123123","[{\"mobile\":\"1565230哈哈60\",\"age\":3]}"); // System.out.println(str2); // System.out.println(desDecode("123123123",str2)); // } // }
import com.mocoder.dingding.utils.encryp.EncryptUtils; import javax.net.ssl.*; import java.io.*; import java.net.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Iterator; import java.util.Map;
@Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }}; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, null); sslSocketFactory = sslContext.getSocketFactory(); } catch (Exception e) { new RuntimeException(e); } } public static void main(String[] args) { String tmpStr = "14589071547192919-5308-35d3d1ec-a2a7-48b7-b7ce-abafaf3be4ec66666";
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/encryp/EncryptUtils.java // public class EncryptUtils { // // private static final BASE64Encoder base64Encoder = new BASE64Encoder(); // private static final BASE64Decoder base64Decoder = new BASE64Decoder(); // // // public static String md5(String sourceStr) { // return DigestUtils.md5Hex(sourceStr); // } // // public static String sha1(String src) { // return DigestUtils.sha1Hex(src); // } // // public static String base64Encode(String src) { // return base64Encoder.encode(StringUtils.getBytesUtf8(src)); // } // // public static String base64Decode(String src) throws IOException { // return StringUtils.newStringUtf8(base64Decoder.decodeBuffer(src)); // } // // /** // * DES算法,加密 // * // * @param data 待加密字符串 // * @param key 加密私钥,长度不能够小于8位 // * @return 加密后字符串 // * @throws Exception // */ // public static String desEncode(String key, String data) { // if (data == null) // return null; // try { // DESKeySpec dks = new DESKeySpec(StringUtils.getBytesUtf8(key)); // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // //key的长度不能够小于8位字节 // Key secretKey = keyFactory.generateSecret(dks); // Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // IvParameterSpec iv = new IvParameterSpec(StringUtils.getBytesUtf8("12345678")); // AlgorithmParameterSpec paramSpec = iv; // cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); // byte[] bytes = cipher.doFinal(StringUtils.getBytesUtf8(data)); // return Hex.encodeHexString(bytes); // } catch (Exception e) { // throw new RuntimeException("des加密失败", e); // } // } // // /** // * DES算法,解密 // * // * @param data 待解密字符串 // * @param key 解密私钥,长度不能够小于8位 // * @return 解密后的字符串 // * @throws Exception 异常 // */ // public static String desDecode(String key, String data) { // if (data == null) // return null; // try { // DESKeySpec dks = new DESKeySpec(StringUtils.getBytesUtf8(key)); // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // //key的长度不能够小于8位字节 // Key secretKey = keyFactory.generateSecret(dks); // Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // IvParameterSpec iv = new IvParameterSpec(StringUtils.getBytesUtf8("12345678")); // AlgorithmParameterSpec paramSpec = iv; // cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec); // byte[] bytes = Hex.decodeHex(data.toCharArray()); // return StringUtils.newStringUtf8(cipher.doFinal(bytes)); // } catch (Exception e) { // throw new RuntimeException("des解密失败", e); // } // } // // public static void main(String[] args) throws DecoderException { // String str = base64Encode("[{\"mobile\":\"1565230哈哈60\",\"age\":3]}"); // System.out.println(str); // try { // System.out.println(base64Decode(str)); // } catch (IOException e) { // } // String str2 = desEncode("123123123","[{\"mobile\":\"1565230哈哈60\",\"age\":3]}"); // System.out.println(str2); // System.out.println(desDecode("123123123",str2)); // } // } // Path: dingding-app-server-web/src/test/java/com/mocoder/dingding/test/client/HttpClientUtil.java import com.mocoder.dingding.utils.encryp.EncryptUtils; import javax.net.ssl.*; import java.io.*; import java.net.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Iterator; import java.util.Map; @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }}; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, null); sslSocketFactory = sslContext.getSocketFactory(); } catch (Exception e) { new RuntimeException(e); } } public static void main(String[] args) { String tmpStr = "14589071547192919-5308-35d3d1ec-a2a7-48b7-b7ce-abafaf3be4ec66666";
String targetToken = EncryptUtils.md5(tmpStr);
yangshuai0711/dingding-app-server
dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/JsonUtil.java
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/bean/TypeRef.java // public class TypeRef<T> extends TypeReference<T> { // // @Override // public int compareTo(TypeReference<T> o) { // return this.getType().equals(o.getType())?0:1; // } // }
import com.mocoder.dingding.utils.bean.TypeRef; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.type.TypeReference; import java.io.IOException;
package com.mocoder.dingding.utils.web; /** * Created by yangshuai3 on 2016/1/26. */ public class JsonUtil { /** * 将对象按照json字符串格式输出 * * @param obj javabean对象实例 * @return json字符串 * @throws IOException */ public static String toString(Object obj) throws IOException { if(obj==null){ return null; } ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); return mapper.writeValueAsString(obj); } /** * 解析json字符串格式到javabean对象 * * @param json json字符串 * @param type 类型包装类,new新实力请带上泛型 * @param <T> 目标对象类型 * @return 目标对象实例 * @throws IOException */
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/bean/TypeRef.java // public class TypeRef<T> extends TypeReference<T> { // // @Override // public int compareTo(TypeReference<T> o) { // return this.getType().equals(o.getType())?0:1; // } // } // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/JsonUtil.java import com.mocoder.dingding.utils.bean.TypeRef; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.type.TypeReference; import java.io.IOException; package com.mocoder.dingding.utils.web; /** * Created by yangshuai3 on 2016/1/26. */ public class JsonUtil { /** * 将对象按照json字符串格式输出 * * @param obj javabean对象实例 * @return json字符串 * @throws IOException */ public static String toString(Object obj) throws IOException { if(obj==null){ return null; } ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); return mapper.writeValueAsString(obj); } /** * 解析json字符串格式到javabean对象 * * @param json json字符串 * @param type 类型包装类,new新实力请带上泛型 * @param <T> 目标对象类型 * @return 目标对象实例 * @throws IOException */
public static <T> T toObject(String json, TypeRef<T> type) throws IOException {
yangshuai0711/dingding-app-server
dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/RedisUtil.java
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/bean/TypeRef.java // public class TypeRef<T> extends TypeReference<T> { // // @Override // public int compareTo(TypeReference<T> o) { // return this.getType().equals(o.getType())?0:1; // } // } // // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/spring/SpringContextHolder.java // public class SpringContextHolder implements ApplicationContextAware{ // private static ApplicationContext context; // @Override // public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // context = applicationContext; // } // // public static <T> T getBean(Class<T> claz){ // return context.getBean(claz); // } // // public static <T> T getBean(String name){ // return (T)context.getBean(name); // } // }
import com.mocoder.dingding.utils.bean.TypeRef; import com.mocoder.dingding.utils.spring.SpringContextHolder; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.LinkedHashMap; import java.util.Map;
package com.mocoder.dingding.utils.web; /** * Created by yangshuai on 16/1/31. */ public class RedisUtil { private static RedisTemplate redisTemplate; static {
// Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/bean/TypeRef.java // public class TypeRef<T> extends TypeReference<T> { // // @Override // public int compareTo(TypeReference<T> o) { // return this.getType().equals(o.getType())?0:1; // } // } // // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/spring/SpringContextHolder.java // public class SpringContextHolder implements ApplicationContextAware{ // private static ApplicationContext context; // @Override // public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // context = applicationContext; // } // // public static <T> T getBean(Class<T> claz){ // return context.getBean(claz); // } // // public static <T> T getBean(String name){ // return (T)context.getBean(name); // } // } // Path: dingding-app-server-utils/src/main/java/com/mocoder/dingding/utils/web/RedisUtil.java import com.mocoder.dingding.utils.bean.TypeRef; import com.mocoder.dingding.utils.spring.SpringContextHolder; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.LinkedHashMap; import java.util.Map; package com.mocoder.dingding.utils.web; /** * Created by yangshuai on 16/1/31. */ public class RedisUtil { private static RedisTemplate redisTemplate; static {
redisTemplate = SpringContextHolder.getBean(RedisTemplate.class);