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
yiding-he/hydrogen-ssdb
src/test/java/com/hyd/ssdb/SsdbClientMultiThreadTest.java
// Path: src/main/java/com/hyd/ssdb/protocol/Request.java // public class Request { // // private Charset charset = AbstractClient.DEFAULT_CHARSET; // // private Block header; // // private Server forceServer; // 强制指定请求的发送地址 // // private final List<Block> blocks = new ArrayList<Block>(); // // public Request(String command) { // String[] tokens = command.split("\\s+"); // readTokens(tokens); // } // // public Request(Object... tokens) { // if (tokens.length == 0) { // throw new SsdbException("command is empty"); // } // // readTokens(tokens); // } // // public Server getForceServer() { // return forceServer; // } // // public void setForceServer(Server forceServer) { // this.forceServer = forceServer; // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // private void readTokens(Object[] tokens) { // // // 一个命令至少有 command 和 key 两个部分,然后可能有后面其他参数 // if (isKeyRequired(tokens) && tokens.length < 2) { // throw new SsdbException("Command '" + tokens[0] + "' has no parameters or not supported."); // } // // this.header = new Block(tokens[0].toString().getBytes(charset)); // // for (int i = 1; i < tokens.length; i++) { // Object token = tokens[i]; // Block block; // if (token instanceof byte[]) { // block = new Block((byte[]) token); // } else { // block = new Block(token.toString().getBytes(charset)); // } // this.blocks.add(block); // } // } // // private boolean isKeyRequired(Object[] tokens) { // if (tokens.length == 0) { // return true; // } // // return !(tokens[0].equals("dbsize") || tokens[0].equals("info")); // } // // public Block getHeader() { // return header; // } // // public List<Block> getBlocks() { // return blocks; // } // // public String getKey() { // return blocks.isEmpty() ? null : blocks.get(0).toString(); // 第一个参数一定是 key,用来决定其放在哪台服务器上 // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(header.toString()).append(' '); // // for (Block block : blocks) { // sb.append(block.toString()).append(' '); // } // // sb.deleteCharAt(sb.length() - 1); // return sb.toString(); // } // // public byte[] toBytes() { // byte[][] byteArrays = new byte[blocks.size() + 2][]; // // byteArrays[0] = header.toBytes(); // for (int i = 0; i < blocks.size(); i++) { // byteArrays[i + 1] = blocks.get(i).toBytes(); // } // byteArrays[byteArrays.length - 1] = new byte[]{'\n'}; // // return Bytes.concat(byteArrays); // } // }
import com.hyd.ssdb.protocol.Request; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Random;
package com.hyd.ssdb; /** * (description) * created at 15-12-3 * * @author Yiding */ public class SsdbClientMultiThreadTest { private SsdbClient ssdbClient; @Before public void init() { this.ssdbClient = new SsdbClient("192.168.1.180", 8888); } @After public void finish() { this.ssdbClient.close(); } @Test public void testMultiThread() throws Exception { for (int i = 0; i < 50; i++) { new Thread(new SsdbTask(ssdbClient)).start(); } Thread.sleep(10000); } //////////////////////////////////////////////////////////////// private static class SsdbTask implements Runnable { private final SsdbClient ssdbClient; private Random random; public SsdbTask(SsdbClient ssdbClient) { this.ssdbClient = ssdbClient; random = new Random(); } @Override public void run() { long start = System.currentTimeMillis(); long end = start + 4000; while (System.currentTimeMillis() < end) {
// Path: src/main/java/com/hyd/ssdb/protocol/Request.java // public class Request { // // private Charset charset = AbstractClient.DEFAULT_CHARSET; // // private Block header; // // private Server forceServer; // 强制指定请求的发送地址 // // private final List<Block> blocks = new ArrayList<Block>(); // // public Request(String command) { // String[] tokens = command.split("\\s+"); // readTokens(tokens); // } // // public Request(Object... tokens) { // if (tokens.length == 0) { // throw new SsdbException("command is empty"); // } // // readTokens(tokens); // } // // public Server getForceServer() { // return forceServer; // } // // public void setForceServer(Server forceServer) { // this.forceServer = forceServer; // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // private void readTokens(Object[] tokens) { // // // 一个命令至少有 command 和 key 两个部分,然后可能有后面其他参数 // if (isKeyRequired(tokens) && tokens.length < 2) { // throw new SsdbException("Command '" + tokens[0] + "' has no parameters or not supported."); // } // // this.header = new Block(tokens[0].toString().getBytes(charset)); // // for (int i = 1; i < tokens.length; i++) { // Object token = tokens[i]; // Block block; // if (token instanceof byte[]) { // block = new Block((byte[]) token); // } else { // block = new Block(token.toString().getBytes(charset)); // } // this.blocks.add(block); // } // } // // private boolean isKeyRequired(Object[] tokens) { // if (tokens.length == 0) { // return true; // } // // return !(tokens[0].equals("dbsize") || tokens[0].equals("info")); // } // // public Block getHeader() { // return header; // } // // public List<Block> getBlocks() { // return blocks; // } // // public String getKey() { // return blocks.isEmpty() ? null : blocks.get(0).toString(); // 第一个参数一定是 key,用来决定其放在哪台服务器上 // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(header.toString()).append(' '); // // for (Block block : blocks) { // sb.append(block.toString()).append(' '); // } // // sb.deleteCharAt(sb.length() - 1); // return sb.toString(); // } // // public byte[] toBytes() { // byte[][] byteArrays = new byte[blocks.size() + 2][]; // // byteArrays[0] = header.toBytes(); // for (int i = 0; i < blocks.size(); i++) { // byteArrays[i + 1] = blocks.get(i).toBytes(); // } // byteArrays[byteArrays.length - 1] = new byte[]{'\n'}; // // return Bytes.concat(byteArrays); // } // } // Path: src/test/java/com/hyd/ssdb/SsdbClientMultiThreadTest.java import com.hyd.ssdb.protocol.Request; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Random; package com.hyd.ssdb; /** * (description) * created at 15-12-3 * * @author Yiding */ public class SsdbClientMultiThreadTest { private SsdbClient ssdbClient; @Before public void init() { this.ssdbClient = new SsdbClient("192.168.1.180", 8888); } @After public void finish() { this.ssdbClient.close(); } @Test public void testMultiThread() throws Exception { for (int i = 0; i < 50; i++) { new Thread(new SsdbTask(ssdbClient)).start(); } Thread.sleep(10000); } //////////////////////////////////////////////////////////////// private static class SsdbTask implements Runnable { private final SsdbClient ssdbClient; private Random random; public SsdbTask(SsdbClient ssdbClient) { this.ssdbClient = ssdbClient; random = new Random(); } @Override public void run() { long start = System.currentTimeMillis(); long end = start + 4000; while (System.currentTimeMillis() < end) {
ssdbClient.sendRequest(new Request(
yiding-he/hydrogen-ssdb
src/test/java/com/hyd/ssdb/KryoSerializationTest.java
// Path: src/main/java/com/hyd/ssdb/util/Bytes.java // public class Bytes { // // private static final String[] HEX_ARRAY = { // "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", // "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", // "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", // "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", // "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", // "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", // "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", // "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", // "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", // "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", // "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", // "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", // "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", // "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", // "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", // "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"}; // // private Bytes() { // } // // /** // * 组合多个 byte[] 数组 // * // * @param byteArrays 要组合的数组 // * // * @return 组合的结果 // */ // public static byte[] concat(byte[]... byteArrays) { // int totalLength = 0; // for (byte[] byteArray : byteArrays) { // totalLength += byteArray.length; // } // // byte[] result = new byte[totalLength]; // int counter = 0; // for (byte[] byteArray : byteArrays) { // System.arraycopy(byteArray, 0, result, counter, byteArray.length); // counter += byteArray.length; // } // // return result; // } // // /** // * 字节串生成16进制字符串(最笨但最快的办法) // * // * @param bytes 要转换的字节串 // * // * @return 转换后的字符串 // */ // public static String toString(byte[] bytes) { // StringBuilder sb = new StringBuilder(bytes.length * 2); // for (byte b : bytes) { // sb.append(HEX_ARRAY[0xFF & b]); // } // return sb.toString(); // } // // }
import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.ByteBufferOutput; import com.hyd.ssdb.util.Bytes; import org.junit.Assert; import org.junit.Test; import java.util.Date;
public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getRegistrationTime() { return registrationTime; } public void setRegistrationTime(Date registrationTime) { this.registrationTime = registrationTime; } } @Test public void testSerialization() throws Exception { User user = new User(1, "admin", new Date()); Kryo kryo = new Kryo(); ByteBufferOutput output = new ByteBufferOutput(10240); kryo.writeObject(output, user); byte[] bytes = output.toBytes();
// Path: src/main/java/com/hyd/ssdb/util/Bytes.java // public class Bytes { // // private static final String[] HEX_ARRAY = { // "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", // "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", // "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", // "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", // "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", // "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", // "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", // "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", // "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", // "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", // "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", // "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", // "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", // "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", // "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", // "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"}; // // private Bytes() { // } // // /** // * 组合多个 byte[] 数组 // * // * @param byteArrays 要组合的数组 // * // * @return 组合的结果 // */ // public static byte[] concat(byte[]... byteArrays) { // int totalLength = 0; // for (byte[] byteArray : byteArrays) { // totalLength += byteArray.length; // } // // byte[] result = new byte[totalLength]; // int counter = 0; // for (byte[] byteArray : byteArrays) { // System.arraycopy(byteArray, 0, result, counter, byteArray.length); // counter += byteArray.length; // } // // return result; // } // // /** // * 字节串生成16进制字符串(最笨但最快的办法) // * // * @param bytes 要转换的字节串 // * // * @return 转换后的字符串 // */ // public static String toString(byte[] bytes) { // StringBuilder sb = new StringBuilder(bytes.length * 2); // for (byte b : bytes) { // sb.append(HEX_ARRAY[0xFF & b]); // } // return sb.toString(); // } // // } // Path: src/test/java/com/hyd/ssdb/KryoSerializationTest.java import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.ByteBufferOutput; import com.hyd.ssdb.util.Bytes; import org.junit.Assert; import org.junit.Test; import java.util.Date; public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getRegistrationTime() { return registrationTime; } public void setRegistrationTime(Date registrationTime) { this.registrationTime = registrationTime; } } @Test public void testSerialization() throws Exception { User user = new User(1, "admin", new Date()); Kryo kryo = new Kryo(); ByteBufferOutput output = new ByteBufferOutput(10240); kryo.writeObject(output, user); byte[] bytes = output.toBytes();
System.out.println("Saved bytes: " + Bytes.toString(bytes));
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/conf/Sharding.java
// Path: src/main/java/com/hyd/ssdb/SsdbClientException.java // public class SsdbClientException extends SsdbException { // // public SsdbClientException() { // } // // public SsdbClientException(String message) { // super(message); // } // // public SsdbClientException(String message, Throwable cause) { // super(message, cause); // } // // public SsdbClientException(Throwable cause) { // super(cause); // } // }
import com.hyd.ssdb.SsdbClientException; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package com.hyd.ssdb.conf; /** * 根据服务器的拓扑结构,决定一个请求应该被发送到哪台服务器 * <p> * created at 15-12-3 * * @author Yiding */ public abstract class Sharding { protected List<Cluster> clusters; /** * 构造方法 * * @param cluster 集群配置,整个负载均衡当中只会有一个集群 */ public Sharding(Cluster cluster) { this(Collections.singletonList(cluster)); } /** * 构造方法 * * @param clusters 集群配置。注意本方法将会使用 clusters 的拷贝,因此调用本方法之后再操作 * clusters(清空或增减元素),不会对 Sharding 有任何影响。 */ public Sharding(List<Cluster> clusters) { // 清掉可能的 null 元素 clusters.removeAll(Collections.singleton((Cluster) null)); if (clusters.isEmpty()) {
// Path: src/main/java/com/hyd/ssdb/SsdbClientException.java // public class SsdbClientException extends SsdbException { // // public SsdbClientException() { // } // // public SsdbClientException(String message) { // super(message); // } // // public SsdbClientException(String message, Throwable cause) { // super(message, cause); // } // // public SsdbClientException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/hyd/ssdb/conf/Sharding.java import com.hyd.ssdb.SsdbClientException; import java.util.ArrayList; import java.util.Collections; import java.util.List; package com.hyd.ssdb.conf; /** * 根据服务器的拓扑结构,决定一个请求应该被发送到哪台服务器 * <p> * created at 15-12-3 * * @author Yiding */ public abstract class Sharding { protected List<Cluster> clusters; /** * 构造方法 * * @param cluster 集群配置,整个负载均衡当中只会有一个集群 */ public Sharding(Cluster cluster) { this(Collections.singletonList(cluster)); } /** * 构造方法 * * @param clusters 集群配置。注意本方法将会使用 clusters 的拷贝,因此调用本方法之后再操作 * clusters(清空或增减元素),不会对 Sharding 有任何影响。 */ public Sharding(List<Cluster> clusters) { // 清掉可能的 null 元素 clusters.removeAll(Collections.singleton((Cluster) null)); if (clusters.isEmpty()) {
throw new SsdbClientException("clusters is empty");
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/protocol/Response.java
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // }
import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.util.*;
return null; } return this.body.isEmpty() ? 0 : Integer.parseInt(this.body.get(0).toString()); } public int getIntResult(int defaultValue) { Integer result = getIntResult(); return result == null ? defaultValue : result; } public Long getLongResult() { if (this.head.toString().equals("not_found")) { return null; } return this.body.isEmpty() ? 0 : Long.parseLong(this.body.get(0).toString()); } public long getLongResult(long defaultValue) { Long result = getLongResult(); return result == null ? defaultValue : result; } public List<String> getBlocks() { ArrayList<String> blocks = new ArrayList<>(); for (Block block : body) { blocks.add(block.toString(charset)); } return blocks; }
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // } // Path: src/main/java/com/hyd/ssdb/protocol/Response.java import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.util.*; return null; } return this.body.isEmpty() ? 0 : Integer.parseInt(this.body.get(0).toString()); } public int getIntResult(int defaultValue) { Integer result = getIntResult(); return result == null ? defaultValue : result; } public Long getLongResult() { if (this.head.toString().equals("not_found")) { return null; } return this.body.isEmpty() ? 0 : Long.parseLong(this.body.get(0).toString()); } public long getLongResult(long defaultValue) { Long result = getLongResult(); return result == null ? defaultValue : result; } public List<String> getBlocks() { ArrayList<String> blocks = new ArrayList<>(); for (Block block : body) { blocks.add(block.toString(charset)); } return blocks; }
public List<KeyValue> getKeyValues() {
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/protocol/Response.java
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // }
import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.util.*;
return null; } return this.body.isEmpty() ? 0 : Long.parseLong(this.body.get(0).toString()); } public long getLongResult(long defaultValue) { Long result = getLongResult(); return result == null ? defaultValue : result; } public List<String> getBlocks() { ArrayList<String> blocks = new ArrayList<>(); for (Block block : body) { blocks.add(block.toString(charset)); } return blocks; } public List<KeyValue> getKeyValues() { List<KeyValue> keyValues = new ArrayList<>(); for (int i = 0; i + 1 < body.size(); i += 2) { keyValues.add(new KeyValue( body.get(i).getData(), body.get(i + 1).getData(), charset )); } return keyValues; }
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // } // Path: src/main/java/com/hyd/ssdb/protocol/Response.java import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.util.*; return null; } return this.body.isEmpty() ? 0 : Long.parseLong(this.body.get(0).toString()); } public long getLongResult(long defaultValue) { Long result = getLongResult(); return result == null ? defaultValue : result; } public List<String> getBlocks() { ArrayList<String> blocks = new ArrayList<>(); for (Block block : body) { blocks.add(block.toString(charset)); } return blocks; } public List<KeyValue> getKeyValues() { List<KeyValue> keyValues = new ArrayList<>(); for (int i = 0; i + 1 < body.size(); i += 2) { keyValues.add(new KeyValue( body.get(i).getData(), body.get(i + 1).getData(), charset )); } return keyValues; }
public List<IdScore> getIdScores() {
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/conn/ConnectionPoolManager.java
// Path: src/main/java/com/hyd/ssdb/protocol/Request.java // public class Request { // // private Charset charset = AbstractClient.DEFAULT_CHARSET; // // private Block header; // // private Server forceServer; // 强制指定请求的发送地址 // // private final List<Block> blocks = new ArrayList<Block>(); // // public Request(String command) { // String[] tokens = command.split("\\s+"); // readTokens(tokens); // } // // public Request(Object... tokens) { // if (tokens.length == 0) { // throw new SsdbException("command is empty"); // } // // readTokens(tokens); // } // // public Server getForceServer() { // return forceServer; // } // // public void setForceServer(Server forceServer) { // this.forceServer = forceServer; // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // private void readTokens(Object[] tokens) { // // // 一个命令至少有 command 和 key 两个部分,然后可能有后面其他参数 // if (isKeyRequired(tokens) && tokens.length < 2) { // throw new SsdbException("Command '" + tokens[0] + "' has no parameters or not supported."); // } // // this.header = new Block(tokens[0].toString().getBytes(charset)); // // for (int i = 1; i < tokens.length; i++) { // Object token = tokens[i]; // Block block; // if (token instanceof byte[]) { // block = new Block((byte[]) token); // } else { // block = new Block(token.toString().getBytes(charset)); // } // this.blocks.add(block); // } // } // // private boolean isKeyRequired(Object[] tokens) { // if (tokens.length == 0) { // return true; // } // // return !(tokens[0].equals("dbsize") || tokens[0].equals("info")); // } // // public Block getHeader() { // return header; // } // // public List<Block> getBlocks() { // return blocks; // } // // public String getKey() { // return blocks.isEmpty() ? null : blocks.get(0).toString(); // 第一个参数一定是 key,用来决定其放在哪台服务器上 // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(header.toString()).append(' '); // // for (Block block : blocks) { // sb.append(block.toString()).append(' '); // } // // sb.deleteCharAt(sb.length() - 1); // return sb.toString(); // } // // public byte[] toBytes() { // byte[][] byteArrays = new byte[blocks.size() + 2][]; // // byteArrays[0] = header.toBytes(); // for (int i = 0; i < blocks.size(); i++) { // byteArrays[i + 1] = blocks.get(i).toBytes(); // } // byteArrays[byteArrays.length - 1] = new byte[]{'\n'}; // // return Bytes.concat(byteArrays); // } // } // // Path: src/main/java/com/hyd/ssdb/protocol/WriteRequest.java // public class WriteRequest extends Request { // // public WriteRequest(String command) { // super(command); // } // // public WriteRequest(Object... tokens) { // super(tokens); // } // }
import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.protocol.Request; import com.hyd.ssdb.protocol.WriteRequest; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.hyd.ssdb.conn; /** * NetworkManager 有两个职责: * 1、管理网络的拓扑结构(通过 Sharding 类),决定请求发送到哪个 SSDB 服务器; * 2、当请求发送失败时,自动更新失效的服务器列表,并尝试重新发送请求到同一 * Cluster 的其他服务器,直到没有服务器可用,才抛出异常。 * * @author Yiding */ public class ConnectionPoolManager { private static final Logger LOG = LoggerFactory.getLogger(ConnectionPoolManager.class); private Sharding sharding; // 负载均衡拓扑结构 private Map<Server, ConnectionPool> connectionPoolMap = new ConcurrentHashMap<Server, ConnectionPool>(); public ConnectionPoolManager(Sharding sharding) { this.sharding = sharding; this.sharding.initClusters(); } public Sharding getSharding() { return sharding; }
// Path: src/main/java/com/hyd/ssdb/protocol/Request.java // public class Request { // // private Charset charset = AbstractClient.DEFAULT_CHARSET; // // private Block header; // // private Server forceServer; // 强制指定请求的发送地址 // // private final List<Block> blocks = new ArrayList<Block>(); // // public Request(String command) { // String[] tokens = command.split("\\s+"); // readTokens(tokens); // } // // public Request(Object... tokens) { // if (tokens.length == 0) { // throw new SsdbException("command is empty"); // } // // readTokens(tokens); // } // // public Server getForceServer() { // return forceServer; // } // // public void setForceServer(Server forceServer) { // this.forceServer = forceServer; // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // private void readTokens(Object[] tokens) { // // // 一个命令至少有 command 和 key 两个部分,然后可能有后面其他参数 // if (isKeyRequired(tokens) && tokens.length < 2) { // throw new SsdbException("Command '" + tokens[0] + "' has no parameters or not supported."); // } // // this.header = new Block(tokens[0].toString().getBytes(charset)); // // for (int i = 1; i < tokens.length; i++) { // Object token = tokens[i]; // Block block; // if (token instanceof byte[]) { // block = new Block((byte[]) token); // } else { // block = new Block(token.toString().getBytes(charset)); // } // this.blocks.add(block); // } // } // // private boolean isKeyRequired(Object[] tokens) { // if (tokens.length == 0) { // return true; // } // // return !(tokens[0].equals("dbsize") || tokens[0].equals("info")); // } // // public Block getHeader() { // return header; // } // // public List<Block> getBlocks() { // return blocks; // } // // public String getKey() { // return blocks.isEmpty() ? null : blocks.get(0).toString(); // 第一个参数一定是 key,用来决定其放在哪台服务器上 // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(header.toString()).append(' '); // // for (Block block : blocks) { // sb.append(block.toString()).append(' '); // } // // sb.deleteCharAt(sb.length() - 1); // return sb.toString(); // } // // public byte[] toBytes() { // byte[][] byteArrays = new byte[blocks.size() + 2][]; // // byteArrays[0] = header.toBytes(); // for (int i = 0; i < blocks.size(); i++) { // byteArrays[i + 1] = blocks.get(i).toBytes(); // } // byteArrays[byteArrays.length - 1] = new byte[]{'\n'}; // // return Bytes.concat(byteArrays); // } // } // // Path: src/main/java/com/hyd/ssdb/protocol/WriteRequest.java // public class WriteRequest extends Request { // // public WriteRequest(String command) { // super(command); // } // // public WriteRequest(Object... tokens) { // super(tokens); // } // } // Path: src/main/java/com/hyd/ssdb/conn/ConnectionPoolManager.java import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.protocol.Request; import com.hyd.ssdb.protocol.WriteRequest; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.hyd.ssdb.conn; /** * NetworkManager 有两个职责: * 1、管理网络的拓扑结构(通过 Sharding 类),决定请求发送到哪个 SSDB 服务器; * 2、当请求发送失败时,自动更新失效的服务器列表,并尝试重新发送请求到同一 * Cluster 的其他服务器,直到没有服务器可用,才抛出异常。 * * @author Yiding */ public class ConnectionPoolManager { private static final Logger LOG = LoggerFactory.getLogger(ConnectionPoolManager.class); private Sharding sharding; // 负载均衡拓扑结构 private Map<Server, ConnectionPool> connectionPoolMap = new ConcurrentHashMap<Server, ConnectionPool>(); public ConnectionPoolManager(Sharding sharding) { this.sharding = sharding; this.sharding.initClusters(); } public Sharding getSharding() { return sharding; }
public List<PoolAndConnection> getAllConnections(Request request) {
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/conn/ConnectionPoolManager.java
// Path: src/main/java/com/hyd/ssdb/protocol/Request.java // public class Request { // // private Charset charset = AbstractClient.DEFAULT_CHARSET; // // private Block header; // // private Server forceServer; // 强制指定请求的发送地址 // // private final List<Block> blocks = new ArrayList<Block>(); // // public Request(String command) { // String[] tokens = command.split("\\s+"); // readTokens(tokens); // } // // public Request(Object... tokens) { // if (tokens.length == 0) { // throw new SsdbException("command is empty"); // } // // readTokens(tokens); // } // // public Server getForceServer() { // return forceServer; // } // // public void setForceServer(Server forceServer) { // this.forceServer = forceServer; // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // private void readTokens(Object[] tokens) { // // // 一个命令至少有 command 和 key 两个部分,然后可能有后面其他参数 // if (isKeyRequired(tokens) && tokens.length < 2) { // throw new SsdbException("Command '" + tokens[0] + "' has no parameters or not supported."); // } // // this.header = new Block(tokens[0].toString().getBytes(charset)); // // for (int i = 1; i < tokens.length; i++) { // Object token = tokens[i]; // Block block; // if (token instanceof byte[]) { // block = new Block((byte[]) token); // } else { // block = new Block(token.toString().getBytes(charset)); // } // this.blocks.add(block); // } // } // // private boolean isKeyRequired(Object[] tokens) { // if (tokens.length == 0) { // return true; // } // // return !(tokens[0].equals("dbsize") || tokens[0].equals("info")); // } // // public Block getHeader() { // return header; // } // // public List<Block> getBlocks() { // return blocks; // } // // public String getKey() { // return blocks.isEmpty() ? null : blocks.get(0).toString(); // 第一个参数一定是 key,用来决定其放在哪台服务器上 // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(header.toString()).append(' '); // // for (Block block : blocks) { // sb.append(block.toString()).append(' '); // } // // sb.deleteCharAt(sb.length() - 1); // return sb.toString(); // } // // public byte[] toBytes() { // byte[][] byteArrays = new byte[blocks.size() + 2][]; // // byteArrays[0] = header.toBytes(); // for (int i = 0; i < blocks.size(); i++) { // byteArrays[i + 1] = blocks.get(i).toBytes(); // } // byteArrays[byteArrays.length - 1] = new byte[]{'\n'}; // // return Bytes.concat(byteArrays); // } // } // // Path: src/main/java/com/hyd/ssdb/protocol/WriteRequest.java // public class WriteRequest extends Request { // // public WriteRequest(String command) { // super(command); // } // // public WriteRequest(Object... tokens) { // super(tokens); // } // }
import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.protocol.Request; import com.hyd.ssdb.protocol.WriteRequest; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.hyd.ssdb.conn; /** * NetworkManager 有两个职责: * 1、管理网络的拓扑结构(通过 Sharding 类),决定请求发送到哪个 SSDB 服务器; * 2、当请求发送失败时,自动更新失效的服务器列表,并尝试重新发送请求到同一 * Cluster 的其他服务器,直到没有服务器可用,才抛出异常。 * * @author Yiding */ public class ConnectionPoolManager { private static final Logger LOG = LoggerFactory.getLogger(ConnectionPoolManager.class); private Sharding sharding; // 负载均衡拓扑结构 private Map<Server, ConnectionPool> connectionPoolMap = new ConcurrentHashMap<Server, ConnectionPool>(); public ConnectionPoolManager(Sharding sharding) { this.sharding = sharding; this.sharding.initClusters(); } public Sharding getSharding() { return sharding; } public List<PoolAndConnection> getAllConnections(Request request) {
// Path: src/main/java/com/hyd/ssdb/protocol/Request.java // public class Request { // // private Charset charset = AbstractClient.DEFAULT_CHARSET; // // private Block header; // // private Server forceServer; // 强制指定请求的发送地址 // // private final List<Block> blocks = new ArrayList<Block>(); // // public Request(String command) { // String[] tokens = command.split("\\s+"); // readTokens(tokens); // } // // public Request(Object... tokens) { // if (tokens.length == 0) { // throw new SsdbException("command is empty"); // } // // readTokens(tokens); // } // // public Server getForceServer() { // return forceServer; // } // // public void setForceServer(Server forceServer) { // this.forceServer = forceServer; // } // // public Charset getCharset() { // return charset; // } // // public void setCharset(Charset charset) { // this.charset = charset; // } // // private void readTokens(Object[] tokens) { // // // 一个命令至少有 command 和 key 两个部分,然后可能有后面其他参数 // if (isKeyRequired(tokens) && tokens.length < 2) { // throw new SsdbException("Command '" + tokens[0] + "' has no parameters or not supported."); // } // // this.header = new Block(tokens[0].toString().getBytes(charset)); // // for (int i = 1; i < tokens.length; i++) { // Object token = tokens[i]; // Block block; // if (token instanceof byte[]) { // block = new Block((byte[]) token); // } else { // block = new Block(token.toString().getBytes(charset)); // } // this.blocks.add(block); // } // } // // private boolean isKeyRequired(Object[] tokens) { // if (tokens.length == 0) { // return true; // } // // return !(tokens[0].equals("dbsize") || tokens[0].equals("info")); // } // // public Block getHeader() { // return header; // } // // public List<Block> getBlocks() { // return blocks; // } // // public String getKey() { // return blocks.isEmpty() ? null : blocks.get(0).toString(); // 第一个参数一定是 key,用来决定其放在哪台服务器上 // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(header.toString()).append(' '); // // for (Block block : blocks) { // sb.append(block.toString()).append(' '); // } // // sb.deleteCharAt(sb.length() - 1); // return sb.toString(); // } // // public byte[] toBytes() { // byte[][] byteArrays = new byte[blocks.size() + 2][]; // // byteArrays[0] = header.toBytes(); // for (int i = 0; i < blocks.size(); i++) { // byteArrays[i + 1] = blocks.get(i).toBytes(); // } // byteArrays[byteArrays.length - 1] = new byte[]{'\n'}; // // return Bytes.concat(byteArrays); // } // } // // Path: src/main/java/com/hyd/ssdb/protocol/WriteRequest.java // public class WriteRequest extends Request { // // public WriteRequest(String command) { // super(command); // } // // public WriteRequest(Object... tokens) { // super(tokens); // } // } // Path: src/main/java/com/hyd/ssdb/conn/ConnectionPoolManager.java import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.protocol.Request; import com.hyd.ssdb.protocol.WriteRequest; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.hyd.ssdb.conn; /** * NetworkManager 有两个职责: * 1、管理网络的拓扑结构(通过 Sharding 类),决定请求发送到哪个 SSDB 服务器; * 2、当请求发送失败时,自动更新失效的服务器列表,并尝试重新发送请求到同一 * Cluster 的其他服务器,直到没有服务器可用,才抛出异常。 * * @author Yiding */ public class ConnectionPoolManager { private static final Logger LOG = LoggerFactory.getLogger(ConnectionPoolManager.class); private Sharding sharding; // 负载均衡拓扑结构 private Map<Server, ConnectionPool> connectionPoolMap = new ConcurrentHashMap<Server, ConnectionPool>(); public ConnectionPoolManager(Sharding sharding) { this.sharding = sharding; this.sharding.initClusters(); } public Sharding getSharding() { return sharding; } public List<PoolAndConnection> getAllConnections(Request request) {
boolean write = request instanceof WriteRequest;
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/conn/ConnectionFactory.java
// Path: src/main/java/com/hyd/ssdb/conf/Server.java // public class Server { // // private String host; // 服务器地址 // // private int port; // 服务器端口 // // private String pass; // 服务器校验密码(可选) // // private boolean master = true; // 是否是主服务器。 // // private GenericObjectPoolConfig<Connection> poolConfig = createDefaultPoolConfig(); // 连接池配置参数 // // private SocketConfig socketConfig = new SocketConfig(); // 网络配置参数 // // public Server() { // } // // public Server(String host, int port) { // this.host = host; // this.port = port; // } // // public Server(String host, int port, boolean master) { // this.host = host; // this.port = port; // this.master = master; // } // // public Server(String host, int port, String pass) { // this.host = host; // this.port = port; // this.pass = pass; // } // // public Server(String host, int port, int timeoutSeconds) { // this.host = host; // this.port = port; // this.socketConfig.setSoTimeout(timeoutSeconds * 1000); // } // // public Server(String host, int port, SocketConfig socketConfig) { // this.host = host; // this.port = port; // this.socketConfig = socketConfig; // } // // public Server(String host, int port, int timeoutSeconds, int bufferSize) { // this.host = host; // this.port = port; // this.socketConfig.setSoTimeout(timeoutSeconds * 1000); // this.socketConfig.setSoBufferSize(bufferSize); // } // // public Server(String host, int port, String pass, boolean master) { // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // } // // public Server(String host, int port, String pass, boolean master, int timeoutSeconds, int poolMaxTotal) { // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // this.socketConfig.setSoTimeout(timeoutSeconds * 1000); // this.poolConfig.setMaxTotal(poolMaxTotal); // } // // public Server(String host, int port, String pass, boolean master, SocketConfig socketConfig) { // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // // if (socketConfig != null) { // this.socketConfig = socketConfig; // } // } // // public Server(String host, int port, String pass, boolean master, // SocketConfig socketConfig, GenericObjectPoolConfig<Connection> poolConfig) { // // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // // if (socketConfig != null) { // this.socketConfig = socketConfig; // } // // if (poolConfig != null) { // this.poolConfig = poolConfig; // } // } // // // private GenericObjectPoolConfig<Connection> createDefaultPoolConfig() { // GenericObjectPoolConfig<Connection> config = new GenericObjectPoolConfig<>(); // config.setMaxIdle(1); // return config; // } // // public GenericObjectPoolConfig<Connection> getPoolConfig() { // return poolConfig; // } // // public void setPoolConfig(GenericObjectPoolConfig<Connection> poolConfig) { // this.poolConfig = poolConfig; // } // // public SocketConfig getSocketConfig() { // return socketConfig; // } // // public void setSocketConfig(SocketConfig socketConfig) { // this.socketConfig = socketConfig; // } // // public boolean isMaster() { // return master; // } // // public void setMaster(boolean master) { // this.master = master; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getPass() { // return pass; // } // // public void setPass(String pass) { // this.pass = pass; // } // // @SuppressWarnings("SimplifiableIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Server)) return false; // // Server server = (Server) o; // // if (getPort() != server.getPort()) return false; // return getHost().equals(server.getHost()); // // } // // @Override // public int hashCode() { // int result = getHost().hashCode(); // result = 31 * result + getPort(); // return result; // } // // @Override // public String toString() { // return "Server{" + // "host='" + host + '\'' + // ", port=" + port + // ", master=" + master + // '}'; // } // }
import com.hyd.ssdb.conf.Server; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.hyd.ssdb.conn; /** * 创建 Connection 对象并检查其状态的工厂类。 * 一个 ConnectionFactory 对象只针对一个 SSDB 服务器 * * @author Yiding */ public class ConnectionFactory implements PooledObjectFactory<Connection> { static final Logger LOG = LoggerFactory.getLogger(ConnectionFactory.class);
// Path: src/main/java/com/hyd/ssdb/conf/Server.java // public class Server { // // private String host; // 服务器地址 // // private int port; // 服务器端口 // // private String pass; // 服务器校验密码(可选) // // private boolean master = true; // 是否是主服务器。 // // private GenericObjectPoolConfig<Connection> poolConfig = createDefaultPoolConfig(); // 连接池配置参数 // // private SocketConfig socketConfig = new SocketConfig(); // 网络配置参数 // // public Server() { // } // // public Server(String host, int port) { // this.host = host; // this.port = port; // } // // public Server(String host, int port, boolean master) { // this.host = host; // this.port = port; // this.master = master; // } // // public Server(String host, int port, String pass) { // this.host = host; // this.port = port; // this.pass = pass; // } // // public Server(String host, int port, int timeoutSeconds) { // this.host = host; // this.port = port; // this.socketConfig.setSoTimeout(timeoutSeconds * 1000); // } // // public Server(String host, int port, SocketConfig socketConfig) { // this.host = host; // this.port = port; // this.socketConfig = socketConfig; // } // // public Server(String host, int port, int timeoutSeconds, int bufferSize) { // this.host = host; // this.port = port; // this.socketConfig.setSoTimeout(timeoutSeconds * 1000); // this.socketConfig.setSoBufferSize(bufferSize); // } // // public Server(String host, int port, String pass, boolean master) { // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // } // // public Server(String host, int port, String pass, boolean master, int timeoutSeconds, int poolMaxTotal) { // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // this.socketConfig.setSoTimeout(timeoutSeconds * 1000); // this.poolConfig.setMaxTotal(poolMaxTotal); // } // // public Server(String host, int port, String pass, boolean master, SocketConfig socketConfig) { // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // // if (socketConfig != null) { // this.socketConfig = socketConfig; // } // } // // public Server(String host, int port, String pass, boolean master, // SocketConfig socketConfig, GenericObjectPoolConfig<Connection> poolConfig) { // // this.host = host; // this.port = port; // this.pass = pass; // this.master = master; // // if (socketConfig != null) { // this.socketConfig = socketConfig; // } // // if (poolConfig != null) { // this.poolConfig = poolConfig; // } // } // // // private GenericObjectPoolConfig<Connection> createDefaultPoolConfig() { // GenericObjectPoolConfig<Connection> config = new GenericObjectPoolConfig<>(); // config.setMaxIdle(1); // return config; // } // // public GenericObjectPoolConfig<Connection> getPoolConfig() { // return poolConfig; // } // // public void setPoolConfig(GenericObjectPoolConfig<Connection> poolConfig) { // this.poolConfig = poolConfig; // } // // public SocketConfig getSocketConfig() { // return socketConfig; // } // // public void setSocketConfig(SocketConfig socketConfig) { // this.socketConfig = socketConfig; // } // // public boolean isMaster() { // return master; // } // // public void setMaster(boolean master) { // this.master = master; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getPass() { // return pass; // } // // public void setPass(String pass) { // this.pass = pass; // } // // @SuppressWarnings("SimplifiableIfStatement") // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Server)) return false; // // Server server = (Server) o; // // if (getPort() != server.getPort()) return false; // return getHost().equals(server.getHost()); // // } // // @Override // public int hashCode() { // int result = getHost().hashCode(); // result = 31 * result + getPort(); // return result; // } // // @Override // public String toString() { // return "Server{" + // "host='" + host + '\'' + // ", port=" + port + // ", master=" + master + // '}'; // } // } // Path: src/main/java/com/hyd/ssdb/conn/ConnectionFactory.java import com.hyd.ssdb.conf.Server; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.hyd.ssdb.conn; /** * 创建 Connection 对象并检查其状态的工厂类。 * 一个 ConnectionFactory 对象只针对一个 SSDB 服务器 * * @author Yiding */ public class ConnectionFactory implements PooledObjectFactory<Connection> { static final Logger LOG = LoggerFactory.getLogger(ConnectionFactory.class);
private Server server;
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/AbstractClient.java
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // }
import com.hyd.ssdb.conf.*; import com.hyd.ssdb.conn.*; import com.hyd.ssdb.protocol.*; import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import org.slf4j.LoggerFactory;
protected String[] prependCommand(String token, String[] parameters) { String[] command = new String[parameters.length + 1]; command[0] = token; System.arraycopy(parameters, 0, command, 1, parameters.length); return command; } /** * 将两个 token 插入到 parameters 的第一位,生成一个新的数组 * * @param token1 要插入的内容 * @param token2 要插入的内容 * @param parameters 参数 * * @return 新生成的数组 */ protected String[] prependCommand(String token1, String token2, String[] parameters) { String[] command = new String[parameters.length + 2]; command[0] = token1; command[1] = token2; System.arraycopy(parameters, 0, command, 2, parameters.length); return command; } // 将 token1,token2 和 parameters 组合成一个字符串数组 protected String[] prependCommand(String token1, String token2, List<String> parameters) { return prependCommand(token1, token2, parameters.toArray(new String[0])); } // 将 token1,token2 和 keyValues 组合成一个字符串数组
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // } // Path: src/main/java/com/hyd/ssdb/AbstractClient.java import com.hyd.ssdb.conf.*; import com.hyd.ssdb.conn.*; import com.hyd.ssdb.protocol.*; import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import org.slf4j.LoggerFactory; protected String[] prependCommand(String token, String[] parameters) { String[] command = new String[parameters.length + 1]; command[0] = token; System.arraycopy(parameters, 0, command, 1, parameters.length); return command; } /** * 将两个 token 插入到 parameters 的第一位,生成一个新的数组 * * @param token1 要插入的内容 * @param token2 要插入的内容 * @param parameters 参数 * * @return 新生成的数组 */ protected String[] prependCommand(String token1, String token2, String[] parameters) { String[] command = new String[parameters.length + 2]; command[0] = token1; command[1] = token2; System.arraycopy(parameters, 0, command, 2, parameters.length); return command; } // 将 token1,token2 和 parameters 组合成一个字符串数组 protected String[] prependCommand(String token1, String token2, List<String> parameters) { return prependCommand(token1, token2, parameters.toArray(new String[0])); } // 将 token1,token2 和 keyValues 组合成一个字符串数组
protected String[] prependCommandKeyValue(String token1, String token2, List<KeyValue> keyValues) {
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/AbstractClient.java
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // }
import com.hyd.ssdb.conf.*; import com.hyd.ssdb.conn.*; import com.hyd.ssdb.protocol.*; import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import org.slf4j.LoggerFactory;
* @return 新生成的数组 */ protected String[] prependCommand(String token1, String token2, String[] parameters) { String[] command = new String[parameters.length + 2]; command[0] = token1; command[1] = token2; System.arraycopy(parameters, 0, command, 2, parameters.length); return command; } // 将 token1,token2 和 parameters 组合成一个字符串数组 protected String[] prependCommand(String token1, String token2, List<String> parameters) { return prependCommand(token1, token2, parameters.toArray(new String[0])); } // 将 token1,token2 和 keyValues 组合成一个字符串数组 protected String[] prependCommandKeyValue(String token1, String token2, List<KeyValue> keyValues) { String[] command = new String[keyValues.size() * 2 + 2]; command[0] = token1; command[1] = token2; for (int i = 0; i < keyValues.size(); i++) { KeyValue keyValue = keyValues.get(i); command[i * 2 + 2] = keyValue.getKeyString(); command[i * 2 + 3] = keyValue.getValueString(); } return command; } // 将 token1,token2 和 idScores 组合成一个字符串数组
// Path: src/main/java/com/hyd/ssdb/util/IdScore.java // public class IdScore { // // private String id; // // private long score; // // public IdScore() { // } // // public IdScore(String id, long score) { // this.id = id; // this.score = score; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public long getScore() { // return score; // } // // public void setScore(long score) { // this.score = score; // } // // @Override // public String toString() { // return "IdScore{" + // "id='" + id + '\'' + // ", score=" + score + // '}'; // } // } // // Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // } // Path: src/main/java/com/hyd/ssdb/AbstractClient.java import com.hyd.ssdb.conf.*; import com.hyd.ssdb.conn.*; import com.hyd.ssdb.protocol.*; import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import org.slf4j.LoggerFactory; * @return 新生成的数组 */ protected String[] prependCommand(String token1, String token2, String[] parameters) { String[] command = new String[parameters.length + 2]; command[0] = token1; command[1] = token2; System.arraycopy(parameters, 0, command, 2, parameters.length); return command; } // 将 token1,token2 和 parameters 组合成一个字符串数组 protected String[] prependCommand(String token1, String token2, List<String> parameters) { return prependCommand(token1, token2, parameters.toArray(new String[0])); } // 将 token1,token2 和 keyValues 组合成一个字符串数组 protected String[] prependCommandKeyValue(String token1, String token2, List<KeyValue> keyValues) { String[] command = new String[keyValues.size() * 2 + 2]; command[0] = token1; command[1] = token2; for (int i = 0; i < keyValues.size(); i++) { KeyValue keyValue = keyValues.get(i); command[i * 2 + 2] = keyValue.getKeyString(); command[i * 2 + 3] = keyValue.getValueString(); } return command; } // 将 token1,token2 和 idScores 组合成一个字符串数组
protected String[] prependCommandIdScore(String token1, String token2, List<IdScore> idScores) {
yiding-he/hydrogen-ssdb
src/test/java/com/hyd/ssdb/BytesTest.java
// Path: src/main/java/com/hyd/ssdb/util/Bytes.java // public class Bytes { // // private static final String[] HEX_ARRAY = { // "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", // "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", // "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", // "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", // "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", // "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", // "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", // "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", // "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", // "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", // "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", // "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", // "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", // "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", // "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", // "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"}; // // private Bytes() { // } // // /** // * 组合多个 byte[] 数组 // * // * @param byteArrays 要组合的数组 // * // * @return 组合的结果 // */ // public static byte[] concat(byte[]... byteArrays) { // int totalLength = 0; // for (byte[] byteArray : byteArrays) { // totalLength += byteArray.length; // } // // byte[] result = new byte[totalLength]; // int counter = 0; // for (byte[] byteArray : byteArrays) { // System.arraycopy(byteArray, 0, result, counter, byteArray.length); // counter += byteArray.length; // } // // return result; // } // // /** // * 字节串生成16进制字符串(最笨但最快的办法) // * // * @param bytes 要转换的字节串 // * // * @return 转换后的字符串 // */ // public static String toString(byte[] bytes) { // StringBuilder sb = new StringBuilder(bytes.length * 2); // for (byte b : bytes) { // sb.append(HEX_ARRAY[0xFF & b]); // } // return sb.toString(); // } // // }
import com.hyd.ssdb.util.Bytes; import org.junit.Test; import java.util.Arrays;
package com.hyd.ssdb; /** * (description) * created at 15-12-2 * * @author Yiding */ public class BytesTest { @Test public void testConcat() throws Exception { byte[] arr1 = {1, 2, 3}; byte[] arr2 = {4, 5, 6}; byte[] arr3 = {7, 8, 9};
// Path: src/main/java/com/hyd/ssdb/util/Bytes.java // public class Bytes { // // private static final String[] HEX_ARRAY = { // "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", // "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", // "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", // "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", // "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", // "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", // "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", // "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", // "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", // "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", // "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", // "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", // "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", // "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", // "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", // "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"}; // // private Bytes() { // } // // /** // * 组合多个 byte[] 数组 // * // * @param byteArrays 要组合的数组 // * // * @return 组合的结果 // */ // public static byte[] concat(byte[]... byteArrays) { // int totalLength = 0; // for (byte[] byteArray : byteArrays) { // totalLength += byteArray.length; // } // // byte[] result = new byte[totalLength]; // int counter = 0; // for (byte[] byteArray : byteArrays) { // System.arraycopy(byteArray, 0, result, counter, byteArray.length); // counter += byteArray.length; // } // // return result; // } // // /** // * 字节串生成16进制字符串(最笨但最快的办法) // * // * @param bytes 要转换的字节串 // * // * @return 转换后的字符串 // */ // public static String toString(byte[] bytes) { // StringBuilder sb = new StringBuilder(bytes.length * 2); // for (byte b : bytes) { // sb.append(HEX_ARRAY[0xFF & b]); // } // return sb.toString(); // } // // } // Path: src/test/java/com/hyd/ssdb/BytesTest.java import com.hyd.ssdb.util.Bytes; import org.junit.Test; import java.util.Arrays; package com.hyd.ssdb; /** * (description) * created at 15-12-2 * * @author Yiding */ public class BytesTest { @Test public void testConcat() throws Exception { byte[] arr1 = {1, 2, 3}; byte[] arr2 = {4, 5, 6}; byte[] arr3 = {7, 8, 9};
System.out.println(Arrays.toString(Bytes.concat(arr1, arr2, arr3)));
yiding-he/hydrogen-ssdb
src/test/java/com/hyd/ssdb/ClusterSsdbClientTest.java
// Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // }
import com.hyd.ssdb.util.KeyValue; import org.junit.Test; import java.util.Arrays; import static junit.framework.TestCase.*;
package com.hyd.ssdb; /** * (description) * created at 16/08/05 * * @author yiding_he */ public class ClusterSsdbClientTest extends ClusterBaseTest { @Test public void testMultiGetSet() throws Exception { ssdbClient.multiSet("key1", "value1", "key2", "value2", "key3", "value3"); assertEquals("value1", ssdbClient.get("key1")); assertEquals("value2", ssdbClient.get("key2")); assertEquals("value3", ssdbClient.get("key3")); } @Test public void testMultiGetSet2() throws Exception { ssdbClient.multiSet(Arrays.asList(
// Path: src/main/java/com/hyd/ssdb/util/KeyValue.java // public class KeyValue { // // private Charset charset; // // private byte[] key; // // private byte[] value; // // public KeyValue(byte[] key, byte[] value, Charset charset) { // this.key = key; // this.value = value; // this.charset = charset; // } // // public KeyValue(String key, byte[] value, Charset charset) { // this((charset == null? key.getBytes(): key.getBytes(charset)), value, charset); // } // // public KeyValue(String key, String value) { // this(key, value, AbstractClient.DEFAULT_CHARSET); // } // // public KeyValue(String key, String value, Charset charset) { // this(key.getBytes(charset), value.getBytes(charset), charset); // } // // public byte[] getKey() { // return key; // } // // public String getKeyString() { // return this.charset == null? new String(this.key) : new String(this.key, this.charset); // } // // public void setKey(byte[] key) { // this.key = key; // } // // public byte[] getValue() { // return value; // } // // public String getValueString() { // return new String(this.value, this.charset); // } // // public void setValue(byte[] value) { // this.value = value; // } // } // Path: src/test/java/com/hyd/ssdb/ClusterSsdbClientTest.java import com.hyd.ssdb.util.KeyValue; import org.junit.Test; import java.util.Arrays; import static junit.framework.TestCase.*; package com.hyd.ssdb; /** * (description) * created at 16/08/05 * * @author yiding_he */ public class ClusterSsdbClientTest extends ClusterBaseTest { @Test public void testMultiGetSet() throws Exception { ssdbClient.multiSet("key1", "value1", "key2", "value2", "key3", "value3"); assertEquals("value1", ssdbClient.get("key1")); assertEquals("value2", ssdbClient.get("key2")); assertEquals("value3", ssdbClient.get("key3")); } @Test public void testMultiGetSet2() throws Exception { ssdbClient.multiSet(Arrays.asList(
new KeyValue("key1", "value1"),
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/sharding/ConsistentHashSharding.java
// Path: src/main/java/com/hyd/ssdb/util/MD5.java // public class MD5 { // // /** // * 利用 md5 生成字符串的 hashCode // * // * @param str 要签名的字符串 // * // * @return 签名的 hash // */ // public static int md5Hash(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // byte[] bytes = digest.digest(str.getBytes("UTF-8")); // return b2i(bytes); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // // public static int b2i(byte[] b) { // int value = 0; // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (b[i] & 0x000000FF) << shift; // } // return value; // } // } // // Path: src/main/java/com/hyd/ssdb/util/Range.java // public class Range<T extends Number> { // // private T min; // // private T max; // // public Range(T min, T max) { // this.min = min; // this.max = max; // } // // public T getMin() { // return min; // } // // public void setMin(T min) { // this.min = min; // } // // public T getMax() { // return max; // } // // public void setMax(T max) { // this.max = max; // } // // public boolean contains(T value) { // if (value instanceof Integer) { // return (Integer) this.min <= (Integer) value && (Integer) value <= (Integer) this.max; // } else if (value instanceof Long) { // return (Long) this.min <= (Long) value && (Long) value <= (Long) this.max; // } else if (value instanceof Double) { // return (Double) this.min <= (Double) value && (Double) value <= (Double) this.max; // } else if (value instanceof Float) { // return (Float) this.min <= (Float) value && (Float) value <= (Float) this.max; // } else if (value instanceof Short) { // return (Short) this.min <= (Short) value && (Short) value <= (Short) this.max; // } else if (value instanceof Byte) { // return (Byte) this.min <= (Byte) value && (Byte) value <= (Byte) this.max; // } else { // throw new UnsupportedOperationException("Type '" + value.getClass() + "' not supported."); // } // } // // public Range<T> duplicate() { // return new Range<T>(min, max); // } // // @Override // public String toString() { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // }
import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.util.MD5; import com.hyd.ssdb.util.Range; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.hyd.ssdb.sharding; /** * 基于一致性哈希的分片策略。这是 hydrogen-ssdb 实现的缺省分片策略。 * <p></p> * ConsistentHashSharding 有一个属性叫做 {@link #spofStrategy},用于决定当出现单点故障时如何处理。 * <p></p> * created at 15-12-8 * * @author Yiding */ public class ConsistentHashSharding extends Sharding { private static final Logger LOG = LoggerFactory.getLogger(ConsistentHashSharding.class); /** * 单点故障处理策略,参考 {@link SPOFStrategy} */ private SPOFStrategy spofStrategy = SPOFStrategy.AutoExpandStrategy; public ConsistentHashSharding(Cluster cluster) { super(cluster); } ////////////////////////////////////////////////////////////// public ConsistentHashSharding(List<Cluster> clusters) { super(clusters); } public ConsistentHashSharding(Cluster... clusters) { super(Arrays.asList(clusters)); } public SPOFStrategy getSpofStrategy() { return spofStrategy; } public void setSpofStrategy(SPOFStrategy spofStrategy) { this.spofStrategy = spofStrategy; }
// Path: src/main/java/com/hyd/ssdb/util/MD5.java // public class MD5 { // // /** // * 利用 md5 生成字符串的 hashCode // * // * @param str 要签名的字符串 // * // * @return 签名的 hash // */ // public static int md5Hash(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // byte[] bytes = digest.digest(str.getBytes("UTF-8")); // return b2i(bytes); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // // public static int b2i(byte[] b) { // int value = 0; // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (b[i] & 0x000000FF) << shift; // } // return value; // } // } // // Path: src/main/java/com/hyd/ssdb/util/Range.java // public class Range<T extends Number> { // // private T min; // // private T max; // // public Range(T min, T max) { // this.min = min; // this.max = max; // } // // public T getMin() { // return min; // } // // public void setMin(T min) { // this.min = min; // } // // public T getMax() { // return max; // } // // public void setMax(T max) { // this.max = max; // } // // public boolean contains(T value) { // if (value instanceof Integer) { // return (Integer) this.min <= (Integer) value && (Integer) value <= (Integer) this.max; // } else if (value instanceof Long) { // return (Long) this.min <= (Long) value && (Long) value <= (Long) this.max; // } else if (value instanceof Double) { // return (Double) this.min <= (Double) value && (Double) value <= (Double) this.max; // } else if (value instanceof Float) { // return (Float) this.min <= (Float) value && (Float) value <= (Float) this.max; // } else if (value instanceof Short) { // return (Short) this.min <= (Short) value && (Short) value <= (Short) this.max; // } else if (value instanceof Byte) { // return (Byte) this.min <= (Byte) value && (Byte) value <= (Byte) this.max; // } else { // throw new UnsupportedOperationException("Type '" + value.getClass() + "' not supported."); // } // } // // public Range<T> duplicate() { // return new Range<T>(min, max); // } // // @Override // public String toString() { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // } // Path: src/main/java/com/hyd/ssdb/sharding/ConsistentHashSharding.java import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.util.MD5; import com.hyd.ssdb.util.Range; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.hyd.ssdb.sharding; /** * 基于一致性哈希的分片策略。这是 hydrogen-ssdb 实现的缺省分片策略。 * <p></p> * ConsistentHashSharding 有一个属性叫做 {@link #spofStrategy},用于决定当出现单点故障时如何处理。 * <p></p> * created at 15-12-8 * * @author Yiding */ public class ConsistentHashSharding extends Sharding { private static final Logger LOG = LoggerFactory.getLogger(ConsistentHashSharding.class); /** * 单点故障处理策略,参考 {@link SPOFStrategy} */ private SPOFStrategy spofStrategy = SPOFStrategy.AutoExpandStrategy; public ConsistentHashSharding(Cluster cluster) { super(cluster); } ////////////////////////////////////////////////////////////// public ConsistentHashSharding(List<Cluster> clusters) { super(clusters); } public ConsistentHashSharding(Cluster... clusters) { super(Arrays.asList(clusters)); } public SPOFStrategy getSpofStrategy() { return spofStrategy; } public void setSpofStrategy(SPOFStrategy spofStrategy) { this.spofStrategy = spofStrategy; }
public Map<String, Range<Integer>> getRangeMap() {
yiding-he/hydrogen-ssdb
src/main/java/com/hyd/ssdb/sharding/ConsistentHashSharding.java
// Path: src/main/java/com/hyd/ssdb/util/MD5.java // public class MD5 { // // /** // * 利用 md5 生成字符串的 hashCode // * // * @param str 要签名的字符串 // * // * @return 签名的 hash // */ // public static int md5Hash(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // byte[] bytes = digest.digest(str.getBytes("UTF-8")); // return b2i(bytes); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // // public static int b2i(byte[] b) { // int value = 0; // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (b[i] & 0x000000FF) << shift; // } // return value; // } // } // // Path: src/main/java/com/hyd/ssdb/util/Range.java // public class Range<T extends Number> { // // private T min; // // private T max; // // public Range(T min, T max) { // this.min = min; // this.max = max; // } // // public T getMin() { // return min; // } // // public void setMin(T min) { // this.min = min; // } // // public T getMax() { // return max; // } // // public void setMax(T max) { // this.max = max; // } // // public boolean contains(T value) { // if (value instanceof Integer) { // return (Integer) this.min <= (Integer) value && (Integer) value <= (Integer) this.max; // } else if (value instanceof Long) { // return (Long) this.min <= (Long) value && (Long) value <= (Long) this.max; // } else if (value instanceof Double) { // return (Double) this.min <= (Double) value && (Double) value <= (Double) this.max; // } else if (value instanceof Float) { // return (Float) this.min <= (Float) value && (Float) value <= (Float) this.max; // } else if (value instanceof Short) { // return (Short) this.min <= (Short) value && (Short) value <= (Short) this.max; // } else if (value instanceof Byte) { // return (Byte) this.min <= (Byte) value && (Byte) value <= (Byte) this.max; // } else { // throw new UnsupportedOperationException("Type '" + value.getClass() + "' not supported."); // } // } // // public Range<T> duplicate() { // return new Range<T>(min, max); // } // // @Override // public String toString() { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // }
import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.util.MD5; import com.hyd.ssdb.util.Range; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
throw new SsdbClientException("should not be here"); } private int getAvailableClusterCount() { int n = 0; for (Cluster cluster : clusters) { if (!cluster.isInvalid()) { n += 1; } } return n; } private boolean noClusterAvailable() { for (Cluster cluster : clusters) { if (!cluster.isInvalid()) { return false; } } return true; } @Override public Cluster getClusterByKey(String key) { if (noClusterAvailable()) { throw new SsdbNoClusterAvailableException("NO CLUSTER AVAILABLE"); }
// Path: src/main/java/com/hyd/ssdb/util/MD5.java // public class MD5 { // // /** // * 利用 md5 生成字符串的 hashCode // * // * @param str 要签名的字符串 // * // * @return 签名的 hash // */ // public static int md5Hash(String str) { // try { // MessageDigest digest = MessageDigest.getInstance("MD5"); // byte[] bytes = digest.digest(str.getBytes("UTF-8")); // return b2i(bytes); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); // } // } // // public static int b2i(byte[] b) { // int value = 0; // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (b[i] & 0x000000FF) << shift; // } // return value; // } // } // // Path: src/main/java/com/hyd/ssdb/util/Range.java // public class Range<T extends Number> { // // private T min; // // private T max; // // public Range(T min, T max) { // this.min = min; // this.max = max; // } // // public T getMin() { // return min; // } // // public void setMin(T min) { // this.min = min; // } // // public T getMax() { // return max; // } // // public void setMax(T max) { // this.max = max; // } // // public boolean contains(T value) { // if (value instanceof Integer) { // return (Integer) this.min <= (Integer) value && (Integer) value <= (Integer) this.max; // } else if (value instanceof Long) { // return (Long) this.min <= (Long) value && (Long) value <= (Long) this.max; // } else if (value instanceof Double) { // return (Double) this.min <= (Double) value && (Double) value <= (Double) this.max; // } else if (value instanceof Float) { // return (Float) this.min <= (Float) value && (Float) value <= (Float) this.max; // } else if (value instanceof Short) { // return (Short) this.min <= (Short) value && (Short) value <= (Short) this.max; // } else if (value instanceof Byte) { // return (Byte) this.min <= (Byte) value && (Byte) value <= (Byte) this.max; // } else { // throw new UnsupportedOperationException("Type '" + value.getClass() + "' not supported."); // } // } // // public Range<T> duplicate() { // return new Range<T>(min, max); // } // // @Override // public String toString() { // return "Range{" + // "min=" + min + // ", max=" + max + // '}'; // } // } // Path: src/main/java/com/hyd/ssdb/sharding/ConsistentHashSharding.java import com.hyd.ssdb.*; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.util.MD5; import com.hyd.ssdb.util.Range; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; throw new SsdbClientException("should not be here"); } private int getAvailableClusterCount() { int n = 0; for (Cluster cluster : clusters) { if (!cluster.isInvalid()) { n += 1; } } return n; } private boolean noClusterAvailable() { for (Cluster cluster : clusters) { if (!cluster.isInvalid()) { return false; } } return true; } @Override public Cluster getClusterByKey(String key) { if (noClusterAvailable()) { throw new SsdbNoClusterAvailableException("NO CLUSTER AVAILABLE"); }
int hash = MD5.md5Hash(key);
jbenech/gnikrap
gnikrap-core/src/test/java/webapp/TranslationTest.java
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/Configuration.java // public final class Configuration { // private final JsonObject data; // // private Configuration(JsonObject data) { // this.data = data; // } // // public String getValueAsString(String path) { // return getValueAsString(path, null); // } // // public String getValueAsString(String path, String defaultValue) { // // return data.getString(path, defaultValue); // } // // public boolean getValueAsBoolean(String path) { // return getValueAsBoolean(path, false); // } // // public boolean getValueAsBoolean(String path, boolean defaultValue) { // return data.getBoolean(path, defaultValue); // } // // public int getValueAsInt(String path) { // return getValueAsInt(path, 0); // } // // public int getValueAsInt(String path, int defaultValue) { // return data.getInt(path, defaultValue); // } // // @Override // public String toString() { // return "Configuration: " + data.toString(); // } // // /** // * Load the configuration file which have the name of the package.class in the following order: // * <ul> // * <li>File in the current folder: <user.dir></li> // * <li>If not found: look at <user.home>/.gnikrap/</li> // * <li>If not found: look in root classpath</li> // * <ul> // */ // public static Configuration load(Class<?> clazzToConfigure) throws IOException { // String shortFileName = clazzToConfigure.getName() + ".config"; // String configurationFile = System.getProperty("user.dir") + "/" + shortFileName; // // if (new File(configurationFile).exists() == false) { // configurationFile = System.getProperty("user.home") + "/.gnikrap/" + shortFileName; // } // // if (new File(configurationFile).exists()) { // try (Reader r = new FileReader(configurationFile)) { // return new Configuration(JsonObject.readFrom(r)); // } // } else { // InputStream is = Configuration.class.getResourceAsStream("/" + shortFileName); // if (is != null) { // return new Configuration(JsonObject.readFrom(new InputStreamReader(is))); // } else { // throw new IOException("No configuration file found for: '" + shortFileName + "'"); // } // } // } // }
import org.gnikrap.utils.Configuration; import org.testng.Assert; import org.testng.annotations.Test; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonObject.Member; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet;
} } private Set<String> flatten(Map<String, JsonObject> ref) { Set<String> result = new TreeSet<>(); for (Map.Entry<String, JsonObject> e : ref.entrySet()) { flatten(e.getValue(), e.getKey(), result); } return result; } private void flatten(JsonObject ref, String path, Set<String> target) { for (Member m : ref) { String newPath = path + (path.length() > 0 ? "." : "") + m.getName(); if (m.getValue().isObject()) { flatten(m.getValue().asObject(), newPath, target); } else { if (!m.getName().startsWith("@")) { target.add(newPath); } } } } /** * Load the list of translation files available */ private List<File> loadTranslationFiles() { String translationPath = null; try {
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/Configuration.java // public final class Configuration { // private final JsonObject data; // // private Configuration(JsonObject data) { // this.data = data; // } // // public String getValueAsString(String path) { // return getValueAsString(path, null); // } // // public String getValueAsString(String path, String defaultValue) { // // return data.getString(path, defaultValue); // } // // public boolean getValueAsBoolean(String path) { // return getValueAsBoolean(path, false); // } // // public boolean getValueAsBoolean(String path, boolean defaultValue) { // return data.getBoolean(path, defaultValue); // } // // public int getValueAsInt(String path) { // return getValueAsInt(path, 0); // } // // public int getValueAsInt(String path, int defaultValue) { // return data.getInt(path, defaultValue); // } // // @Override // public String toString() { // return "Configuration: " + data.toString(); // } // // /** // * Load the configuration file which have the name of the package.class in the following order: // * <ul> // * <li>File in the current folder: <user.dir></li> // * <li>If not found: look at <user.home>/.gnikrap/</li> // * <li>If not found: look in root classpath</li> // * <ul> // */ // public static Configuration load(Class<?> clazzToConfigure) throws IOException { // String shortFileName = clazzToConfigure.getName() + ".config"; // String configurationFile = System.getProperty("user.dir") + "/" + shortFileName; // // if (new File(configurationFile).exists() == false) { // configurationFile = System.getProperty("user.home") + "/.gnikrap/" + shortFileName; // } // // if (new File(configurationFile).exists()) { // try (Reader r = new FileReader(configurationFile)) { // return new Configuration(JsonObject.readFrom(r)); // } // } else { // InputStream is = Configuration.class.getResourceAsStream("/" + shortFileName); // if (is != null) { // return new Configuration(JsonObject.readFrom(new InputStreamReader(is))); // } else { // throw new IOException("No configuration file found for: '" + shortFileName + "'"); // } // } // } // } // Path: gnikrap-core/src/test/java/webapp/TranslationTest.java import org.gnikrap.utils.Configuration; import org.testng.Assert; import org.testng.annotations.Test; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonObject.Member; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; } } private Set<String> flatten(Map<String, JsonObject> ref) { Set<String> result = new TreeSet<>(); for (Map.Entry<String, JsonObject> e : ref.entrySet()) { flatten(e.getValue(), e.getKey(), result); } return result; } private void flatten(JsonObject ref, String path, Set<String> target) { for (Member m : ref) { String newPath = path + (path.length() > 0 ? "." : "") + m.getName(); if (m.getValue().isObject()) { flatten(m.getValue().asObject(), newPath, target); } else { if (!m.getName().startsWith("@")) { target.add(newPath); } } } } /** * Load the list of translation files available */ private List<File> loadTranslationFiles() { String translationPath = null; try {
Configuration c = Configuration.load(TranslationTest.class);
jbenech/gnikrap
gnikrap-core/src/main/java/org/gnikrap/script/EV3SriptCommandSocketConnectionCallback.java
// Path: gnikrap-core/src/main/java/org/gnikrap/GnikrapAppContext.java // public interface GnikrapAppContext { // // /** // * Returns the {@link GnikrapApp} object (the application entry point). // */ // GnikrapApp getGnikrapApp(); // // /** // * Returns the {@link EV3ActionProcessor} object (process asynchronously all the actions/events from the GUI). // */ // EV3ActionProcessor getEV3ActionProcessor(); // // /** // * Returns the {@link ScriptExecutionManager} object (manage the script that run on Gnikrap). // */ // ScriptExecutionManager getScriptExecutionManager(); // // /** // * Returns {@link Configuration} object (Application configuration configuration loaded from the config file). // */ // Configuration getConfiguration(); // // /** // * Returns the {@link EV3SriptCommandSocketConnectionCallback} object (Enable to send back information to the GUI). // */ // EV3SriptCommandSocketConnectionCallback getEV3SriptCommandSocketConnectionCallback(); // } // // Path: gnikrap-core/src/main/java/org/gnikrap/utils/LoggerUtils.java // public class LoggerUtils { // // private LoggerUtils() { // Avoid instantiation // } // // /** // * Default initialization of the Logging fwk - Replace default formatter. // */ // public static void initializeLogging() { // Logger.getLogger(""); // // for (Enumeration<String> e = LogManager.getLogManager().getLoggerNames(); e.hasMoreElements();) { // for (Handler h : Logger.getLogger(e.nextElement()).getHandlers()) { // h.setFormatter(new OneLineFormatter()); // h.setLevel(Level.ALL); // Only filter Logger level // } // } // } // // /** // * // */ // public static void setDefaultLogLevel(String level) { // Level l = Level.parse(level); // initializeLogging(); // // for (Enumeration<String> e = LogManager.getLogManager().getLoggerNames(); e.hasMoreElements();) { // Logger.getLogger(e.nextElement()).setLevel(l); // } // } // // /** // * @return the {@see Logger} for this class // */ // public static Logger getLogger(Class<?> clazz) { // return Logger.getLogger(clazz.getName()); // } // // /** // * Print a log on a simple line // */ // public static final class OneLineFormatter extends Formatter { // private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n"); // private static final String FIELD_SEPARATOR = " - "; // // private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS");; // private final Date tempDate = new Date(); // // /** // * Format the given LogRecord. // * // * @param record the log record to be formatted. // * @return a formatted log record // */ // @Override // public synchronized String format(final LogRecord record) { // StringBuilder sb = new StringBuilder(256); // // // Date // tempDate.setTime(record.getMillis()); // sb.append(dateFormat.format(tempDate)).append(FIELD_SEPARATOR); // // // Level // sb.append(record.getLevel().getName()).append(FIELD_SEPARATOR); // // // Source // if (record.getSourceClassName() != null) { // sb.append(record.getSourceClassName()); // } else { // sb.append(record.getLoggerName()); // } // if (record.getSourceMethodName() != null) { // sb.append("/").append(record.getSourceMethodName()); // } // sb.append(FIELD_SEPARATOR); // // // Message // sb.append(formatMessage(record)).append(LINE_SEPARATOR); // // // Exceptions (if any) // if (record.getThrown() != null) { // StringWriter sw = new StringWriter(256); // PrintWriter pw = new PrintWriter(sw); // record.getThrown().printStackTrace(pw); // sb.append(sw); // } // // return sb.toString(); // } // } // }
import java.util.logging.Level; import java.util.logging.Logger; import org.gnikrap.GnikrapAppContext; import org.gnikrap.utils.LoggerUtils; import org.xnio.ChannelListener; import io.undertow.websockets.WebSocketConnectionCallback; import io.undertow.websockets.core.AbstractReceiveListener; import io.undertow.websockets.core.BufferedTextMessage; import io.undertow.websockets.core.StreamSourceFrameChannel; import io.undertow.websockets.core.WebSocketCallback; import io.undertow.websockets.core.WebSocketChannel; import io.undertow.websockets.core.WebSockets; import io.undertow.websockets.spi.WebSocketHttpExchange; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID;
/* * Gnikrap is a simple scripting environment for the Lego Mindstrom EV3 * Copyright (C) 2014-2015 Jean BENECH * * Gnikrap is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gnikrap is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gnikrap. If not, see <http://www.gnu.org/licenses/>. */ package org.gnikrap.script; /** * Handle the WebSocket connections for the Gnikrap web application. */ final public class EV3SriptCommandSocketConnectionCallback implements WebSocketConnectionCallback { private static final Logger LOGGER = LoggerUtils.getLogger(EV3SriptCommandSocketConnectionCallback.class); /** List of currently active WebSocket connections */ private final List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); private final EV3ActionProcessor ev3ActionProcessor;
// Path: gnikrap-core/src/main/java/org/gnikrap/GnikrapAppContext.java // public interface GnikrapAppContext { // // /** // * Returns the {@link GnikrapApp} object (the application entry point). // */ // GnikrapApp getGnikrapApp(); // // /** // * Returns the {@link EV3ActionProcessor} object (process asynchronously all the actions/events from the GUI). // */ // EV3ActionProcessor getEV3ActionProcessor(); // // /** // * Returns the {@link ScriptExecutionManager} object (manage the script that run on Gnikrap). // */ // ScriptExecutionManager getScriptExecutionManager(); // // /** // * Returns {@link Configuration} object (Application configuration configuration loaded from the config file). // */ // Configuration getConfiguration(); // // /** // * Returns the {@link EV3SriptCommandSocketConnectionCallback} object (Enable to send back information to the GUI). // */ // EV3SriptCommandSocketConnectionCallback getEV3SriptCommandSocketConnectionCallback(); // } // // Path: gnikrap-core/src/main/java/org/gnikrap/utils/LoggerUtils.java // public class LoggerUtils { // // private LoggerUtils() { // Avoid instantiation // } // // /** // * Default initialization of the Logging fwk - Replace default formatter. // */ // public static void initializeLogging() { // Logger.getLogger(""); // // for (Enumeration<String> e = LogManager.getLogManager().getLoggerNames(); e.hasMoreElements();) { // for (Handler h : Logger.getLogger(e.nextElement()).getHandlers()) { // h.setFormatter(new OneLineFormatter()); // h.setLevel(Level.ALL); // Only filter Logger level // } // } // } // // /** // * // */ // public static void setDefaultLogLevel(String level) { // Level l = Level.parse(level); // initializeLogging(); // // for (Enumeration<String> e = LogManager.getLogManager().getLoggerNames(); e.hasMoreElements();) { // Logger.getLogger(e.nextElement()).setLevel(l); // } // } // // /** // * @return the {@see Logger} for this class // */ // public static Logger getLogger(Class<?> clazz) { // return Logger.getLogger(clazz.getName()); // } // // /** // * Print a log on a simple line // */ // public static final class OneLineFormatter extends Formatter { // private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n"); // private static final String FIELD_SEPARATOR = " - "; // // private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS");; // private final Date tempDate = new Date(); // // /** // * Format the given LogRecord. // * // * @param record the log record to be formatted. // * @return a formatted log record // */ // @Override // public synchronized String format(final LogRecord record) { // StringBuilder sb = new StringBuilder(256); // // // Date // tempDate.setTime(record.getMillis()); // sb.append(dateFormat.format(tempDate)).append(FIELD_SEPARATOR); // // // Level // sb.append(record.getLevel().getName()).append(FIELD_SEPARATOR); // // // Source // if (record.getSourceClassName() != null) { // sb.append(record.getSourceClassName()); // } else { // sb.append(record.getLoggerName()); // } // if (record.getSourceMethodName() != null) { // sb.append("/").append(record.getSourceMethodName()); // } // sb.append(FIELD_SEPARATOR); // // // Message // sb.append(formatMessage(record)).append(LINE_SEPARATOR); // // // Exceptions (if any) // if (record.getThrown() != null) { // StringWriter sw = new StringWriter(256); // PrintWriter pw = new PrintWriter(sw); // record.getThrown().printStackTrace(pw); // sb.append(sw); // } // // return sb.toString(); // } // } // } // Path: gnikrap-core/src/main/java/org/gnikrap/script/EV3SriptCommandSocketConnectionCallback.java import java.util.logging.Level; import java.util.logging.Logger; import org.gnikrap.GnikrapAppContext; import org.gnikrap.utils.LoggerUtils; import org.xnio.ChannelListener; import io.undertow.websockets.WebSocketConnectionCallback; import io.undertow.websockets.core.AbstractReceiveListener; import io.undertow.websockets.core.BufferedTextMessage; import io.undertow.websockets.core.StreamSourceFrameChannel; import io.undertow.websockets.core.WebSocketCallback; import io.undertow.websockets.core.WebSocketChannel; import io.undertow.websockets.core.WebSockets; import io.undertow.websockets.spi.WebSocketHttpExchange; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; /* * Gnikrap is a simple scripting environment for the Lego Mindstrom EV3 * Copyright (C) 2014-2015 Jean BENECH * * Gnikrap is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gnikrap is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gnikrap. If not, see <http://www.gnu.org/licenses/>. */ package org.gnikrap.script; /** * Handle the WebSocket connections for the Gnikrap web application. */ final public class EV3SriptCommandSocketConnectionCallback implements WebSocketConnectionCallback { private static final Logger LOGGER = LoggerUtils.getLogger(EV3SriptCommandSocketConnectionCallback.class); /** List of currently active WebSocket connections */ private final List<WebSocketSession> sessions = new ArrayList<WebSocketSession>(); private final EV3ActionProcessor ev3ActionProcessor;
public EV3SriptCommandSocketConnectionCallback(GnikrapAppContext context) {
jbenech/gnikrap
gnikrap-core/src/main/java/org/gnikrap/script/EV3Message.java
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/MapBuilder.java // public final class MapBuilder<K, V> { // private final Map<K, V> map; // // public MapBuilder(Map<K, V> map) { // this.map = map; // } // // public MapBuilder<K, V> put(K k, V v) { // map.put(k, v); // return this; // } // // public Map<K, V> build() { // return map; // } // // public static final <K, V> MapBuilder<K, V> buildHashMap(K k, V v) { // return new MapBuilder<K, V>(new HashMap<K, V>()).put(k, v); // } // // public static final <K, V> MapBuilder<K, V> buildTreeMapBuilder() { // return new MapBuilder<K, V>(new TreeMap<K, V>()); // } // }
import com.eclipsesource.json.JsonValue; import java.util.UUID; import org.gnikrap.utils.MapBuilder; import com.eclipsesource.json.JsonObject;
/* * Gnikrap is a simple scripting environment for the Lego Mindstrom EV3 * Copyright (C) 2014 Jean BENECH * * Gnikrap is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gnikrap is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gnikrap. If not, see <http://www.gnu.org/licenses/>. */ package org.gnikrap.script; /** * A helper class to use the json message received from the browser. */ public final class EV3Message { private final UUID sessionUUID; private final JsonObject jsonMessage; private String action; public EV3Message(UUID sessionUUID, String rawData) { this.sessionUUID = sessionUUID; this.jsonMessage = JsonObject.readFrom(rawData); } public UUID getSessionUUID() { return sessionUUID; } /** * Returns the {@link JsonValue} of the node with the name {@code fieldName}, throws an {@link EV3Exception} if not found. */ public JsonValue getField(String fieldName) throws EV3Exception { JsonValue keyNode = jsonMessage.get(fieldName); if (keyNode != null) { return keyNode; } else {
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/MapBuilder.java // public final class MapBuilder<K, V> { // private final Map<K, V> map; // // public MapBuilder(Map<K, V> map) { // this.map = map; // } // // public MapBuilder<K, V> put(K k, V v) { // map.put(k, v); // return this; // } // // public Map<K, V> build() { // return map; // } // // public static final <K, V> MapBuilder<K, V> buildHashMap(K k, V v) { // return new MapBuilder<K, V>(new HashMap<K, V>()).put(k, v); // } // // public static final <K, V> MapBuilder<K, V> buildTreeMapBuilder() { // return new MapBuilder<K, V>(new TreeMap<K, V>()); // } // } // Path: gnikrap-core/src/main/java/org/gnikrap/script/EV3Message.java import com.eclipsesource.json.JsonValue; import java.util.UUID; import org.gnikrap.utils.MapBuilder; import com.eclipsesource.json.JsonObject; /* * Gnikrap is a simple scripting environment for the Lego Mindstrom EV3 * Copyright (C) 2014 Jean BENECH * * Gnikrap is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Gnikrap is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gnikrap. If not, see <http://www.gnu.org/licenses/>. */ package org.gnikrap.script; /** * A helper class to use the json message received from the browser. */ public final class EV3Message { private final UUID sessionUUID; private final JsonObject jsonMessage; private String action; public EV3Message(UUID sessionUUID, String rawData) { this.sessionUUID = sessionUUID; this.jsonMessage = JsonObject.readFrom(rawData); } public UUID getSessionUUID() { return sessionUUID; } /** * Returns the {@link JsonValue} of the node with the name {@code fieldName}, throws an {@link EV3Exception} if not found. */ public JsonValue getField(String fieldName) throws EV3Exception { JsonValue keyNode = jsonMessage.get(fieldName); if (keyNode != null) { return keyNode; } else {
throw new EV3Exception(EV3Exception.MESSAGE_FIELD_NOT_FOUND, MapBuilder.buildHashMap("field", fieldName).build());
jbenech/gnikrap
gnikrap-core/src/main/java/org/gnikrap/script/ev3api/SimpleEV3Sound.java
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/MapBuilder.java // public final class MapBuilder<K, V> { // private final Map<K, V> map; // // public MapBuilder(Map<K, V> map) { // this.map = map; // } // // public MapBuilder<K, V> put(K k, V v) { // map.put(k, v); // return this; // } // // public Map<K, V> build() { // return map; // } // // public static final <K, V> MapBuilder<K, V> buildHashMap(K k, V v) { // return new MapBuilder<K, V>(new HashMap<K, V>()).put(k, v); // } // // public static final <K, V> MapBuilder<K, V> buildTreeMapBuilder() { // return new MapBuilder<K, V>(new TreeMap<K, V>()); // } // }
import lejos.hardware.Audio; import lejos.hardware.BrickFinder; import lejos.hardware.Sounds; import org.gnikrap.utils.MapBuilder; import org.gnikrap.utils.ScriptApi;
public int getVolume() { return audio.getVolume(); } @ScriptApi public void beep() { audio.systemSound(Sounds.BEEP); } /** * Play with the volume defined with {{@link #setVolume(int)} . */ @ScriptApi public void playTone(int frequency, int durationInMS) { audio.playTone(frequency, durationInMS, volume); } // public void playTone(int frequency, int durationInMS, int vol) { // audio.playTone(frequency, durationInMS, vol); // } // Currently not part of the ScriptAPI public void playFile(String filename) throws EV3ScriptException { playFile(filename, volume); } // Currently not part of the ScriptAPI public void playFile(String filename, int volume) throws EV3ScriptException { // TODO: implement // Sound.playSample(file, vol)
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/MapBuilder.java // public final class MapBuilder<K, V> { // private final Map<K, V> map; // // public MapBuilder(Map<K, V> map) { // this.map = map; // } // // public MapBuilder<K, V> put(K k, V v) { // map.put(k, v); // return this; // } // // public Map<K, V> build() { // return map; // } // // public static final <K, V> MapBuilder<K, V> buildHashMap(K k, V v) { // return new MapBuilder<K, V>(new HashMap<K, V>()).put(k, v); // } // // public static final <K, V> MapBuilder<K, V> buildTreeMapBuilder() { // return new MapBuilder<K, V>(new TreeMap<K, V>()); // } // } // Path: gnikrap-core/src/main/java/org/gnikrap/script/ev3api/SimpleEV3Sound.java import lejos.hardware.Audio; import lejos.hardware.BrickFinder; import lejos.hardware.Sounds; import org.gnikrap.utils.MapBuilder; import org.gnikrap.utils.ScriptApi; public int getVolume() { return audio.getVolume(); } @ScriptApi public void beep() { audio.systemSound(Sounds.BEEP); } /** * Play with the volume defined with {{@link #setVolume(int)} . */ @ScriptApi public void playTone(int frequency, int durationInMS) { audio.playTone(frequency, durationInMS, volume); } // public void playTone(int frequency, int durationInMS, int vol) { // audio.playTone(frequency, durationInMS, vol); // } // Currently not part of the ScriptAPI public void playFile(String filename) throws EV3ScriptException { playFile(filename, volume); } // Currently not part of the ScriptAPI public void playFile(String filename, int volume) throws EV3ScriptException { // TODO: implement // Sound.playSample(file, vol)
throw new EV3ScriptException(EV3ScriptException.API_NOT_IMPLEMENTED, MapBuilder.buildHashMap("function", "playFile()").build());
jbenech/gnikrap
gnikrap-core/src/main/java/org/gnikrap/script/ev3api/SimpleEV3IRSensor.java
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/MapBuilder.java // public final class MapBuilder<K, V> { // private final Map<K, V> map; // // public MapBuilder(Map<K, V> map) { // this.map = map; // } // // public MapBuilder<K, V> put(K k, V v) { // map.put(k, v); // return this; // } // // public Map<K, V> build() { // return map; // } // // public static final <K, V> MapBuilder<K, V> buildHashMap(K k, V v) { // return new MapBuilder<K, V>(new HashMap<K, V>()).put(k, v); // } // // public static final <K, V> MapBuilder<K, V> buildTreeMapBuilder() { // return new MapBuilder<K, V>(new TreeMap<K, V>()); // } // }
import lejos.hardware.port.Port; import lejos.hardware.sensor.EV3IRSensor; import lejos.hardware.sensor.SensorMode; import org.gnikrap.utils.MapBuilder; import org.gnikrap.utils.ScriptApi;
@ScriptApi public void setChannel(int channel) throws EV3ScriptException { checkChannel(channel); this.channel = channel; } @ScriptApi public RemoteCommandResult getRemoteCommand() { int temp = delegate.getRemoteCommand(channel - 1); // channel 0-based logger.log(EV3Constants.IR_SENSOR_REMOTE, temp); return new RemoteCommandResult(temp); } @ScriptApi public float getDistance() { distanceMode.fetchSample(distanceSample, 0); float result = distanceSample[0]; logger.log(EV3Constants.IR_SENSOR_DISTANCE, result); return result; } @ScriptApi public SeekBeaconResult seekBeacon() { seekMode.fetchSample(seekSample, 0); // TODO: Something to log ?! return new SeekBeaconResult(seekSample, channel); } protected static void checkChannel(int channel) throws EV3ScriptException { if (channel < 1 || channel > 4) {
// Path: gnikrap-core/src/main/java/org/gnikrap/utils/MapBuilder.java // public final class MapBuilder<K, V> { // private final Map<K, V> map; // // public MapBuilder(Map<K, V> map) { // this.map = map; // } // // public MapBuilder<K, V> put(K k, V v) { // map.put(k, v); // return this; // } // // public Map<K, V> build() { // return map; // } // // public static final <K, V> MapBuilder<K, V> buildHashMap(K k, V v) { // return new MapBuilder<K, V>(new HashMap<K, V>()).put(k, v); // } // // public static final <K, V> MapBuilder<K, V> buildTreeMapBuilder() { // return new MapBuilder<K, V>(new TreeMap<K, V>()); // } // } // Path: gnikrap-core/src/main/java/org/gnikrap/script/ev3api/SimpleEV3IRSensor.java import lejos.hardware.port.Port; import lejos.hardware.sensor.EV3IRSensor; import lejos.hardware.sensor.SensorMode; import org.gnikrap.utils.MapBuilder; import org.gnikrap.utils.ScriptApi; @ScriptApi public void setChannel(int channel) throws EV3ScriptException { checkChannel(channel); this.channel = channel; } @ScriptApi public RemoteCommandResult getRemoteCommand() { int temp = delegate.getRemoteCommand(channel - 1); // channel 0-based logger.log(EV3Constants.IR_SENSOR_REMOTE, temp); return new RemoteCommandResult(temp); } @ScriptApi public float getDistance() { distanceMode.fetchSample(distanceSample, 0); float result = distanceSample[0]; logger.log(EV3Constants.IR_SENSOR_DISTANCE, result); return result; } @ScriptApi public SeekBeaconResult seekBeacon() { seekMode.fetchSample(seekSample, 0); // TODO: Something to log ?! return new SeekBeaconResult(seekSample, channel); } protected static void checkChannel(int channel) throws EV3ScriptException { if (channel < 1 || channel > 4) {
throw new EV3ScriptException(EV3ScriptException.INVALID_CHANNEL_VALUE, MapBuilder.buildHashMap("channel", Integer.toString(channel)).build());
zhaque/my-wallpaper
src/com/koonen/photostream/settings/UserSettingsActivity.java
// Path: src/com/koonen/utils/StatisticUtils.java // public class StatisticUtils { // public static void onStartSession(Context context) { // FlurryAgent.onStartSession(context, ActivityConstants.FLURRY_KEY); // } // // public static void onEndSession() { // FlurryAgent.onEndSession(); // } // // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.Preference.OnPreferenceChangeListener; import com.koonen.photostream.R; import com.koonen.utils.StatisticUtils;
@Override public boolean onPreferenceChange(Preference preference, Object value) { String text = (String) value; initRotationSourcesList(text); return true; } }); } private void initRotationSourcesList(String networkName) { ListPreference rotationSourcePreference = (ListPreference) findPreference(UserPreferences.ROTATION_SOURCE_KEY); if (networkName == null || networkName.trim() == "") { rotationSourcePreference .setEntries(R.array.photo_source_type_safe_names); rotationSourcePreference .setEntryValues(R.array.photo_source_type_safe_values); } else { rotationSourcePreference .setEntries(R.array.photo_source_type_names); rotationSourcePreference .setEntryValues(R.array.photo_source_type_values); } } @Override protected void onStart() { super.onStart();
// Path: src/com/koonen/utils/StatisticUtils.java // public class StatisticUtils { // public static void onStartSession(Context context) { // FlurryAgent.onStartSession(context, ActivityConstants.FLURRY_KEY); // } // // public static void onEndSession() { // FlurryAgent.onEndSession(); // } // // } // Path: src/com/koonen/photostream/settings/UserSettingsActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.Preference.OnPreferenceChangeListener; import com.koonen.photostream.R; import com.koonen.utils.StatisticUtils; @Override public boolean onPreferenceChange(Preference preference, Object value) { String text = (String) value; initRotationSourcesList(text); return true; } }); } private void initRotationSourcesList(String networkName) { ListPreference rotationSourcePreference = (ListPreference) findPreference(UserPreferences.ROTATION_SOURCE_KEY); if (networkName == null || networkName.trim() == "") { rotationSourcePreference .setEntries(R.array.photo_source_type_safe_names); rotationSourcePreference .setEntryValues(R.array.photo_source_type_safe_values); } else { rotationSourcePreference .setEntries(R.array.photo_source_type_names); rotationSourcePreference .setEntryValues(R.array.photo_source_type_values); } } @Override protected void onStart() { super.onStart();
StatisticUtils.onStartSession(this);
zhaque/my-wallpaper
src/com/koonen/photostream/CategoryEditActivity.java
// Path: src/com/koonen/photostream/dao/Category.java // public class Category implements Parcelable { // // public static final String RECENT_CATEGORY = "Recent"; // // // private static final String[] CATEGORY_NAMES = { "Me", "Art", "Australia", // // "Beach", "Birthday", "California", "Canada", "Cat", "China", // // "Christmas", "City", "Concert", "Dog", "England", "Europe", // // "Family", "Festival", "Flowers", "Food", "France", "Friends", // // "Fun", "Germany", "Green", "Holiday", "Italy", "Japan", "London", // // "Music", "Nature", "New", "Newyork", "Night", "Nikon", "Nyc", // // "Paris", "Park", "Party", "People", "Portrait", "Red", // // "San Francisco", "Sky", "Snow", "Spain", "Summer", "Sunset", // // "Stockholm", "Travel", "Usa", "Vacation", "Water", "Wedding", // // "Winter" }; // // // // public static final Set<String> CATEGORY_NAMES_SET; // // // // static { // // CATEGORY_NAMES_SET = new HashSet<String>(Arrays.asList(CATEGORY_NAMES)); // // } // // private int id; // private String name; // private String tags; // // private Category() { // } // // private Category(Parcel in) { // id = in.readInt(); // name = in.readString(); // tags = in.readString(); // } // // public void update(Category category) { // name = category.name; // tags = category.tags; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTags() { // return tags; // } // // public void setTags(String tags) { // this.tags = tags; // } // // public boolean isRecent() { // return RECENT_CATEGORY.equals(name); // } // // @Override // public int hashCode() { // return id; // } // // @Override // public String toString() { // return id + " - " + name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(tags); // } // // public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { // public Category createFromParcel(Parcel in) { // return new Category(in); // } // // public Category[] newArray(int size) { // return new Category[size]; // } // }; // // public static Category createRecentCategory() { // Category category = new Category(); // category.name = RECENT_CATEGORY; // category.tags = ""; // return category; // } // // public static Category createCategory() { // Category category = new Category(); // return category; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.koonen.photostream.dao.Category;
package com.koonen.photostream; /** * * @author Glick * */ public class CategoryEditActivity extends Activity { static final String EXTRA_CATEGORY = "com.koonen.photostream.category"; static final String EXTRA_EDIT_CATEGORY = "com.koonen.photostream.edit_category"; private EditText categoryName; private EditText categoryTags;
// Path: src/com/koonen/photostream/dao/Category.java // public class Category implements Parcelable { // // public static final String RECENT_CATEGORY = "Recent"; // // // private static final String[] CATEGORY_NAMES = { "Me", "Art", "Australia", // // "Beach", "Birthday", "California", "Canada", "Cat", "China", // // "Christmas", "City", "Concert", "Dog", "England", "Europe", // // "Family", "Festival", "Flowers", "Food", "France", "Friends", // // "Fun", "Germany", "Green", "Holiday", "Italy", "Japan", "London", // // "Music", "Nature", "New", "Newyork", "Night", "Nikon", "Nyc", // // "Paris", "Park", "Party", "People", "Portrait", "Red", // // "San Francisco", "Sky", "Snow", "Spain", "Summer", "Sunset", // // "Stockholm", "Travel", "Usa", "Vacation", "Water", "Wedding", // // "Winter" }; // // // // public static final Set<String> CATEGORY_NAMES_SET; // // // // static { // // CATEGORY_NAMES_SET = new HashSet<String>(Arrays.asList(CATEGORY_NAMES)); // // } // // private int id; // private String name; // private String tags; // // private Category() { // } // // private Category(Parcel in) { // id = in.readInt(); // name = in.readString(); // tags = in.readString(); // } // // public void update(Category category) { // name = category.name; // tags = category.tags; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTags() { // return tags; // } // // public void setTags(String tags) { // this.tags = tags; // } // // public boolean isRecent() { // return RECENT_CATEGORY.equals(name); // } // // @Override // public int hashCode() { // return id; // } // // @Override // public String toString() { // return id + " - " + name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(tags); // } // // public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { // public Category createFromParcel(Parcel in) { // return new Category(in); // } // // public Category[] newArray(int size) { // return new Category[size]; // } // }; // // public static Category createRecentCategory() { // Category category = new Category(); // category.name = RECENT_CATEGORY; // category.tags = ""; // return category; // } // // public static Category createCategory() { // Category category = new Category(); // return category; // } // } // Path: src/com/koonen/photostream/CategoryEditActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.koonen.photostream.dao.Category; package com.koonen.photostream; /** * * @author Glick * */ public class CategoryEditActivity extends Activity { static final String EXTRA_CATEGORY = "com.koonen.photostream.category"; static final String EXTRA_EDIT_CATEGORY = "com.koonen.photostream.edit_category"; private EditText categoryName; private EditText categoryTags;
private Category category;
zhaque/my-wallpaper
src/com/koonen/utils/StatisticUtils.java
// Path: src/com/koonen/photostream/ActivityConstants.java // public class ActivityConstants { // // static final int REQUEST_ID_CATEGORY_EDIT = 100; // static final int RESULT_CATEGORY_FAIL = 10; // static final int RESULT_CATEGORY_EXIST = 11; // // static final int REQUEST_ID_CATEGORY_SEARCH = 20; // static final int RESULT_CATEGORY_SEARCH = 12; // // static final int SIMILAR_RESPONSE_ID = 1; // // static final int FILE_SYSTEM_PHOTO_REQUEST_ID = 101; // // public static final String FLURRY_KEY = "13DLYWDWTLT1CF699CD6"; // }
import android.content.Context; import com.flurry.android.FlurryAgent; import com.koonen.photostream.ActivityConstants;
package com.koonen.utils; /** * * @author dryganets * */ public class StatisticUtils { public static void onStartSession(Context context) {
// Path: src/com/koonen/photostream/ActivityConstants.java // public class ActivityConstants { // // static final int REQUEST_ID_CATEGORY_EDIT = 100; // static final int RESULT_CATEGORY_FAIL = 10; // static final int RESULT_CATEGORY_EXIST = 11; // // static final int REQUEST_ID_CATEGORY_SEARCH = 20; // static final int RESULT_CATEGORY_SEARCH = 12; // // static final int SIMILAR_RESPONSE_ID = 1; // // static final int FILE_SYSTEM_PHOTO_REQUEST_ID = 101; // // public static final String FLURRY_KEY = "13DLYWDWTLT1CF699CD6"; // } // Path: src/com/koonen/utils/StatisticUtils.java import android.content.Context; import com.flurry.android.FlurryAgent; import com.koonen.photostream.ActivityConstants; package com.koonen.utils; /** * * @author dryganets * */ public class StatisticUtils { public static void onStartSession(Context context) {
FlurryAgent.onStartSession(context, ActivityConstants.FLURRY_KEY);
zhaque/my-wallpaper
src/com/koonen/photostream/settings/UserPreferences.java
// Path: src/com/koonen/photostream/effects/TypeEffect.java // public class TypeEffect extends Enumeration { // // // public static final TypeEffect UNKNOWN_EFFECT = new TypeEffect("Unknown", // // "unknown"); // public static final TypeEffect RANDOM_EFFECT = new TypeEffect("random", // "random"); // public static final TypeEffect TRANSLATE_EFFECT = new TypeEffect( // "translate", "translate"); // public static final TypeEffect ALPHA_EFFECT = new TypeEffect("Alpha", // "alpha"); // public static final TypeEffect _3D_ROTATE_EFFECT = new TypeEffect( // "3dRotate", "3dRotate"); // public static final TypeEffect SCALE_EFFECT = new TypeEffect("scale", // "scale"); // // static { // // add(TypeEffect.class, UNKNOWN_EFFECT); // add(TypeEffect.class, RANDOM_EFFECT); // add(TypeEffect.class, TRANSLATE_EFFECT); // add(TypeEffect.class, ALPHA_EFFECT); // add(TypeEffect.class, _3D_ROTATE_EFFECT); // add(TypeEffect.class, SCALE_EFFECT); // } // // // public static TypeEffect GenerateTypeEffect() { // Collection<Enumeration> values = RANDOM_EFFECT.values(TypeEffect.class); // int num = Math.abs(new Random().nextInt()) % values.size(); // TypeEffect typeEffect = (TypeEffect) values.toArray()[num]; // if (typeEffect == RANDOM_EFFECT) { // typeEffect = _3D_ROTATE_EFFECT; // } // return typeEffect; // // } // // private TypeEffect(String name, String value) { // super(name, value); // } // // public static TypeEffect valueOf(String name) { // TypeEffect result = null; // result = (TypeEffect) valueOf(TypeEffect.class, name); // return result; // } // }
import com.koonen.photostream.effects.TypeEffect; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
// return preferences.getString(NETWORK_PASSWORD_KEY, ""); // } public String getUserName() { return preferences.getString(NETWORK_USER_NAME_KEY, ""); } public Network getNetwork() { return Network.valueOf(preferences .getString(NETWORK_NAME_KEY, "flickr")); } public boolean isRotationEnabed() { return preferences.getBoolean(ROTATION_ENABLED_KEY, false); } public long getRotationSchedule() { return Long .parseLong(preferences.getString(ROTATION_SCHEDULE_KEY, "0")); } public BackgroundSource getRotationBackgroundSource() { return BackgroundSource.valueOf(preferences.getString( ROTATION_SOURCE_KEY, "")); } public boolean isRotationNotificationEnabled() { return preferences.getBoolean(ROTATION_NOTIFICATION_KEY, false); }
// Path: src/com/koonen/photostream/effects/TypeEffect.java // public class TypeEffect extends Enumeration { // // // public static final TypeEffect UNKNOWN_EFFECT = new TypeEffect("Unknown", // // "unknown"); // public static final TypeEffect RANDOM_EFFECT = new TypeEffect("random", // "random"); // public static final TypeEffect TRANSLATE_EFFECT = new TypeEffect( // "translate", "translate"); // public static final TypeEffect ALPHA_EFFECT = new TypeEffect("Alpha", // "alpha"); // public static final TypeEffect _3D_ROTATE_EFFECT = new TypeEffect( // "3dRotate", "3dRotate"); // public static final TypeEffect SCALE_EFFECT = new TypeEffect("scale", // "scale"); // // static { // // add(TypeEffect.class, UNKNOWN_EFFECT); // add(TypeEffect.class, RANDOM_EFFECT); // add(TypeEffect.class, TRANSLATE_EFFECT); // add(TypeEffect.class, ALPHA_EFFECT); // add(TypeEffect.class, _3D_ROTATE_EFFECT); // add(TypeEffect.class, SCALE_EFFECT); // } // // // public static TypeEffect GenerateTypeEffect() { // Collection<Enumeration> values = RANDOM_EFFECT.values(TypeEffect.class); // int num = Math.abs(new Random().nextInt()) % values.size(); // TypeEffect typeEffect = (TypeEffect) values.toArray()[num]; // if (typeEffect == RANDOM_EFFECT) { // typeEffect = _3D_ROTATE_EFFECT; // } // return typeEffect; // // } // // private TypeEffect(String name, String value) { // super(name, value); // } // // public static TypeEffect valueOf(String name) { // TypeEffect result = null; // result = (TypeEffect) valueOf(TypeEffect.class, name); // return result; // } // } // Path: src/com/koonen/photostream/settings/UserPreferences.java import com.koonen.photostream.effects.TypeEffect; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; // return preferences.getString(NETWORK_PASSWORD_KEY, ""); // } public String getUserName() { return preferences.getString(NETWORK_USER_NAME_KEY, ""); } public Network getNetwork() { return Network.valueOf(preferences .getString(NETWORK_NAME_KEY, "flickr")); } public boolean isRotationEnabed() { return preferences.getBoolean(ROTATION_ENABLED_KEY, false); } public long getRotationSchedule() { return Long .parseLong(preferences.getString(ROTATION_SCHEDULE_KEY, "0")); } public BackgroundSource getRotationBackgroundSource() { return BackgroundSource.valueOf(preferences.getString( ROTATION_SOURCE_KEY, "")); } public boolean isRotationNotificationEnabled() { return preferences.getBoolean(ROTATION_NOTIFICATION_KEY, false); }
public TypeEffect getTypeEffect() {
zhaque/my-wallpaper
src/com/koonen/photostream/api/ServiceContext.java
// Path: src/com/koonen/photostream/dao/Category.java // public class Category implements Parcelable { // // public static final String RECENT_CATEGORY = "Recent"; // // // private static final String[] CATEGORY_NAMES = { "Me", "Art", "Australia", // // "Beach", "Birthday", "California", "Canada", "Cat", "China", // // "Christmas", "City", "Concert", "Dog", "England", "Europe", // // "Family", "Festival", "Flowers", "Food", "France", "Friends", // // "Fun", "Germany", "Green", "Holiday", "Italy", "Japan", "London", // // "Music", "Nature", "New", "Newyork", "Night", "Nikon", "Nyc", // // "Paris", "Park", "Party", "People", "Portrait", "Red", // // "San Francisco", "Sky", "Snow", "Spain", "Summer", "Sunset", // // "Stockholm", "Travel", "Usa", "Vacation", "Water", "Wedding", // // "Winter" }; // // // // public static final Set<String> CATEGORY_NAMES_SET; // // // // static { // // CATEGORY_NAMES_SET = new HashSet<String>(Arrays.asList(CATEGORY_NAMES)); // // } // // private int id; // private String name; // private String tags; // // private Category() { // } // // private Category(Parcel in) { // id = in.readInt(); // name = in.readString(); // tags = in.readString(); // } // // public void update(Category category) { // name = category.name; // tags = category.tags; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTags() { // return tags; // } // // public void setTags(String tags) { // this.tags = tags; // } // // public boolean isRecent() { // return RECENT_CATEGORY.equals(name); // } // // @Override // public int hashCode() { // return id; // } // // @Override // public String toString() { // return id + " - " + name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(tags); // } // // public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { // public Category createFromParcel(Parcel in) { // return new Category(in); // } // // public Category[] newArray(int size) { // return new Category[size]; // } // }; // // public static Category createRecentCategory() { // Category category = new Category(); // category.name = RECENT_CATEGORY; // category.tags = ""; // return category; // } // // public static Category createCategory() { // Category category = new Category(); // return category; // } // }
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.provider.MediaStore.Images.Media; import com.koonen.photostream.dao.Category;
String name = (String) iterator.next(); result.addParameter(name, serviceContext.extra.get(name)); } result.setQuery(serviceContext.getQuery()); result.type = serviceContext.getType(); // result.setScreenName(serviceContext.getScreenName()); result.setScreenName("Make this your wallpaper!"); return result; } public static ServiceContext createFavoritesServiceContext(int pageSize) { ServiceContext result = new ServiceContext(); result.setPagable(true); result.setPageSize(pageSize); result.setCurrentPage(1); result.type = Type.FAVORITES; result.setScreenName("My favorites photos"); return result; } public static ServiceContext createCameraServiceContext() { ServiceContext result = new ServiceContext(); result.setPagable(true); result.setPageSize(1); result.setCurrentPage(1); result.type = Type.CAMERA; result.setScreenName("Photo from camera"); return result; }
// Path: src/com/koonen/photostream/dao/Category.java // public class Category implements Parcelable { // // public static final String RECENT_CATEGORY = "Recent"; // // // private static final String[] CATEGORY_NAMES = { "Me", "Art", "Australia", // // "Beach", "Birthday", "California", "Canada", "Cat", "China", // // "Christmas", "City", "Concert", "Dog", "England", "Europe", // // "Family", "Festival", "Flowers", "Food", "France", "Friends", // // "Fun", "Germany", "Green", "Holiday", "Italy", "Japan", "London", // // "Music", "Nature", "New", "Newyork", "Night", "Nikon", "Nyc", // // "Paris", "Park", "Party", "People", "Portrait", "Red", // // "San Francisco", "Sky", "Snow", "Spain", "Summer", "Sunset", // // "Stockholm", "Travel", "Usa", "Vacation", "Water", "Wedding", // // "Winter" }; // // // // public static final Set<String> CATEGORY_NAMES_SET; // // // // static { // // CATEGORY_NAMES_SET = new HashSet<String>(Arrays.asList(CATEGORY_NAMES)); // // } // // private int id; // private String name; // private String tags; // // private Category() { // } // // private Category(Parcel in) { // id = in.readInt(); // name = in.readString(); // tags = in.readString(); // } // // public void update(Category category) { // name = category.name; // tags = category.tags; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTags() { // return tags; // } // // public void setTags(String tags) { // this.tags = tags; // } // // public boolean isRecent() { // return RECENT_CATEGORY.equals(name); // } // // @Override // public int hashCode() { // return id; // } // // @Override // public String toString() { // return id + " - " + name; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(tags); // } // // public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { // public Category createFromParcel(Parcel in) { // return new Category(in); // } // // public Category[] newArray(int size) { // return new Category[size]; // } // }; // // public static Category createRecentCategory() { // Category category = new Category(); // category.name = RECENT_CATEGORY; // category.tags = ""; // return category; // } // // public static Category createCategory() { // Category category = new Category(); // return category; // } // } // Path: src/com/koonen/photostream/api/ServiceContext.java import java.util.HashMap; import java.util.Iterator; import java.util.Map; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.provider.MediaStore.Images.Media; import com.koonen.photostream.dao.Category; String name = (String) iterator.next(); result.addParameter(name, serviceContext.extra.get(name)); } result.setQuery(serviceContext.getQuery()); result.type = serviceContext.getType(); // result.setScreenName(serviceContext.getScreenName()); result.setScreenName("Make this your wallpaper!"); return result; } public static ServiceContext createFavoritesServiceContext(int pageSize) { ServiceContext result = new ServiceContext(); result.setPagable(true); result.setPageSize(pageSize); result.setCurrentPage(1); result.type = Type.FAVORITES; result.setScreenName("My favorites photos"); return result; } public static ServiceContext createCameraServiceContext() { ServiceContext result = new ServiceContext(); result.setPagable(true); result.setPageSize(1); result.setCurrentPage(1); result.type = Type.CAMERA; result.setScreenName("Photo from camera"); return result; }
public static ServiceContext createCategoryContext(Category category,
zhaque/my-wallpaper
src/com/koonen/photostream/CameraPreviewActivity.java
// Path: src/com/koonen/utils/StreamUtils.java // public class StreamUtils { // private static final String TAG = "StreamUtils"; // // private static final int IO_BUFFER_SIZE = 1024 * 8; // // /** // * Copy the content of the input stream into the output stream, using a // * temporary byte array buffer whose size is defined by // * {@link #IO_BUFFER_SIZE}. // * // * @param in // * The input stream to copy from. // * @param out // * The output stream to copy to. // * // * @throws IOException // * If any error occurs during the copy. // */ // public static void copy(InputStream in, OutputStream out) // throws IOException { // byte[] b = new byte[IO_BUFFER_SIZE]; // int read; // while ((read = in.read(b)) != -1) { // out.write(b, 0, read); // } // } // // /** // * Closes the specified stream. // * // * @param stream // * The stream to close. // */ // public static void closeStream(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // android.util.Log.e(TAG, "Could not close stream", e); // } // } // } // // // TODO: refactore // public static boolean saveBitmap(Context context, Bitmap bitmap, // String filePath) { // boolean result = false; // try { // FileOutputStream fos = context.openFileOutput(filePath, // Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); // // bitmap.compress(CompressFormat.JPEG, 100, fos); // // fos.flush(); // fos.close(); // result = true; // } catch (Exception e) { // Log.e(TAG, e.toString()); // } // return result; // } // }
import java.util.concurrent.Semaphore; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.Window; import com.koonen.utils.StreamUtils;
// Create our Preview view and set it as the content of our activity. mPreview = new Preview(this); setContentView(mPreview); } private static final int MENU_ITEM_TAKE_PICTURE = 1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_ITEM_TAKE_PICTURE, 0, R.string.camera_take_picture); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ITEM_TAKE_PICTURE: Thread thread = new Thread(new Runnable() { @Override public void run() { mPreview.setTakePicture(true); mPreview.takePicture(); try { mPreview.getSemaphore().acquire(); } catch (InterruptedException e) { } Bitmap bitmap = mPreview.getPicture();
// Path: src/com/koonen/utils/StreamUtils.java // public class StreamUtils { // private static final String TAG = "StreamUtils"; // // private static final int IO_BUFFER_SIZE = 1024 * 8; // // /** // * Copy the content of the input stream into the output stream, using a // * temporary byte array buffer whose size is defined by // * {@link #IO_BUFFER_SIZE}. // * // * @param in // * The input stream to copy from. // * @param out // * The output stream to copy to. // * // * @throws IOException // * If any error occurs during the copy. // */ // public static void copy(InputStream in, OutputStream out) // throws IOException { // byte[] b = new byte[IO_BUFFER_SIZE]; // int read; // while ((read = in.read(b)) != -1) { // out.write(b, 0, read); // } // } // // /** // * Closes the specified stream. // * // * @param stream // * The stream to close. // */ // public static void closeStream(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // android.util.Log.e(TAG, "Could not close stream", e); // } // } // } // // // TODO: refactore // public static boolean saveBitmap(Context context, Bitmap bitmap, // String filePath) { // boolean result = false; // try { // FileOutputStream fos = context.openFileOutput(filePath, // Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); // // bitmap.compress(CompressFormat.JPEG, 100, fos); // // fos.flush(); // fos.close(); // result = true; // } catch (Exception e) { // Log.e(TAG, e.toString()); // } // return result; // } // } // Path: src/com/koonen/photostream/CameraPreviewActivity.java import java.util.concurrent.Semaphore; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.Window; import com.koonen.utils.StreamUtils; // Create our Preview view and set it as the content of our activity. mPreview = new Preview(this); setContentView(mPreview); } private static final int MENU_ITEM_TAKE_PICTURE = 1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_ITEM_TAKE_PICTURE, 0, R.string.camera_take_picture); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ITEM_TAKE_PICTURE: Thread thread = new Thread(new Runnable() { @Override public void run() { mPreview.setTakePicture(true); mPreview.takePicture(); try { mPreview.getSemaphore().acquire(); } catch (InterruptedException e) { } Bitmap bitmap = mPreview.getPicture();
StreamUtils.saveBitmap(CameraPreviewActivity.this, bitmap,
zhaque/my-wallpaper
src/com/koonen/photostream/api/flickr/Auth.java
// Path: src/com/koonen/photostream/api/User.java // public class User { // String id; // // public User(String id) { // super(); // this.id = id; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // }
import com.koonen.photostream.api.User;
package com.koonen.photostream.api.flickr; public class Auth { private String token; private Perms perms;
// Path: src/com/koonen/photostream/api/User.java // public class User { // String id; // // public User(String id) { // super(); // this.id = id; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // Path: src/com/koonen/photostream/api/flickr/Auth.java import com.koonen.photostream.api.User; package com.koonen.photostream.api.flickr; public class Auth { private String token; private Perms perms;
private User user;
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientConfiguration.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/SimpleDnsBasedDiscoveryClient.java // @FunctionalInterface // public interface ServiceIdToHostnameConverter { // // String toHostname(String serviceId); // // }
import org.springframework.context.annotation.Configuration; import org.cloudfoundry.operations.CloudFoundryOperations; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.SimpleDnsBasedDiscoveryClient.ServiceIdToHostnameConverter; import org.springframework.context.annotation.Bean;
/* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Josh Long */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CloudFoundryOperations.class) @ConditionalOnDiscoveryEnabled @ConditionalOnBlockingDiscoveryEnabled @ConditionalOnCloudFoundryDiscoveryEnabled @EnableConfigurationProperties(CloudFoundryDiscoveryProperties.class) public class CloudFoundryDiscoveryClientConfiguration { @Bean @ConditionalOnBean(CloudFoundryDiscoveryClient.class) public CloudFoundryHeartbeatSender cloudFoundryHeartbeatSender(CloudFoundryDiscoveryClient client) { return new CloudFoundryHeartbeatSender(client); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-dns", havingValue = "false", matchIfMissing = true) public static class CloudFoundryDiscoveryClientConfig { @Bean @ConditionalOnMissingBean(DiscoveryClient.class) public CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient(CloudFoundryOperations cf,
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/SimpleDnsBasedDiscoveryClient.java // @FunctionalInterface // public interface ServiceIdToHostnameConverter { // // String toHostname(String serviceId); // // } // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientConfiguration.java import org.springframework.context.annotation.Configuration; import org.cloudfoundry.operations.CloudFoundryOperations; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.SimpleDnsBasedDiscoveryClient.ServiceIdToHostnameConverter; import org.springframework.context.annotation.Bean; /* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Josh Long */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CloudFoundryOperations.class) @ConditionalOnDiscoveryEnabled @ConditionalOnBlockingDiscoveryEnabled @ConditionalOnCloudFoundryDiscoveryEnabled @EnableConfigurationProperties(CloudFoundryDiscoveryProperties.class) public class CloudFoundryDiscoveryClientConfiguration { @Bean @ConditionalOnBean(CloudFoundryDiscoveryClient.class) public CloudFoundryHeartbeatSender cloudFoundryHeartbeatSender(CloudFoundryDiscoveryClient client) { return new CloudFoundryHeartbeatSender(client); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-dns", havingValue = "false", matchIfMissing = true) public static class CloudFoundryDiscoveryClientConfig { @Bean @ConditionalOnMissingBean(DiscoveryClient.class) public CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient(CloudFoundryOperations cf,
CloudFoundryService svc, CloudFoundryDiscoveryProperties cloudFoundryDiscoveryProperties) {
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientConfiguration.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/SimpleDnsBasedDiscoveryClient.java // @FunctionalInterface // public interface ServiceIdToHostnameConverter { // // String toHostname(String serviceId); // // }
import org.springframework.context.annotation.Configuration; import org.cloudfoundry.operations.CloudFoundryOperations; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.SimpleDnsBasedDiscoveryClient.ServiceIdToHostnameConverter; import org.springframework.context.annotation.Bean;
/* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Josh Long */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CloudFoundryOperations.class) @ConditionalOnDiscoveryEnabled @ConditionalOnBlockingDiscoveryEnabled @ConditionalOnCloudFoundryDiscoveryEnabled @EnableConfigurationProperties(CloudFoundryDiscoveryProperties.class) public class CloudFoundryDiscoveryClientConfiguration { @Bean @ConditionalOnBean(CloudFoundryDiscoveryClient.class) public CloudFoundryHeartbeatSender cloudFoundryHeartbeatSender(CloudFoundryDiscoveryClient client) { return new CloudFoundryHeartbeatSender(client); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-dns", havingValue = "false", matchIfMissing = true) public static class CloudFoundryDiscoveryClientConfig { @Bean @ConditionalOnMissingBean(DiscoveryClient.class) public CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient(CloudFoundryOperations cf, CloudFoundryService svc, CloudFoundryDiscoveryProperties cloudFoundryDiscoveryProperties) { return new CloudFoundryDiscoveryClient(cf, svc, cloudFoundryDiscoveryProperties); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-dns", havingValue = "true") public static class DnsBasedCloudFoundryDiscoveryClientConfig { @Bean @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-container-ip", havingValue = "true") @ConditionalOnMissingBean(DiscoveryClient.class)
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/SimpleDnsBasedDiscoveryClient.java // @FunctionalInterface // public interface ServiceIdToHostnameConverter { // // String toHostname(String serviceId); // // } // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientConfiguration.java import org.springframework.context.annotation.Configuration; import org.cloudfoundry.operations.CloudFoundryOperations; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.SimpleDnsBasedDiscoveryClient.ServiceIdToHostnameConverter; import org.springframework.context.annotation.Bean; /* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Josh Long */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CloudFoundryOperations.class) @ConditionalOnDiscoveryEnabled @ConditionalOnBlockingDiscoveryEnabled @ConditionalOnCloudFoundryDiscoveryEnabled @EnableConfigurationProperties(CloudFoundryDiscoveryProperties.class) public class CloudFoundryDiscoveryClientConfiguration { @Bean @ConditionalOnBean(CloudFoundryDiscoveryClient.class) public CloudFoundryHeartbeatSender cloudFoundryHeartbeatSender(CloudFoundryDiscoveryClient client) { return new CloudFoundryHeartbeatSender(client); } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-dns", havingValue = "false", matchIfMissing = true) public static class CloudFoundryDiscoveryClientConfig { @Bean @ConditionalOnMissingBean(DiscoveryClient.class) public CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient(CloudFoundryOperations cf, CloudFoundryService svc, CloudFoundryDiscoveryProperties cloudFoundryDiscoveryProperties) { return new CloudFoundryDiscoveryClient(cf, svc, cloudFoundryDiscoveryProperties); } } @Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-dns", havingValue = "true") public static class DnsBasedCloudFoundryDiscoveryClientConfig { @Bean @ConditionalOnProperty(value = "spring.cloud.cloudfoundry.discovery.use-container-ip", havingValue = "true") @ConditionalOnMissingBean(DiscoveryClient.class)
public SimpleDnsBasedDiscoveryClient discoveryClient(ObjectProvider<ServiceIdToHostnameConverter> provider,
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryAppServiceDiscoveryClientTest.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // }
import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import java.util.HashMap; import java.util.List; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.util.function.Tuples; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService;
/* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Toshiaki Maki */ public class CloudFoundryAppServiceDiscoveryClientTest { private CloudFoundryAppServiceDiscoveryClient discoveryClient; private CloudFoundryOperations cloudFoundryOperations;
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryAppServiceDiscoveryClientTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import java.util.HashMap; import java.util.List; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.util.function.Tuples; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; /* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Toshiaki Maki */ public class CloudFoundryAppServiceDiscoveryClientTest { private CloudFoundryAppServiceDiscoveryClient discoveryClient; private CloudFoundryOperations cloudFoundryOperations;
private CloudFoundryService cloudFoundryService;
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryAppServiceDiscoveryClient.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // }
import java.util.HashMap; import java.util.List; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.InstanceDetail; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService;
/* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * * Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Toshiaki Maki * @see <a href="https://github.com/cloudfoundry/cf-app-sd-release">CF App Service * Discovery Release</a> * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class CloudFoundryAppServiceDiscoveryClient extends CloudFoundryDiscoveryClient { private static final String INTERNAL_DOMAIN = "apps.internal";
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryAppServiceDiscoveryClient.java import java.util.HashMap; import java.util.List; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.InstanceDetail; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; /* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * * Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Toshiaki Maki * @see <a href="https://github.com/cloudfoundry/cf-app-sd-release">CF App Service * Discovery Release</a> * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class CloudFoundryAppServiceDiscoveryClient extends CloudFoundryDiscoveryClient { private static final String INTERNAL_DOMAIN = "apps.internal";
CloudFoundryAppServiceDiscoveryClient(CloudFoundryOperations cloudFoundryOperations, CloudFoundryService svc,
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-web/src/test/java/org/springframework/cloud/cloudfoundry/environment/VcapServiceCredentialsEnvironmentPostProcessorTests.java
// Path: spring-cloud-cloudfoundry-web/src/main/java/org/springframework/cloud/cloudfoundry/environment/VcapServiceCredentialsEnvironmentPostProcessor.java // static final Bindable<Map<String, Object>> STRING_OBJECT_MAP = Bindable.mapOf(String.class, Object.class);
import java.util.Collections; import java.util.Map; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.cloudfoundry.environment.VcapServiceCredentialsEnvironmentPostProcessor.STRING_OBJECT_MAP;
/* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.environment; /** * @author Dave Syer * */ public class VcapServiceCredentialsEnvironmentPostProcessorTests { private VcapServiceCredentialsEnvironmentPostProcessor listener = new VcapServiceCredentialsEnvironmentPostProcessor(); private ConfigurableEnvironment environment = new StandardEnvironment(); @Test public void noop() { this.listener.postProcessEnvironment(this.environment, new SpringApplication());
// Path: spring-cloud-cloudfoundry-web/src/main/java/org/springframework/cloud/cloudfoundry/environment/VcapServiceCredentialsEnvironmentPostProcessor.java // static final Bindable<Map<String, Object>> STRING_OBJECT_MAP = Bindable.mapOf(String.class, Object.class); // Path: spring-cloud-cloudfoundry-web/src/test/java/org/springframework/cloud/cloudfoundry/environment/VcapServiceCredentialsEnvironmentPostProcessorTests.java import java.util.Collections; import java.util.Map; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.cloud.cloudfoundry.environment.VcapServiceCredentialsEnvironmentPostProcessor.STRING_OBJECT_MAP; /* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.environment; /** * @author Dave Syer * */ public class VcapServiceCredentialsEnvironmentPostProcessorTests { private VcapServiceCredentialsEnvironmentPostProcessor listener = new VcapServiceCredentialsEnvironmentPostProcessor(); private ConfigurableEnvironment environment = new StandardEnvironment(); @Test public void noop() { this.listener.postProcessEnvironment(this.environment, new SpringApplication());
Map<String, Object> properties = Binder.get(this.environment).bind("security.oauth2", STRING_OBJECT_MAP)
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryReactiveDiscoveryClientConfigurationTests.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // }
import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.cloudfoundry.operations.CloudFoundryOperations; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.client.discovery.health.reactive.ReactiveDiscoveryClientHealthIndicator; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.context.annotation.Bean;
}); } @Test public void worksWithoutWebflux() { contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.reactive")).run(context -> { assertThat(context).doesNotHaveBean(CloudFoundryReactiveHeartbeatSender.class); assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); }); } @Test public void worksWithoutActuator() { contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")).run(context -> { assertThat(context).hasSingleBean(CloudFoundryReactiveHeartbeatSender.class); assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); }); } @TestConfiguration static class MockedCloudFoundryConfiguration { @Bean public CloudFoundryOperations mockedOperations() { return mock(CloudFoundryOperations.class); } @Bean
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryReactiveDiscoveryClientConfigurationTests.java import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.cloudfoundry.operations.CloudFoundryOperations; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.client.discovery.health.reactive.ReactiveDiscoveryClientHealthIndicator; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.context.annotation.Bean; }); } @Test public void worksWithoutWebflux() { contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.reactive")).run(context -> { assertThat(context).doesNotHaveBean(CloudFoundryReactiveHeartbeatSender.class); assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); }); } @Test public void worksWithoutActuator() { contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")).run(context -> { assertThat(context).hasSingleBean(CloudFoundryReactiveHeartbeatSender.class); assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); }); } @TestConfiguration static class MockedCloudFoundryConfiguration { @Bean public CloudFoundryOperations mockedOperations() { return mock(CloudFoundryOperations.class); } @Bean
public CloudFoundryService mockedService() {
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryAppServiceReactiveDiscoveryClientTests.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // }
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import static org.mockito.Mockito.when; import java.util.UUID; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; import reactor.util.function.Tuples;
/* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * @author Tim Ysewyn */ @ExtendWith(MockitoExtension.class) class CloudFoundryAppServiceReactiveDiscoveryClientTests { @Mock
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryAppServiceReactiveDiscoveryClientTests.java import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import static org.mockito.Mockito.when; import java.util.UUID; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; /* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * @author Tim Ysewyn */ @ExtendWith(MockitoExtension.class) class CloudFoundryAppServiceReactiveDiscoveryClientTests { @Mock
private CloudFoundryService svc;
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryAppServiceReactiveDiscoveryClient.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // }
import org.cloudfoundry.operations.CloudFoundryOperations; import reactor.core.publisher.Flux; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties;
/* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Tim Ysewyn * @see <a href="https://github.com/cloudfoundry/cf-app-sd-release">CF App Service * Discovery Release</a> * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class CloudFoundryAppServiceReactiveDiscoveryClient extends CloudFoundryNativeReactiveDiscoveryClient { private static final String INTERNAL_DOMAIN = "apps.internal";
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryAppServiceReactiveDiscoveryClient.java import org.cloudfoundry.operations.CloudFoundryOperations; import reactor.core.publisher.Flux; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; /* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Tim Ysewyn * @see <a href="https://github.com/cloudfoundry/cf-app-sd-release">CF App Service * Discovery Release</a> * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class CloudFoundryAppServiceReactiveDiscoveryClient extends CloudFoundryNativeReactiveDiscoveryClient { private static final String INTERNAL_DOMAIN = "apps.internal";
private final CloudFoundryService cloudFoundryService;
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryAppServiceReactiveDiscoveryClient.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // }
import org.cloudfoundry.operations.CloudFoundryOperations; import reactor.core.publisher.Flux; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties;
/* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Tim Ysewyn * @see <a href="https://github.com/cloudfoundry/cf-app-sd-release">CF App Service * Discovery Release</a> * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class CloudFoundryAppServiceReactiveDiscoveryClient extends CloudFoundryNativeReactiveDiscoveryClient { private static final String INTERNAL_DOMAIN = "apps.internal"; private final CloudFoundryService cloudFoundryService; CloudFoundryAppServiceReactiveDiscoveryClient(CloudFoundryOperations cloudFoundryOperations,
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryAppServiceReactiveDiscoveryClient.java import org.cloudfoundry.operations.CloudFoundryOperations; import reactor.core.publisher.Flux; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; /* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Tim Ysewyn * @see <a href="https://github.com/cloudfoundry/cf-app-sd-release">CF App Service * Discovery Release</a> * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class CloudFoundryAppServiceReactiveDiscoveryClient extends CloudFoundryNativeReactiveDiscoveryClient { private static final String INTERNAL_DOMAIN = "apps.internal"; private final CloudFoundryService cloudFoundryService; CloudFoundryAppServiceReactiveDiscoveryClient(CloudFoundryOperations cloudFoundryOperations,
CloudFoundryService svc, CloudFoundryDiscoveryProperties cloudFoundryDiscoveryProperties) {
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientConfigurationTest.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // }
import org.cloudfoundry.operations.CloudFoundryOperations; import org.junit.Test; import org.mockito.Mockito; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat;
@Test public void testUseContainerIpFalse() { this.contextRunner.withUserConfiguration(CloudFoundryConfig.class) .withPropertyValues("spring.cloud.cloudfoundry.discovery.use-dns=true", "spring.cloud.cloudfoundry.discovery.use-container-ip=false") .run((context) -> { DiscoveryClient discoveryClient = context.getBean(DiscoveryClient.class); assertThat(discoveryClient.getClass()).isEqualTo(CloudFoundryAppServiceDiscoveryClient.class); }); } @Test public void testUseContainerIpTrue() { this.contextRunner.withPropertyValues("spring.cloud.cloudfoundry.discovery.use-dns=true", "spring.cloud.cloudfoundry.discovery.use-container-ip=true").run((context) -> { DiscoveryClient discoveryClient = context.getBean(DiscoveryClient.class); assertThat(discoveryClient.getClass()).isEqualTo(SimpleDnsBasedDiscoveryClient.class); }); } @Configuration(proxyBeanMethods = false) public static class CloudFoundryConfig { @Bean public CloudFoundryOperations cloudFoundryOperations() { return Mockito.mock(CloudFoundryOperations.class); } @Bean
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientConfigurationTest.java import org.cloudfoundry.operations.CloudFoundryOperations; import org.junit.Test; import org.mockito.Mockito; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; @Test public void testUseContainerIpFalse() { this.contextRunner.withUserConfiguration(CloudFoundryConfig.class) .withPropertyValues("spring.cloud.cloudfoundry.discovery.use-dns=true", "spring.cloud.cloudfoundry.discovery.use-container-ip=false") .run((context) -> { DiscoveryClient discoveryClient = context.getBean(DiscoveryClient.class); assertThat(discoveryClient.getClass()).isEqualTo(CloudFoundryAppServiceDiscoveryClient.class); }); } @Test public void testUseContainerIpTrue() { this.contextRunner.withPropertyValues("spring.cloud.cloudfoundry.discovery.use-dns=true", "spring.cloud.cloudfoundry.discovery.use-container-ip=true").run((context) -> { DiscoveryClient discoveryClient = context.getBean(DiscoveryClient.class); assertThat(discoveryClient.getClass()).isEqualTo(SimpleDnsBasedDiscoveryClient.class); }); } @Configuration(proxyBeanMethods = false) public static class CloudFoundryConfig { @Bean public CloudFoundryOperations cloudFoundryOperations() { return Mockito.mock(CloudFoundryOperations.class); } @Bean
public CloudFoundryService cloudFoundryService() {
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryNativeReactiveDiscoveryClient.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // }
import java.util.HashMap; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.InstanceDetail; import reactor.core.publisher.Flux; import reactor.util.function.Tuple2; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties;
/* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Cloud Foundry maintains a registry of running applications which we expose here as * CloudFoundryService instances. * * @author Tim Ysewyn */ public class CloudFoundryNativeReactiveDiscoveryClient implements ReactiveDiscoveryClient { private final CloudFoundryService cloudFoundryService; private final CloudFoundryOperations cloudFoundryOperations;
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryNativeReactiveDiscoveryClient.java import java.util.HashMap; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.InstanceDetail; import reactor.core.publisher.Flux; import reactor.util.function.Tuple2; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; /* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Cloud Foundry maintains a registry of running applications which we expose here as * CloudFoundryService instances. * * @author Tim Ysewyn */ public class CloudFoundryNativeReactiveDiscoveryClient implements ReactiveDiscoveryClient { private final CloudFoundryService cloudFoundryService; private final CloudFoundryOperations cloudFoundryOperations;
private final CloudFoundryDiscoveryProperties properties;
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/SimpleDnsBasedReactiveDiscoveryClient.java
// Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // }
import java.net.InetAddress; import java.net.UnknownHostException; import java.util.function.Function; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties;
/* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Reactive Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Tim Ysewyn * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class SimpleDnsBasedReactiveDiscoveryClient implements ReactiveDiscoveryClient { private static final Logger log = LoggerFactory.getLogger(SimpleDnsBasedReactiveDiscoveryClient.class); private final ServiceIdToHostnameConverter serviceIdToHostnameConverter; public SimpleDnsBasedReactiveDiscoveryClient(ServiceIdToHostnameConverter serviceIdToHostnameConverter) { this.serviceIdToHostnameConverter = serviceIdToHostnameConverter; }
// Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/reactive/SimpleDnsBasedReactiveDiscoveryClient.java import java.net.InetAddress; import java.net.UnknownHostException; import java.util.function.Function; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; /* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * Reactive Discovery Client implementation using Cloud Foundry's Native DNS based Service * Discovery. * * @author Tim Ysewyn * @see <a href= * "https://www.cloudfoundry.org/blog/polyglot-service-discovery-container-networking-cloud-foundry/">Polyglot * Service Discovery for Container Networking in Cloud Foundry</a> */ public class SimpleDnsBasedReactiveDiscoveryClient implements ReactiveDiscoveryClient { private static final Logger log = LoggerFactory.getLogger(SimpleDnsBasedReactiveDiscoveryClient.class); private final ServiceIdToHostnameConverter serviceIdToHostnameConverter; public SimpleDnsBasedReactiveDiscoveryClient(ServiceIdToHostnameConverter serviceIdToHostnameConverter) { this.serviceIdToHostnameConverter = serviceIdToHostnameConverter; }
public SimpleDnsBasedReactiveDiscoveryClient(CloudFoundryDiscoveryProperties properties) {
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientTest.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // }
import java.util.List; import java.util.UUID; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.Applications; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import reactor.core.publisher.Flux; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock;
/* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Josh Long */ public class CloudFoundryDiscoveryClientTest { private final Log log = LogFactory.getLog(getClass()); private CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient; private String hiServiceServiceId = "hi-service"; private CloudFoundryOperations ops;
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryClientTest.java import java.util.List; import java.util.UUID; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.Applications; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import reactor.core.publisher.Flux; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /* * Copyright 2013-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery; /** * @author Josh Long */ public class CloudFoundryDiscoveryClientTest { private final Log log = LogFactory.getLog(getClass()); private CloudFoundryDiscoveryClient cloudFoundryDiscoveryClient; private String hiServiceServiceId = "hi-service"; private CloudFoundryOperations ops;
private CloudFoundryService svc;
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryNativeReactiveDiscoveryClientTests.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // }
import java.util.UUID; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.Applications; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * @author Tim Ysewyn */ @ExtendWith(MockitoExtension.class) class CloudFoundryNativeReactiveDiscoveryClientTests { @Mock private CloudFoundryOperations operations; @Mock
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryNativeReactiveDiscoveryClientTests.java import java.util.UUID; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.Applications; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * @author Tim Ysewyn */ @ExtendWith(MockitoExtension.class) class CloudFoundryNativeReactiveDiscoveryClientTests { @Mock private CloudFoundryOperations operations; @Mock
private CloudFoundryService svc;
spring-cloud/spring-cloud-cloudfoundry
spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryNativeReactiveDiscoveryClientTests.java
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // }
import java.util.UUID; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.Applications; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * @author Tim Ysewyn */ @ExtendWith(MockitoExtension.class) class CloudFoundryNativeReactiveDiscoveryClientTests { @Mock private CloudFoundryOperations operations; @Mock private CloudFoundryService svc; @Mock
// Path: spring-cloud-cloudfoundry-commons/src/main/java/org/springframework/cloud/cloudfoundry/CloudFoundryService.java // public class CloudFoundryService { // // private final CloudFoundryOperations cloudFoundryOperations; // // public CloudFoundryService(CloudFoundryOperations cloudFoundryOperations) { // this.cloudFoundryOperations = cloudFoundryOperations; // } // // public Flux<Tuple2<ApplicationDetail, InstanceDetail>> getApplicationInstances(String serviceId) { // GetApplicationRequest applicationRequest = GetApplicationRequest.builder().name(serviceId).build(); // return this.cloudFoundryOperations.applications().get(applicationRequest).flatMapMany(applicationDetail -> { // Flux<InstanceDetail> ids = Flux.fromStream(applicationDetail.getInstanceDetails().stream()) // .filter(id -> id.getState().equalsIgnoreCase("RUNNING")); // Flux<ApplicationDetail> generate = Flux.generate(sink -> sink.next(applicationDetail)); // return generate.zipWith(ids); // }); // } // // } // // Path: spring-cloud-cloudfoundry-discovery/src/main/java/org/springframework/cloud/cloudfoundry/discovery/CloudFoundryDiscoveryProperties.java // @ConfigurationProperties(prefix = "spring.cloud.cloudfoundry.discovery") // public class CloudFoundryDiscoveryProperties { // // /** // * Flag to indicate that discovery is enabled. // */ // private boolean enabled = true; // // /** // * Frequency in milliseconds of poll for heart beat. The client will poll on this // * frequency and broadcast a list of service ids. // */ // private long heartbeatFrequency = 5000; // // /** // * Port to use when no port is defined by service discovery. // */ // private int defaultServerPort = 80; // // /** // * Order of the discovery client used by `CompositeDiscoveryClient` for sorting // * available clients. // */ // private int order = 0; // // /** // * Default internal domain when configured to use Native DNS service discovery. // */ // private String internalDomain = "apps.internal"; // // public boolean isEnabled() { // return this.enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public long getHeartbeatFrequency() { // return this.heartbeatFrequency; // } // // public void setHeartbeatFrequency(long heartbeatFrequency) { // this.heartbeatFrequency = heartbeatFrequency; // } // // public int getDefaultServerPort() { // return this.defaultServerPort; // } // // public void setDefaultServerPort(int defaultServerPort) { // this.defaultServerPort = defaultServerPort; // } // // public int getOrder() { // return this.order; // } // // public void setOrder(int order) { // this.order = order; // } // // public String getInternalDomain() { // return this.internalDomain; // } // // public void setInternalDomain(String internalDomain) { // this.internalDomain = internalDomain; // } // // @Override // public String toString() { // // @formatter:off // return new ToStringCreator(this) // .append("enabled", enabled) // .append("heartbeatFrequency", heartbeatFrequency) // .append("defaultServerPort", defaultServerPort) // .append("order", order) // .append("internalDomain", internalDomain) // .toString(); // // @formatter:on // } // // } // Path: spring-cloud-cloudfoundry-discovery/src/test/java/org/springframework/cloud/cloudfoundry/discovery/reactive/CloudFoundryNativeReactiveDiscoveryClientTests.java import java.util.UUID; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.applications.ApplicationDetail; import org.cloudfoundry.operations.applications.ApplicationSummary; import org.cloudfoundry.operations.applications.Applications; import org.cloudfoundry.operations.applications.InstanceDetail; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.cloudfoundry.CloudFoundryService; import org.springframework.cloud.cloudfoundry.discovery.CloudFoundryDiscoveryProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright 2019-2019 the original author or authors. * * 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 * * https://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 org.springframework.cloud.cloudfoundry.discovery.reactive; /** * @author Tim Ysewyn */ @ExtendWith(MockitoExtension.class) class CloudFoundryNativeReactiveDiscoveryClientTests { @Mock private CloudFoundryOperations operations; @Mock private CloudFoundryService svc; @Mock
private CloudFoundryDiscoveryProperties properties;
xpenatan/gdx-bullet-gwt
gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/softbody/btSoftBodyRigidBodyCollisionConfiguration.java
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDefaultCollisionConfiguration.java // public class btDefaultCollisionConfiguration extends btCollisionConfiguration // { // public btDefaultCollisionConfiguration() { // this.jsObject = createObj(); // } // // private native JavaScriptObject createObj() /*-{ // var obj = new $wnd.Ammo.btDefaultCollisionConfiguration(); // return obj; // // $wnd.alert("Hello! I am an alert box!!"); // }-*/; // // // // public native void setVaar(String value) /*-{ // // $wnd.vaar = value; // // }-*/; // // // // public native String getVaar() /*-{ // // return $wnd.vaar; // // }-*/; // // // // public static native String getVaar2() /*-{ // // return $wnd.vaar; // // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDefaultCollisionConstructionInfo.java // public class btDefaultCollisionConstructionInfo extends BulletBase // { // public btDefaultCollisionConstructionInfo() // { // jsObject = createObj(); // } // // private native JavaScriptObject createObj() /*-{ // var obj = new $wnd.Ammo.btDefaultCollisionConstructionInfo(); // obj.javaObject = this; // return obj; // }-*/; // }
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConstructionInfo; import com.google.gwt.core.client.JavaScriptObject;
package com.badlogic.gdx.physics.bullet.softbody; public class btSoftBodyRigidBodyCollisionConfiguration extends btDefaultCollisionConfiguration { public btSoftBodyRigidBodyCollisionConfiguration() { jsObject = createObj(); }
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDefaultCollisionConfiguration.java // public class btDefaultCollisionConfiguration extends btCollisionConfiguration // { // public btDefaultCollisionConfiguration() { // this.jsObject = createObj(); // } // // private native JavaScriptObject createObj() /*-{ // var obj = new $wnd.Ammo.btDefaultCollisionConfiguration(); // return obj; // // $wnd.alert("Hello! I am an alert box!!"); // }-*/; // // // // public native void setVaar(String value) /*-{ // // $wnd.vaar = value; // // }-*/; // // // // public native String getVaar() /*-{ // // return $wnd.vaar; // // }-*/; // // // // public static native String getVaar2() /*-{ // // return $wnd.vaar; // // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDefaultCollisionConstructionInfo.java // public class btDefaultCollisionConstructionInfo extends BulletBase // { // public btDefaultCollisionConstructionInfo() // { // jsObject = createObj(); // } // // private native JavaScriptObject createObj() /*-{ // var obj = new $wnd.Ammo.btDefaultCollisionConstructionInfo(); // obj.javaObject = this; // return obj; // }-*/; // } // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/softbody/btSoftBodyRigidBodyCollisionConfiguration.java import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConstructionInfo; import com.google.gwt.core.client.JavaScriptObject; package com.badlogic.gdx.physics.bullet.softbody; public class btSoftBodyRigidBodyCollisionConfiguration extends btDefaultCollisionConfiguration { public btSoftBodyRigidBodyCollisionConfiguration() { jsObject = createObj(); }
public btSoftBodyRigidBodyCollisionConfiguration(btDefaultCollisionConstructionInfo constructionInfo) {
xpenatan/gdx-bullet-gwt
gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btDiscreteDynamicsWorld.java
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btCollisionConfiguration.java // public class btCollisionConfiguration extends BulletBase // { // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // }
import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject;
package com.badlogic.gdx.physics.bullet.dynamics; public class btDiscreteDynamicsWorld extends btDynamicsWorld { public btDiscreteDynamicsWorld() { }
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btCollisionConfiguration.java // public class btCollisionConfiguration extends BulletBase // { // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // } // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btDiscreteDynamicsWorld.java import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject; package com.badlogic.gdx.physics.bullet.dynamics; public class btDiscreteDynamicsWorld extends btDynamicsWorld { public btDiscreteDynamicsWorld() { }
public btDiscreteDynamicsWorld(btDispatcher dispatcher, btBroadphaseInterface pairCache, btConstraintSolver constraintSolver, btCollisionConfiguration collisionConfiguration)
xpenatan/gdx-bullet-gwt
gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btDiscreteDynamicsWorld.java
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btCollisionConfiguration.java // public class btCollisionConfiguration extends BulletBase // { // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // }
import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject;
package com.badlogic.gdx.physics.bullet.dynamics; public class btDiscreteDynamicsWorld extends btDynamicsWorld { public btDiscreteDynamicsWorld() { }
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btCollisionConfiguration.java // public class btCollisionConfiguration extends BulletBase // { // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // } // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btDiscreteDynamicsWorld.java import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject; package com.badlogic.gdx.physics.bullet.dynamics; public class btDiscreteDynamicsWorld extends btDynamicsWorld { public btDiscreteDynamicsWorld() { }
public btDiscreteDynamicsWorld(btDispatcher dispatcher, btBroadphaseInterface pairCache, btConstraintSolver constraintSolver, btCollisionConfiguration collisionConfiguration)
xpenatan/gdx-bullet-gwt
gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btDiscreteDynamicsWorld.java
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btCollisionConfiguration.java // public class btCollisionConfiguration extends BulletBase // { // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // }
import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject;
package com.badlogic.gdx.physics.bullet.dynamics; public class btDiscreteDynamicsWorld extends btDynamicsWorld { public btDiscreteDynamicsWorld() { }
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btCollisionConfiguration.java // public class btCollisionConfiguration extends BulletBase // { // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // } // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btDiscreteDynamicsWorld.java import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject; package com.badlogic.gdx.physics.bullet.dynamics; public class btDiscreteDynamicsWorld extends btDynamicsWorld { public btDiscreteDynamicsWorld() { }
public btDiscreteDynamicsWorld(btDispatcher dispatcher, btBroadphaseInterface pairCache, btConstraintSolver constraintSolver, btCollisionConfiguration collisionConfiguration)
xpenatan/gdx-bullet-gwt
gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btRaycastVehicle.java
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/BulletBase.java // public class BulletBase implements Disposable // { // public JavaScriptObject jsObject; // public to be able to easily access in js code. // boolean disposed; // // @Override // public void dispose() // { // disposed = true; // if(jsObject != null) // internaldispose(); // jsObject = null; // } // // private native void internaldispose() /*-{ // var bulletBase = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // $wnd.Ammo.destroy(bulletBase); // }-*/; // // public boolean isDisposed() // { // return disposed; // } // // /** Obtains a reference to this object, call release to free the reference. */ // public void obtain() { // } // // /** Release a previously obtained reference, causing the object to be disposed when this was the last reference. */ // public void release() { // } // // /** @return Whether this instance is obtained using the {@link #obtain()} method. */ // public boolean isObtained() { // return false; // } // // protected void construct() { // } // // public void takeOwnership() { // } // }
import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.BulletBase; import com.google.gwt.core.client.JavaScriptObject;
public native float getCurrentSpeedKmHour() /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; return vehicleJS.getCurrentSpeedKmHour(); }-*/; public native void setCoordinateSystem(int rightIndex, int upIndex, int forwardIndex) /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; vehicleJS.setCoordinateSystem(rightIndex, upIndex, forwardIndex); }-*/; public native int getUserConstraintType() /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; return vehicleJS.getUserConstraintType(); }-*/; public native void setUserConstraintType(int userConstraintType) /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; vehicleJS.setUserConstraintType(userConstraintType); }-*/; public native void setUserConstraintId(int uid) /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; vehicleJS.setUserConstraintId(uid); }-*/; public native int getUserConstraintId() /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; return vehicleJS.getUserConstraintId(); }-*/;
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/BulletBase.java // public class BulletBase implements Disposable // { // public JavaScriptObject jsObject; // public to be able to easily access in js code. // boolean disposed; // // @Override // public void dispose() // { // disposed = true; // if(jsObject != null) // internaldispose(); // jsObject = null; // } // // private native void internaldispose() /*-{ // var bulletBase = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // $wnd.Ammo.destroy(bulletBase); // }-*/; // // public boolean isDisposed() // { // return disposed; // } // // /** Obtains a reference to this object, call release to free the reference. */ // public void obtain() { // } // // /** Release a previously obtained reference, causing the object to be disposed when this was the last reference. */ // public void release() { // } // // /** @return Whether this instance is obtained using the {@link #obtain()} method. */ // public boolean isObtained() { // return false; // } // // protected void construct() { // } // // public void takeOwnership() { // } // } // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/dynamics/btRaycastVehicle.java import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.bullet.BulletBase; import com.google.gwt.core.client.JavaScriptObject; public native float getCurrentSpeedKmHour() /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; return vehicleJS.getCurrentSpeedKmHour(); }-*/; public native void setCoordinateSystem(int rightIndex, int upIndex, int forwardIndex) /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; vehicleJS.setCoordinateSystem(rightIndex, upIndex, forwardIndex); }-*/; public native int getUserConstraintType() /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; return vehicleJS.getUserConstraintType(); }-*/; public native void setUserConstraintType(int userConstraintType) /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; vehicleJS.setUserConstraintType(userConstraintType); }-*/; public native void setUserConstraintId(int uid) /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; vehicleJS.setUserConstraintId(uid); }-*/; public native int getUserConstraintId() /*-{ var vehicleJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; return vehicleJS.getUserConstraintId(); }-*/;
static public class btVehicleTuning extends BulletBase {
xpenatan/gdx-bullet-gwt
gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/softbody/btSoftBodyWorldInfo.java
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/BulletBase.java // public class BulletBase implements Disposable // { // public JavaScriptObject jsObject; // public to be able to easily access in js code. // boolean disposed; // // @Override // public void dispose() // { // disposed = true; // if(jsObject != null) // internaldispose(); // jsObject = null; // } // // private native void internaldispose() /*-{ // var bulletBase = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // $wnd.Ammo.destroy(bulletBase); // }-*/; // // public boolean isDisposed() // { // return disposed; // } // // /** Obtains a reference to this object, call release to free the reference. */ // public void obtain() { // } // // /** Release a previously obtained reference, causing the object to be disposed when this was the last reference. */ // public void release() { // } // // /** @return Whether this instance is obtained using the {@link #obtain()} method. */ // public boolean isObtained() { // return false; // } // // protected void construct() { // } // // public void takeOwnership() { // } // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // }
import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject;
package com.badlogic.gdx.physics.bullet.softbody; public class btSoftBodyWorldInfo extends BulletBase { public btSoftBodyWorldInfo() { jsObject = createObj(); } private native JavaScriptObject createObj() /*-{ var obj = new $wnd.Ammo.btSoftBodyWorldInfo(); obj.javaObject = this; return obj; }-*/;
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/BulletBase.java // public class BulletBase implements Disposable // { // public JavaScriptObject jsObject; // public to be able to easily access in js code. // boolean disposed; // // @Override // public void dispose() // { // disposed = true; // if(jsObject != null) // internaldispose(); // jsObject = null; // } // // private native void internaldispose() /*-{ // var bulletBase = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // $wnd.Ammo.destroy(bulletBase); // }-*/; // // public boolean isDisposed() // { // return disposed; // } // // /** Obtains a reference to this object, call release to free the reference. */ // public void obtain() { // } // // /** Release a previously obtained reference, causing the object to be disposed when this was the last reference. */ // public void release() { // } // // /** @return Whether this instance is obtained using the {@link #obtain()} method. */ // public boolean isObtained() { // return false; // } // // protected void construct() { // } // // public void takeOwnership() { // } // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // } // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/softbody/btSoftBodyWorldInfo.java import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject; package com.badlogic.gdx.physics.bullet.softbody; public class btSoftBodyWorldInfo extends BulletBase { public btSoftBodyWorldInfo() { jsObject = createObj(); } private native JavaScriptObject createObj() /*-{ var obj = new $wnd.Ammo.btSoftBodyWorldInfo(); obj.javaObject = this; return obj; }-*/;
public native void setBroadphase(btBroadphaseInterface value) /*-{
xpenatan/gdx-bullet-gwt
gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/softbody/btSoftBodyWorldInfo.java
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/BulletBase.java // public class BulletBase implements Disposable // { // public JavaScriptObject jsObject; // public to be able to easily access in js code. // boolean disposed; // // @Override // public void dispose() // { // disposed = true; // if(jsObject != null) // internaldispose(); // jsObject = null; // } // // private native void internaldispose() /*-{ // var bulletBase = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // $wnd.Ammo.destroy(bulletBase); // }-*/; // // public boolean isDisposed() // { // return disposed; // } // // /** Obtains a reference to this object, call release to free the reference. */ // public void obtain() { // } // // /** Release a previously obtained reference, causing the object to be disposed when this was the last reference. */ // public void release() { // } // // /** @return Whether this instance is obtained using the {@link #obtain()} method. */ // public boolean isObtained() { // return false; // } // // protected void construct() { // } // // public void takeOwnership() { // } // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // }
import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject;
package com.badlogic.gdx.physics.bullet.softbody; public class btSoftBodyWorldInfo extends BulletBase { public btSoftBodyWorldInfo() { jsObject = createObj(); } private native JavaScriptObject createObj() /*-{ var obj = new $wnd.Ammo.btSoftBodyWorldInfo(); obj.javaObject = this; return obj; }-*/; public native void setBroadphase(btBroadphaseInterface value) /*-{ var wInfoJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; var bInterfaceJS = value.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; wInfoJS.set_m_broadphase(bInterfaceJS); }-*/;
// Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/BulletBase.java // public class BulletBase implements Disposable // { // public JavaScriptObject jsObject; // public to be able to easily access in js code. // boolean disposed; // // @Override // public void dispose() // { // disposed = true; // if(jsObject != null) // internaldispose(); // jsObject = null; // } // // private native void internaldispose() /*-{ // var bulletBase = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // $wnd.Ammo.destroy(bulletBase); // }-*/; // // public boolean isDisposed() // { // return disposed; // } // // /** Obtains a reference to this object, call release to free the reference. */ // public void obtain() { // } // // /** Release a previously obtained reference, causing the object to be disposed when this was the last reference. */ // public void release() { // } // // /** @return Whether this instance is obtained using the {@link #obtain()} method. */ // public boolean isObtained() { // return false; // } // // protected void construct() { // } // // public void takeOwnership() { // } // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btBroadphaseInterface.java // public class btBroadphaseInterface extends BulletBase // { // // public native btOverlappingPairCache getOverlappingPairCache() /*-{ // var bpInterfaceJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // var pairCacheJS = bpInterfaceJS.getOverlappingPairCache(); // var pairCache = @com.badlogic.gdx.physics.bullet.Bullet::TMP_btOverlappingPairCache_1; // pairCache.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject = pairCacheJS; // return pairCache; // }-*/; // } // // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/collision/btDispatcher.java // public class btDispatcher extends BulletBase // { // public btPersistentManifold manifold = new btPersistentManifold(); // // public native int getNumManifolds() /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getNumManifolds(); // }-*/; // // public btPersistentManifold getManifoldByIndexInternal(int index) // { // // long cPtr = CollisionJNI.btDispatcher_getManifoldByIndexInternal(swigCPtr, this, index); // // return (cPtr == 0) ? null : new btPersistentManifold(cPtr, false); // // manifold.jsObject = getManifoldByIndexInternall(index); // return manifold; // } // // private native JavaScriptObject getManifoldByIndexInternall(int index) /*-{ // var dispacher = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; // return dispacher.getManifoldByIndexInternal(index); // }-*/; // } // Path: gdx-bullet-gwt/src/com/badlogic/gdx/physics/bullet/gwt/emu/com/badlogic/gdx/physics/bullet/softbody/btSoftBodyWorldInfo.java import com.badlogic.gdx.physics.bullet.BulletBase; import com.badlogic.gdx.physics.bullet.collision.btBroadphaseInterface; import com.badlogic.gdx.physics.bullet.collision.btDispatcher; import com.google.gwt.core.client.JavaScriptObject; package com.badlogic.gdx.physics.bullet.softbody; public class btSoftBodyWorldInfo extends BulletBase { public btSoftBodyWorldInfo() { jsObject = createObj(); } private native JavaScriptObject createObj() /*-{ var obj = new $wnd.Ammo.btSoftBodyWorldInfo(); obj.javaObject = this; return obj; }-*/; public native void setBroadphase(btBroadphaseInterface value) /*-{ var wInfoJS = this.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; var bInterfaceJS = value.@com.badlogic.gdx.physics.bullet.BulletBase::jsObject; wInfoJS.set_m_broadphase(bInterfaceJS); }-*/;
public native void setDispatcher(btDispatcher value) /*-{
apigee/apigee-deploy-maven-plugin
src/main/java/io/apigee/buildTools/enterprise4g/utils/PackageConfigurer.java
// Path: src/main/java/io/apigee/buildTools/enterprise4g/utils/ConfigTokens.java // public class Policy { // // @Key // public String name; // @Key // public List<Token> tokens; // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public List<Token> getTokens() { // return tokens; // } // public void setTokens(List<Token> tokens) { // this.tokens = tokens; // } // }
import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.apigee.buildTools.enterprise4g.utils.ConfigTokens.Policy; import java.io.File; import java.util.List; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element;
/** * Copyright (C) 2014 Apigee Corporation * * 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 io.apigee.buildTools.enterprise4g.utils; /** * updates the configuration values of a package * * @author sdey */ public class PackageConfigurer { public static void configurePackage(String env, File configFile) throws Exception { Logger logger = LogManager.getLogger(PackageConfigurer.class); TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); // get the list of files in proxies folder XMLFileListUtil listFileUtil = new XMLFileListUtil(); List<File> fileList = listFileUtil.getProxyFiles(configFile); FileReader fileutil = new FileReader(); ConfigTokens conf = fileutil.getBundleConfigs(configFile); for (int i = 0; i < fileList.size(); i++) { Document xmlDoc = fileutil.getXMLDocument(fileList.get(i)); try {
// Path: src/main/java/io/apigee/buildTools/enterprise4g/utils/ConfigTokens.java // public class Policy { // // @Key // public String name; // @Key // public List<Token> tokens; // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public List<Token> getTokens() { // return tokens; // } // public void setTokens(List<Token> tokens) { // this.tokens = tokens; // } // } // Path: src/main/java/io/apigee/buildTools/enterprise4g/utils/PackageConfigurer.java import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.apigee.buildTools.enterprise4g.utils.ConfigTokens.Policy; import java.io.File; import java.util.List; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Copyright (C) 2014 Apigee Corporation * * 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 io.apigee.buildTools.enterprise4g.utils; /** * updates the configuration values of a package * * @author sdey */ public class PackageConfigurer { public static void configurePackage(String env, File configFile) throws Exception { Logger logger = LogManager.getLogger(PackageConfigurer.class); TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); // get the list of files in proxies folder XMLFileListUtil listFileUtil = new XMLFileListUtil(); List<File> fileList = listFileUtil.getProxyFiles(configFile); FileReader fileutil = new FileReader(); ConfigTokens conf = fileutil.getBundleConfigs(configFile); for (int i = 0; i < fileList.size(); i++) { Document xmlDoc = fileutil.getXMLDocument(fileList.get(i)); try {
Policy configTokens = conf.getConfigbyEnv(env)
apigee/apigee-deploy-maven-plugin
src/main/java/io/apigee/buildTools/enterprise4g/utils/ServerProfile.java
// Path: src/main/java/io/apigee/buildTools/enterprise4g/rest/ActionFlags.java // public enum ActionFlags { // // VALIDATE, // UPDATE, // CLEAN, // INACTIVE, // OVERRIDE, // FORCE; // // public static ActionFlags valueOfIgnoreCase(String flag) { // return ActionFlags.valueOf(flag.toUpperCase()); // } // // // }
import io.apigee.buildTools.enterprise4g.rest.ActionFlags; import org.apache.http.client.HttpClient; import java.util.EnumSet;
/** * Copyright (C) 2014 Apigee Corporation * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.apigee.buildTools.enterprise4g.utils; public class ServerProfile { // general configuration private String hostURL; // hostname & scheme e.g. https://api.enterprise.apigee.com private String org; private String environment; // prod or test private String api_version; // v2 or v1 in the server url // authentication bits private String tokenURL; // Mgmt API OAuth token endpoint private String mfaToken; // Mgmt API OAuth MFA - TOTP private String clientId; //Mgmt API OAuth Client Id (optional) private String clientSecret; //Mgmt API OAuth Client Secret (optional) private String bearerToken; //Mgmt API OAuth Token private String refreshToken; //Mgmt API OAuth Refresh Token private String authType; // Mgmt API Auth Type oauth|basic private String credential_user; private String credential_pwd; // // packaging configuration private String bundle_zip_full_path; private String profileId; //Profile id as in parent pom
// Path: src/main/java/io/apigee/buildTools/enterprise4g/rest/ActionFlags.java // public enum ActionFlags { // // VALIDATE, // UPDATE, // CLEAN, // INACTIVE, // OVERRIDE, // FORCE; // // public static ActionFlags valueOfIgnoreCase(String flag) { // return ActionFlags.valueOf(flag.toUpperCase()); // } // // // } // Path: src/main/java/io/apigee/buildTools/enterprise4g/utils/ServerProfile.java import io.apigee.buildTools.enterprise4g.rest.ActionFlags; import org.apache.http.client.HttpClient; import java.util.EnumSet; /** * Copyright (C) 2014 Apigee Corporation * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.apigee.buildTools.enterprise4g.utils; public class ServerProfile { // general configuration private String hostURL; // hostname & scheme e.g. https://api.enterprise.apigee.com private String org; private String environment; // prod or test private String api_version; // v2 or v1 in the server url // authentication bits private String tokenURL; // Mgmt API OAuth token endpoint private String mfaToken; // Mgmt API OAuth MFA - TOTP private String clientId; //Mgmt API OAuth Client Id (optional) private String clientSecret; //Mgmt API OAuth Client Secret (optional) private String bearerToken; //Mgmt API OAuth Token private String refreshToken; //Mgmt API OAuth Refresh Token private String authType; // Mgmt API Auth Type oauth|basic private String credential_user; private String credential_pwd; // // packaging configuration private String bundle_zip_full_path; private String profileId; //Profile id as in parent pom
private EnumSet<ActionFlags> actions = EnumSet.noneOf(ActionFlags.class);
apigee/apigee-deploy-maven-plugin
src/test/java/io/apigee/buildTools/enterprise4g/rest/ActionFlagsTest.java
// Path: src/main/java/io/apigee/buildTools/enterprise4g/rest/ActionFlags.java // public enum ActionFlags { // // VALIDATE, // UPDATE, // CLEAN, // INACTIVE, // OVERRIDE, // FORCE; // // public static ActionFlags valueOfIgnoreCase(String flag) { // return ActionFlags.valueOf(flag.toUpperCase()); // } // // // }
import static org.junit.Assert.*; import org.junit.Test; import java.util.EnumSet; import static io.apigee.buildTools.enterprise4g.rest.ActionFlags.*;
/** * Copyright (C) 2014 Apigee Corporation * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.apigee.buildTools.enterprise4g.rest; public class ActionFlagsTest { @Test public void testActionSetFill() {
// Path: src/main/java/io/apigee/buildTools/enterprise4g/rest/ActionFlags.java // public enum ActionFlags { // // VALIDATE, // UPDATE, // CLEAN, // INACTIVE, // OVERRIDE, // FORCE; // // public static ActionFlags valueOfIgnoreCase(String flag) { // return ActionFlags.valueOf(flag.toUpperCase()); // } // // // } // Path: src/test/java/io/apigee/buildTools/enterprise4g/rest/ActionFlagsTest.java import static org.junit.Assert.*; import org.junit.Test; import java.util.EnumSet; import static io.apigee.buildTools.enterprise4g.rest.ActionFlags.*; /** * Copyright (C) 2014 Apigee Corporation * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.apigee.buildTools.enterprise4g.rest; public class ActionFlagsTest { @Test public void testActionSetFill() {
EnumSet<ActionFlags> set = EnumSet.noneOf(ActionFlags.class);
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/SwitchSegmentImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // }
import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.RaspiPin; import osgi.enroute.trains.controller.api.SwitchSegmentController;
package osgi.enroute.trains.hw.provider; @Designate(ocd = SwitchSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.switch", property = "service.exported.interfaces=*", configurationPolicy = ConfigurationPolicy.REQUIRE)
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/SwitchSegmentImpl.java import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.RaspiPin; import osgi.enroute.trains.controller.api.SwitchSegmentController; package osgi.enroute.trains.hw.provider; @Designate(ocd = SwitchSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.switch", property = "service.exported.interfaces=*", configurationPolicy = ConfigurationPolicy.REQUIRE)
public class SwitchSegmentImpl implements SwitchSegmentController {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.application/src/osgi/enroute/trains/application/SegmentPosition.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // }
import org.osgi.dto.DTO; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Segment;
package osgi.enroute.trains.application; public class SegmentPosition extends DTO { public enum Symbol { SWITCH, MERGE, SIGNAL,LOCATOR, BLOCK,PLAIN; }
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // Path: osgi.enroute.trains.application/src/osgi/enroute/trains/application/SegmentPosition.java import org.osgi.dto.DTO; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Segment; package osgi.enroute.trains.application; public class SegmentPosition extends DTO { public enum Symbol { SWITCH, MERGE, SIGNAL,LOCATOR, BLOCK,PLAIN; }
public Segment segment;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.application/src/osgi/enroute/trains/application/SegmentPosition.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // }
import org.osgi.dto.DTO; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Segment;
package osgi.enroute.trains.application; public class SegmentPosition extends DTO { public enum Symbol { SWITCH, MERGE, SIGNAL,LOCATOR, BLOCK,PLAIN; } public Segment segment; public int x=-1, y=0, width=1; public Symbol symbol; public boolean alt = false; public String rfid;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // Path: osgi.enroute.trains.application/src/osgi/enroute/trains/application/SegmentPosition.java import org.osgi.dto.DTO; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Segment; package osgi.enroute.trains.application; public class SegmentPosition extends DTO { public enum Symbol { SWITCH, MERGE, SIGNAL,LOCATOR, BLOCK,PLAIN; } public Segment segment; public int x=-1, y=0, width=1; public Symbol symbol; public boolean alt = false; public String rfid;
public Color color = Color.RED;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.emulator.provider/src/osgi/enroute/trains/emulator/provider/Traverse.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // }
import java.io.Closeable; import org.osgi.framework.BundleContext; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler;
package osgi.enroute.trains.emulator.provider; public interface Traverse extends Closeable { Traverse next(String rfid); Traverse prev(String rfid); void register(BundleContext context); int l(); default boolean isBlocked() { return false; }
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // } // Path: osgi.enroute.trains.emulator.provider/src/osgi/enroute/trains/emulator/provider/Traverse.java import java.io.Closeable; import org.osgi.framework.BundleContext; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler; package osgi.enroute.trains.emulator.provider; public interface Traverse extends Closeable { Traverse next(String rfid); Traverse prev(String rfid); void register(BundleContext context); int l(); default boolean isBlocked() { return false; }
default Segment getSegment() {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.emulator.provider/src/osgi/enroute/trains/emulator/provider/Traverse.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // }
import java.io.Closeable; import org.osgi.framework.BundleContext; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler;
package osgi.enroute.trains.emulator.provider; public interface Traverse extends Closeable { Traverse next(String rfid); Traverse prev(String rfid); void register(BundleContext context); int l(); default boolean isBlocked() { return false; } default Segment getSegment() {
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // } // Path: osgi.enroute.trains.emulator.provider/src/osgi/enroute/trains/emulator/provider/Traverse.java import java.io.Closeable; import org.osgi.framework.BundleContext; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler; package osgi.enroute.trains.emulator.provider; public interface Traverse extends Closeable { Traverse next(String rfid); Traverse prev(String rfid); void register(BundleContext context); int l(); default boolean isBlocked() { return false; } default Segment getSegment() {
SegmentHandler<?> sh = (SegmentHandler<?>)this;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/SignalSegmentImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // }
import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.RaspiPin; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SignalSegmentController;
package osgi.enroute.trains.hw.provider; @Designate(ocd = SignalSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.signal", property = "service.exported.interfaces=*", configurationPolicy = ConfigurationPolicy.REQUIRE)
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/SignalSegmentImpl.java import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.RaspiPin; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SignalSegmentController; package osgi.enroute.trains.hw.provider; @Designate(ocd = SignalSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.signal", property = "service.exported.interfaces=*", configurationPolicy = ConfigurationPolicy.REQUIRE)
public class SignalSegmentImpl implements SignalSegmentController {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/SignalSegmentImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // }
import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.RaspiPin; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SignalSegmentController;
package osgi.enroute.trains.hw.provider; @Designate(ocd = SignalSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.signal", property = "service.exported.interfaces=*", configurationPolicy = ConfigurationPolicy.REQUIRE) public class SignalSegmentImpl implements SignalSegmentController { private GpioPinDigitalOutput green; private GpioPinDigitalOutput red;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/SignalSegmentImpl.java import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.RaspiPin; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SignalSegmentController; package osgi.enroute.trains.hw.provider; @Designate(ocd = SignalSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.signal", property = "service.exported.interfaces=*", configurationPolicy = ConfigurationPolicy.REQUIRE) public class SignalSegmentImpl implements SignalSegmentController { private GpioPinDigitalOutput green; private GpioPinDigitalOutput red;
private Color color;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.location.provider/src/osgi/enroute/trains/location/provider/TrainLocationClient.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/TrainLocator.java // public interface TrainLocator { // // /** // * get train location. Promise is resolved when train passes next location. // * @return colon separated string "trainId:segmentName" // */ // Promise<String> nextLocation(); // }
import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackForSegment; import osgi.enroute.trains.controller.api.TrainLocator;
package osgi.enroute.trains.location.provider; @Designate(ocd = LocationConfig.class) @Component(name = LocationConfig.LOCATION_CONFIG_PID, configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/TrainLocator.java // public interface TrainLocator { // // /** // * get train location. Promise is resolved when train passes next location. // * @return colon separated string "trainId:segmentName" // */ // Promise<String> nextLocation(); // } // Path: osgi.enroute.trains.location.provider/src/osgi/enroute/trains/location/provider/TrainLocationClient.java import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackForSegment; import osgi.enroute.trains.controller.api.TrainLocator; package osgi.enroute.trains.location.provider; @Designate(ocd = LocationConfig.class) @Component(name = LocationConfig.LOCATION_CONFIG_PID, configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
public class TrainLocationClient implements TrainLocator {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.location.provider/src/osgi/enroute/trains/location/provider/TrainLocationClient.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/TrainLocator.java // public interface TrainLocator { // // /** // * get train location. Promise is resolved when train passes next location. // * @return colon separated string "trainId:segmentName" // */ // Promise<String> nextLocation(); // }
import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackForSegment; import osgi.enroute.trains.controller.api.TrainLocator;
package osgi.enroute.trains.location.provider; @Designate(ocd = LocationConfig.class) @Component(name = LocationConfig.LOCATION_CONFIG_PID, configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true) public class TrainLocationClient implements TrainLocator { static final Logger log = LoggerFactory.getLogger(TrainLocationClient.class); private static final String BROKER_URL = "tcp://iot.eclipse.org:1883"; private static final String USERNAME = ""; private static final String PASSWORD = ""; private static final String CLIENT_ID = "TrainLocator"; private MqttClient mqttClient = null; private Map<String, Integer> tag2code = new HashMap<>(); private Map<Integer, String> code2segment = new HashMap<>(); private Deferred<String> nextLocation = new Deferred<String>(); @Reference
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/TrainLocator.java // public interface TrainLocator { // // /** // * get train location. Promise is resolved when train passes next location. // * @return colon separated string "trainId:segmentName" // */ // Promise<String> nextLocation(); // } // Path: osgi.enroute.trains.location.provider/src/osgi/enroute/trains/location/provider/TrainLocationClient.java import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackForSegment; import osgi.enroute.trains.controller.api.TrainLocator; package osgi.enroute.trains.location.provider; @Designate(ocd = LocationConfig.class) @Component(name = LocationConfig.LOCATION_CONFIG_PID, configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true) public class TrainLocationClient implements TrainLocator { static final Logger log = LoggerFactory.getLogger(TrainLocationClient.class); private static final String BROKER_URL = "tcp://iot.eclipse.org:1883"; private static final String USERNAME = ""; private static final String PASSWORD = ""; private static final String CLIENT_ID = "TrainLocator"; private MqttClient mqttClient = null; private Map<String, Integer> tag2code = new HashMap<>(); private Map<Integer, String> code2segment = new HashMap<>(); private Deferred<String> nextLocation = new Deferred<String>(); @Reference
private TrackForSegment trackInfo;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.location.provider/src/osgi/enroute/trains/location/provider/TrainLocationClient.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/TrainLocator.java // public interface TrainLocator { // // /** // * get train location. Promise is resolved when train passes next location. // * @return colon separated string "trainId:segmentName" // */ // Promise<String> nextLocation(); // }
import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackForSegment; import osgi.enroute.trains.controller.api.TrainLocator;
} for (String s : code2tag) { String[] split = s.split("\\s*:\\s*", 2); String tag = split[1]; int code = 0; try { code = Integer.parseInt(split[0]); } catch (NumberFormatException e) { error("non-numeric code<{}> for tag<{}>", split[0], tag); continue; } if (tag2code.containsValue(code)) { final int c = code; List<String> keys = tag2code.entrySet().stream() .filter(e -> e.getValue().equals(c)) .map(e -> e.getKey()) .collect(Collectors.toList()); keys.add(tag); warn("duplicate code {} for tags {}", code, keys); } else { Integer dup = tag2code.put(tag, code); if (dup != null && dup != 0) { warn("duplicate codes [{}, {}] for tag {}", dup, code, tag); } } }
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/TrainLocator.java // public interface TrainLocator { // // /** // * get train location. Promise is resolved when train passes next location. // * @return colon separated string "trainId:segmentName" // */ // Promise<String> nextLocation(); // } // Path: osgi.enroute.trains.location.provider/src/osgi/enroute/trains/location/provider/TrainLocationClient.java import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackForSegment; import osgi.enroute.trains.controller.api.TrainLocator; } for (String s : code2tag) { String[] split = s.split("\\s*:\\s*", 2); String tag = split[1]; int code = 0; try { code = Integer.parseInt(split[0]); } catch (NumberFormatException e) { error("non-numeric code<{}> for tag<{}>", split[0], tag); continue; } if (tag2code.containsValue(code)) { final int c = code; List<String> keys = tag2code.entrySet().stream() .filter(e -> e.getValue().equals(c)) .map(e -> e.getKey()) .collect(Collectors.toList()); keys.add(tag); warn("duplicate code {} for tags {}", code, keys); } else { Integer dup = tag2code.put(tag, code); if (dup != null && dup != 0) { warn("duplicate codes [{}, {}] for tag {}", dup, code, tag); } } }
for (Segment s : trackInfo.getSegments().values()) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/RFIDSegmentImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/RFIDSegmentController.java // public interface RFIDSegmentController extends SegmentController { // // /** // * Return the last seen RFID // */ // String lastRFID(); // // /** // * Read an RFID. Resolves the promise when a new RFID is read. // * @return // */ // Promise<String> nextRFID(); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.controller.api.RFIDSegmentController;
package osgi.enroute.trains.hw.provider; /** * The RFID segment controller connects an RFID reader to a segment and reads out an rfid tag connected * to the train. * * @deprecated As of CeBit 2016 we have changed to an inverse model where the RFID reader is mounted * on the train and RFID tags are spread around the track. * * @author tverbele * */ @Designate(ocd = RFIDSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.rfid", immediate = true, property = { "service.exported.interfaces=*", // Debug.COMMAND_SCOPE + "=rfid", // Debug.COMMAND_FUNCTION + "=lastrfid" }, // configurationPolicy = ConfigurationPolicy.REQUIRE)
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/RFIDSegmentController.java // public interface RFIDSegmentController extends SegmentController { // // /** // * Return the last seen RFID // */ // String lastRFID(); // // /** // * Read an RFID. Resolves the promise when a new RFID is read. // * @return // */ // Promise<String> nextRFID(); // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/RFIDSegmentImpl.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.controller.api.RFIDSegmentController; package osgi.enroute.trains.hw.provider; /** * The RFID segment controller connects an RFID reader to a segment and reads out an rfid tag connected * to the train. * * @deprecated As of CeBit 2016 we have changed to an inverse model where the RFID reader is mounted * on the train and RFID tags are spread around the track. * * @author tverbele * */ @Designate(ocd = RFIDSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.rfid", immediate = true, property = { "service.exported.interfaces=*", // Debug.COMMAND_SCOPE + "=rfid", // Debug.COMMAND_FUNCTION + "=lastrfid" }, // configurationPolicy = ConfigurationPolicy.REQUIRE)
public class RFIDSegmentImpl implements RFIDSegmentController, Runnable {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Passenger.java // public class Passenger extends DTO { // // // which person // public Person person; // // // on which train the passenger is currently on? // public String onTrain = null; // // // in which station the passenger is currently waiting? // public String inStation = null; // // // passenger destination // public String destination = null; // // }
import java.util.List; import osgi.enroute.trains.passenger.api.Passenger;
package osgi.enroute.trains.stations.api; /** * StationsManager provides an API for managing the stations and people traveling from * Station A to B. A person can check in at a station with a planned destination * by calling checkIn(). * * TrainOperators that have a train arriving at a station can call unboard/board to * let passengers hop off/on the train. * * The StationsManager will publish CheckIn/CheckOut events when a person checks in/out * of a station. * * The StationsManager should also update the PassengersStatistics as persons visit stations. * * @author tverbele * */ public interface StationsManager { /** * List all known stations * @return */ List<Station> getStations(); /** * Return the segment for this station * @param station * @return */ String getStationSegment(String station); /** * Return the station for this segment */ String getStation(String segment); /** * List the passengers currently waiting in a station * @param station * @return */
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Passenger.java // public class Passenger extends DTO { // // // which person // public Person person; // // // on which train the passenger is currently on? // public String onTrain = null; // // // in which station the passenger is currently waiting? // public String inStation = null; // // // passenger destination // public String destination = null; // // } // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java import java.util.List; import osgi.enroute.trains.passenger.api.Passenger; package osgi.enroute.trains.stations.api; /** * StationsManager provides an API for managing the stations and people traveling from * Station A to B. A person can check in at a station with a planned destination * by calling checkIn(). * * TrainOperators that have a train arriving at a station can call unboard/board to * let passengers hop off/on the train. * * The StationsManager will publish CheckIn/CheckOut events when a person checks in/out * of a station. * * The StationsManager should also update the PassengersStatistics as persons visit stations. * * @author tverbele * */ public interface StationsManager { /** * List all known stations * @return */ List<Station> getStations(); /** * Return the segment for this station * @param station * @return */ String getStationSegment(String station); /** * Return the station for this segment */ String getStation(String segment); /** * List the passengers currently waiting in a station * @param station * @return */
List<Passenger> getPassengersWaiting(String station);
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Switch.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SwitchHandler<T> extends SegmentHandler<T> { // public SegmentHandler<T> altNext; // public SegmentHandler<T> altPrev; // public boolean toAlternate; // // public SwitchHandler(Segment segment) { // super(segment); // } // // @Override // public Collection<SegmentHandler<T>> move(boolean forward) { // if (forward) { // if (altNext == null) // return super.move(true); // else // return Arrays.asList(next, altNext); // } else { // if (altPrev == null) // return super.move(false); // else // return Arrays.asList(prev, altPrev); // } // } // // @Override // public boolean isMerge() { // return altPrev != null; // } // // @Override // public boolean isSwitch() { // return altNext != null; // } // // @Override // public boolean isPlain() { // return false; // } // // @Override // boolean isPrevAlt(SegmentHandler<T> prev) { // return prev == altPrev; // } // // protected int length() { // return toAlternate ? 35 : 32; // } // // public void setToAlternate(boolean alternate) { // this.toAlternate = alternate; // } // // public boolean event(Observation e) { // switch (e.type) { // case SWITCH: // setToAlternate(e.alternate); // return true; // // default: // return super.event(e); // } // } // }
import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SwitchHandler;
package osgi.enroute.trains.track.manager.example.provider; class Switch extends SwitchHandler<Object> { private ExampleTrackManagerImpl owner;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SwitchHandler<T> extends SegmentHandler<T> { // public SegmentHandler<T> altNext; // public SegmentHandler<T> altPrev; // public boolean toAlternate; // // public SwitchHandler(Segment segment) { // super(segment); // } // // @Override // public Collection<SegmentHandler<T>> move(boolean forward) { // if (forward) { // if (altNext == null) // return super.move(true); // else // return Arrays.asList(next, altNext); // } else { // if (altPrev == null) // return super.move(false); // else // return Arrays.asList(prev, altPrev); // } // } // // @Override // public boolean isMerge() { // return altPrev != null; // } // // @Override // public boolean isSwitch() { // return altNext != null; // } // // @Override // public boolean isPlain() { // return false; // } // // @Override // boolean isPrevAlt(SegmentHandler<T> prev) { // return prev == altPrev; // } // // protected int length() { // return toAlternate ? 35 : 32; // } // // public void setToAlternate(boolean alternate) { // this.toAlternate = alternate; // } // // public boolean event(Observation e) { // switch (e.type) { // case SWITCH: // setToAlternate(e.alternate); // return true; // // default: // return super.event(e); // } // } // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Switch.java import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SwitchHandler; package osgi.enroute.trains.track.manager.example.provider; class Switch extends SwitchHandler<Object> { private ExampleTrackManagerImpl owner;
public Switch(ExampleTrackManagerImpl owner, Segment segment) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Switch.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SwitchHandler<T> extends SegmentHandler<T> { // public SegmentHandler<T> altNext; // public SegmentHandler<T> altPrev; // public boolean toAlternate; // // public SwitchHandler(Segment segment) { // super(segment); // } // // @Override // public Collection<SegmentHandler<T>> move(boolean forward) { // if (forward) { // if (altNext == null) // return super.move(true); // else // return Arrays.asList(next, altNext); // } else { // if (altPrev == null) // return super.move(false); // else // return Arrays.asList(prev, altPrev); // } // } // // @Override // public boolean isMerge() { // return altPrev != null; // } // // @Override // public boolean isSwitch() { // return altNext != null; // } // // @Override // public boolean isPlain() { // return false; // } // // @Override // boolean isPrevAlt(SegmentHandler<T> prev) { // return prev == altPrev; // } // // protected int length() { // return toAlternate ? 35 : 32; // } // // public void setToAlternate(boolean alternate) { // this.toAlternate = alternate; // } // // public boolean event(Observation e) { // switch (e.type) { // case SWITCH: // setToAlternate(e.alternate); // return true; // // default: // return super.event(e); // } // } // }
import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SwitchHandler;
package osgi.enroute.trains.track.manager.example.provider; class Switch extends SwitchHandler<Object> { private ExampleTrackManagerImpl owner; public Switch(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; } public void alternative(boolean toAlternate) { this.toAlternate = toAlternate;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SwitchHandler<T> extends SegmentHandler<T> { // public SegmentHandler<T> altNext; // public SegmentHandler<T> altPrev; // public boolean toAlternate; // // public SwitchHandler(Segment segment) { // super(segment); // } // // @Override // public Collection<SegmentHandler<T>> move(boolean forward) { // if (forward) { // if (altNext == null) // return super.move(true); // else // return Arrays.asList(next, altNext); // } else { // if (altPrev == null) // return super.move(false); // else // return Arrays.asList(prev, altPrev); // } // } // // @Override // public boolean isMerge() { // return altPrev != null; // } // // @Override // public boolean isSwitch() { // return altNext != null; // } // // @Override // public boolean isPlain() { // return false; // } // // @Override // boolean isPrevAlt(SegmentHandler<T> prev) { // return prev == altPrev; // } // // protected int length() { // return toAlternate ? 35 : 32; // } // // public void setToAlternate(boolean alternate) { // this.toAlternate = alternate; // } // // public boolean event(Observation e) { // switch (e.type) { // case SWITCH: // setToAlternate(e.alternate); // return true; // // default: // return super.event(e); // } // } // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Switch.java import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SwitchHandler; package osgi.enroute.trains.track.manager.example.provider; class Switch extends SwitchHandler<Object> { private ExampleTrackManagerImpl owner; public Switch(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; } public void alternative(boolean toAlternate) { this.toAlternate = toAlternate;
Observation o = new Observation();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Locator.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class LocatorHandler<T> extends SegmentHandler<T> { // public String lastSeenId; // public long time; // // public LocatorHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case LOCATED: // setTrain(e.train); // return true; // // default: // return super.event(e); // } // } // // public void setTrain(String rfid) { // this.lastSeenId = rfid; // } // // public boolean isLocator() { // return true; // } // }
import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.LocatorHandler;
package osgi.enroute.trains.track.manager.example.provider; class Locator extends LocatorHandler<Object> { private ExampleTrackManagerImpl owner;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class LocatorHandler<T> extends SegmentHandler<T> { // public String lastSeenId; // public long time; // // public LocatorHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case LOCATED: // setTrain(e.train); // return true; // // default: // return super.event(e); // } // } // // public void setTrain(String rfid) { // this.lastSeenId = rfid; // } // // public boolean isLocator() { // return true; // } // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Locator.java import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.LocatorHandler; package osgi.enroute.trains.track.manager.example.provider; class Locator extends LocatorHandler<Object> { private ExampleTrackManagerImpl owner;
public Locator(ExampleTrackManagerImpl owner, Segment segment) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Locator.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class LocatorHandler<T> extends SegmentHandler<T> { // public String lastSeenId; // public long time; // // public LocatorHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case LOCATED: // setTrain(e.train); // return true; // // default: // return super.event(e); // } // } // // public void setTrain(String rfid) { // this.lastSeenId = rfid; // } // // public boolean isLocator() { // return true; // } // }
import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.LocatorHandler;
package osgi.enroute.trains.track.manager.example.provider; class Locator extends LocatorHandler<Object> { private ExampleTrackManagerImpl owner; public Locator(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; } public void locatedAt(String rfid) { lastSeenId = rfid;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class LocatorHandler<T> extends SegmentHandler<T> { // public String lastSeenId; // public long time; // // public LocatorHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case LOCATED: // setTrain(e.train); // return true; // // default: // return super.event(e); // } // } // // public void setTrain(String rfid) { // this.lastSeenId = rfid; // } // // public boolean isLocator() { // return true; // } // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Locator.java import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.LocatorHandler; package osgi.enroute.trains.track.manager.example.provider; class Locator extends LocatorHandler<Object> { private ExampleTrackManagerImpl owner; public Locator(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; } public void locatedAt(String rfid) { lastSeenId = rfid;
Observation observation = new Observation();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.rest.provider/test/osgi/enroute/trains/rest/provider/RestImplTest.java
// Path: osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/client/TrackClient.java // public class TrackClient { // static JSONCodec codec = new JSONCodec(); // static TypeReference<List<Observation>> LISTOBSERVATIONS = new TypeReference<List<Observation>>() {}; // final URI base; // // @Reference // DTOs dtos; // // public TrackClient(URI base) { // this.base = base; // } // // public boolean blocked(String segment, String reason, boolean blocked) throws Exception { // return (Boolean) send( "blocked", segment, reason, blocked).get(); // } // // Decoder send( Object ... params ) throws Exception { // StringBuilder sb = new StringBuilder(); // String del = base.toString(); // if ( !del.endsWith("/")) // sb.append("/"); // // for ( Object p : params ) { // sb.append(del).append( encode(p)); // del = "/"; // } // InputStream inputStream = new URL(sb.toString()).openConnection().getInputStream(); // return codec.dec().from(inputStream); // } // // // private String encode(Object blocked) throws UnsupportedEncodingException { // return URLEncoder.encode( ""+blocked, "UTF-8"); // } // // public List<Observation> getRecentObservations(long time) throws Exception { // return send("observations", time).get(LISTOBSERVATIONS); // } // }
import java.net.URI; import junit.framework.TestCase; import osgi.enroute.trains.rest.client.TrackClient;
package osgi.enroute.trains.rest.provider; /* * * * */ public class RestImplTest extends TestCase { public void testX() throws Exception {
// Path: osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/client/TrackClient.java // public class TrackClient { // static JSONCodec codec = new JSONCodec(); // static TypeReference<List<Observation>> LISTOBSERVATIONS = new TypeReference<List<Observation>>() {}; // final URI base; // // @Reference // DTOs dtos; // // public TrackClient(URI base) { // this.base = base; // } // // public boolean blocked(String segment, String reason, boolean blocked) throws Exception { // return (Boolean) send( "blocked", segment, reason, blocked).get(); // } // // Decoder send( Object ... params ) throws Exception { // StringBuilder sb = new StringBuilder(); // String del = base.toString(); // if ( !del.endsWith("/")) // sb.append("/"); // // for ( Object p : params ) { // sb.append(del).append( encode(p)); // del = "/"; // } // InputStream inputStream = new URL(sb.toString()).openConnection().getInputStream(); // return codec.dec().from(inputStream); // } // // // private String encode(Object blocked) throws UnsupportedEncodingException { // return URLEncoder.encode( ""+blocked, "UTF-8"); // } // // public List<Observation> getRecentObservations(long time) throws Exception { // return send("observations", time).get(LISTOBSERVATIONS); // } // } // Path: osgi.enroute.trains.rest.provider/test/osgi/enroute/trains/rest/provider/RestImplTest.java import java.net.URI; import junit.framework.TestCase; import osgi.enroute.trains.rest.client.TrackClient; package osgi.enroute.trains.rest.provider; /* * * * */ public class RestImplTest extends TestCase { public void testX() throws Exception {
TrackClient tc = new TrackClient(new URI("http://localhost:8080/rest/"));
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Signal.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SignalHandler<T> extends SegmentHandler<T> { // public Color color = Color.YELLOW; // // public SignalHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case SIGNAL: // setSignal(e.signal); // return true; // // default: // return super.event(e); // } // } // // public void setSignal(Color signal) { // this.color = signal; // } // // public boolean isSignal(){ // return true; // } // }
import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SignalHandler;
package osgi.enroute.trains.track.manager.example.provider; class Signal extends SignalHandler<Object> { private ExampleTrackManagerImpl owner;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SignalHandler<T> extends SegmentHandler<T> { // public Color color = Color.YELLOW; // // public SignalHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case SIGNAL: // setSignal(e.signal); // return true; // // default: // return super.event(e); // } // } // // public void setSignal(Color signal) { // this.color = signal; // } // // public boolean isSignal(){ // return true; // } // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Signal.java import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SignalHandler; package osgi.enroute.trains.track.manager.example.provider; class Signal extends SignalHandler<Object> { private ExampleTrackManagerImpl owner;
public Signal(ExampleTrackManagerImpl owner, Segment segment) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Signal.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SignalHandler<T> extends SegmentHandler<T> { // public Color color = Color.YELLOW; // // public SignalHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case SIGNAL: // setSignal(e.signal); // return true; // // default: // return super.event(e); // } // } // // public void setSignal(Color signal) { // this.color = signal; // } // // public boolean isSignal(){ // return true; // } // }
import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SignalHandler;
package osgi.enroute.trains.track.manager.example.provider; class Signal extends SignalHandler<Object> { private ExampleTrackManagerImpl owner; public Signal(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; }
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SignalHandler<T> extends SegmentHandler<T> { // public Color color = Color.YELLOW; // // public SignalHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case SIGNAL: // setSignal(e.signal); // return true; // // default: // return super.event(e); // } // } // // public void setSignal(Color signal) { // this.color = signal; // } // // public boolean isSignal(){ // return true; // } // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Signal.java import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SignalHandler; package osgi.enroute.trains.track.manager.example.provider; class Signal extends SignalHandler<Object> { private ExampleTrackManagerImpl owner; public Signal(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; }
public void setColor(Color color) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Signal.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SignalHandler<T> extends SegmentHandler<T> { // public Color color = Color.YELLOW; // // public SignalHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case SIGNAL: // setSignal(e.signal); // return true; // // default: // return super.event(e); // } // } // // public void setSignal(Color signal) { // this.color = signal; // } // // public boolean isSignal(){ // return true; // } // }
import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SignalHandler;
package osgi.enroute.trains.track.manager.example.provider; class Signal extends SignalHandler<Object> { private ExampleTrackManagerImpl owner; public Signal(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; } public void setColor(Color color) { this.color = color;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SignalHandler<T> extends SegmentHandler<T> { // public Color color = Color.YELLOW; // // public SignalHandler(Segment segment) { // super(segment); // } // // public boolean event(Observation e) { // switch (e.type) { // case SIGNAL: // setSignal(e.signal); // return true; // // default: // return super.event(e); // } // } // // public void setSignal(Color signal) { // this.color = signal; // } // // public boolean isSignal(){ // return true; // } // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/Signal.java import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SignalHandler; package osgi.enroute.trains.track.manager.example.provider; class Signal extends SignalHandler<Object> { private ExampleTrackManagerImpl owner; public Signal(ExampleTrackManagerImpl owner, Segment segment) { super(segment); this.owner = owner; } public void setColor(Color color) { this.color = color;
Observation o = new Observation();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // }
import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController;
package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command {
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController; package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command {
final Map<String, TrainController> trains = new ConcurrentHashMap<>();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // }
import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController;
package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command { final Map<String, TrainController> trains = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addTrain(TrainController t, ServiceReference<?> ref) { String ch = (String) ref.getProperty("channel"); trains.put(ch.toLowerCase(), t); } void removeTrain(TrainController t) { trains.values().remove(t); }
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController; package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command { final Map<String, TrainController> trains = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addTrain(TrainController t, ServiceReference<?> ref) { String ch = (String) ref.getProperty("channel"); trains.put(ch.toLowerCase(), t); } void removeTrain(TrainController t) { trains.values().remove(t); }
final Map<Integer, SignalSegmentController> signals = new ConcurrentHashMap<>();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // }
import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController;
package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command { final Map<String, TrainController> trains = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addTrain(TrainController t, ServiceReference<?> ref) { String ch = (String) ref.getProperty("channel"); trains.put(ch.toLowerCase(), t); } void removeTrain(TrainController t) { trains.values().remove(t); } final Map<Integer, SignalSegmentController> signals = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addSignal(SignalSegmentController t, ServiceReference<?> ref) {
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController; package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command { final Map<String, TrainController> trains = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addTrain(TrainController t, ServiceReference<?> ref) { String ch = (String) ref.getProperty("channel"); trains.put(ch.toLowerCase(), t); } void removeTrain(TrainController t) { trains.values().remove(t); } final Map<Integer, SignalSegmentController> signals = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addSignal(SignalSegmentController t, ServiceReference<?> ref) {
signals.put((Integer) ref.getProperty(SegmentController.CONTROLLER_ID), t);
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // }
import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController;
package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command { final Map<String, TrainController> trains = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addTrain(TrainController t, ServiceReference<?> ref) { String ch = (String) ref.getProperty("channel"); trains.put(ch.toLowerCase(), t); } void removeTrain(TrainController t) { trains.values().remove(t); } final Map<Integer, SignalSegmentController> signals = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addSignal(SignalSegmentController t, ServiceReference<?> ref) { signals.put((Integer) ref.getProperty(SegmentController.CONTROLLER_ID), t); } void removeSignal(SignalSegmentController s) { signals.values().remove(s); }
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController; package osgi.enroute.trains.hw.provider; /** * */ @Component(immediate = true, property = { Debug.COMMAND_SCOPE + "=trns", // Debug.COMMAND_FUNCTION + "=trns", // Debug.COMMAND_FUNCTION + "=trains", // Debug.COMMAND_FUNCTION + "=move", // Debug.COMMAND_FUNCTION + "=light", // Debug.COMMAND_FUNCTION + "=signal", // Debug.COMMAND_FUNCTION + "=switch", // }, service=Command.class) public class Command { final Map<String, TrainController> trains = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addTrain(TrainController t, ServiceReference<?> ref) { String ch = (String) ref.getProperty("channel"); trains.put(ch.toLowerCase(), t); } void removeTrain(TrainController t) { trains.values().remove(t); } final Map<Integer, SignalSegmentController> signals = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addSignal(SignalSegmentController t, ServiceReference<?> ref) { signals.put((Integer) ref.getProperty(SegmentController.CONTROLLER_ID), t); } void removeSignal(SignalSegmentController s) { signals.values().remove(s); }
final Map<Integer, SwitchSegmentController> switches = new ConcurrentHashMap<>();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // }
import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController;
} void removeSignal(SignalSegmentController s) { signals.values().remove(s); } final Map<Integer, SwitchSegmentController> switches = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addSwitch(SwitchSegmentController t, ServiceReference<?> ref) { switches.put((Integer) ref.getProperty(SegmentController.CONTROLLER_ID), t); } void removeSwitch(SwitchSegmentController s) { switches.values().remove(s); } public void move(String ch, int directionAndSpeed) { trains.get(ch).move(directionAndSpeed); } public void light(String ch, boolean on) { trains.get(ch).light(on); } public String signal(int controller, String color) { SignalSegmentController c = signals.get(controller); if (c == null) return "No such controller"; else
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SegmentController.java // public interface SegmentController { // // /** // * Service property for identifying this controller // */ // String CONTROLLER_ID = "controller.id"; // // /** // * Service property for identifying this controller, by segment name // */ // String CONTROLLER_SEGMENT = "controller.segment"; // // /** // * Get the host location of the segment controller. // */ // default String getLocation() { // return "unknown"; // } // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SignalSegmentController.java // public interface SignalSegmentController extends SegmentController { // // /** // * Set the signal to the given color // * @param color // */ // void signal(Color color); // // Color getSignal(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/SwitchSegmentController.java // public interface SwitchSegmentController extends SegmentController { // // /** // * Set the switch to normal or the alternative // * @param alternative // */ // void swtch(boolean alternative); // // boolean getSwitch(); // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/train/api/TrainController.java // public interface TrainController { // /** // * Service property identifying RC channel for this controller // */ // String CONTROLLER_CHANNEL = "train.channel"; // // /** // * Control the motor. Positive is forward, negative is reverse, 0 is stop. // * // * @param directionAndSpeed // */ // void move(int directionAndSpeed); // // /** // * Control the light on the train // * @param on // */ // void light(boolean on); // // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/Command.java import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.controller.api.SegmentController; import osgi.enroute.trains.controller.api.SignalSegmentController; import osgi.enroute.trains.controller.api.SwitchSegmentController; import osgi.enroute.trains.train.api.TrainController; } void removeSignal(SignalSegmentController s) { signals.values().remove(s); } final Map<Integer, SwitchSegmentController> switches = new ConcurrentHashMap<>(); @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC) void addSwitch(SwitchSegmentController t, ServiceReference<?> ref) { switches.put((Integer) ref.getProperty(SegmentController.CONTROLLER_ID), t); } void removeSwitch(SwitchSegmentController s) { switches.values().remove(s); } public void move(String ch, int directionAndSpeed) { trains.get(ch).move(directionAndSpeed); } public void light(String ch, boolean on) { trains.get(ch).light(on); } public String signal(int controller, String color) { SignalSegmentController c = signals.get(controller); if (c == null) return "No such controller"; else
c.signal(Color.valueOf(color.toUpperCase()));
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/TrackManagerFactory.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/SegmentFactoryAdapter.java // public class SegmentFactoryAdapter<T> implements SegmentFactory<T> { // // @Override // public SegmentHandler<T> create(Segment segment) throws Exception { // SegmentHandler<T> handler; // switch (segment.type) { // case BLOCK: // handler = block(segment); // break; // // case CURVED: // handler = curve(segment); // break; // case LOCATOR: // handler = locator(segment); // break; // case SIGNAL: // handler = signal(segment); // break; // case STRAIGHT: // handler = straight(segment); // break; // case SWITCH: // handler = swtch(segment); // break; // default: // throw new IllegalArgumentException("Missing case " + segment.type); // } // handler.segment = segment; // return handler; // } // // public SegmentHandler<T> block(Segment segment) { // return new Tracks.BlockHandler<T>(segment); // } // // public SegmentHandler<T> curve(Segment segment) { // return new Tracks.CurvedHandler<T>(segment); // } // // public SegmentHandler<T> straight(Segment segment) { // return new Tracks.StraightHandler<T>(segment); // } // // public SegmentHandler<T> signal(Segment segment) { // return new Tracks.SignalHandler<T>(segment); // } // // public SegmentHandler<T> locator(Segment segment) { // return new Tracks.LocatorHandler<T>(segment); // } // // public SegmentHandler<T> swtch(Segment segment) { // return new Tracks.SwitchHandler<T>(segment); // } // // }
import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.SegmentFactoryAdapter;
package osgi.enroute.trains.track.manager.example.provider; class TrackManagerFactory extends SegmentFactoryAdapter<Object>{ final ExampleTrackManagerImpl owner; TrackManagerFactory(ExampleTrackManagerImpl owner) { this.owner = owner; } @Override
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/SegmentFactoryAdapter.java // public class SegmentFactoryAdapter<T> implements SegmentFactory<T> { // // @Override // public SegmentHandler<T> create(Segment segment) throws Exception { // SegmentHandler<T> handler; // switch (segment.type) { // case BLOCK: // handler = block(segment); // break; // // case CURVED: // handler = curve(segment); // break; // case LOCATOR: // handler = locator(segment); // break; // case SIGNAL: // handler = signal(segment); // break; // case STRAIGHT: // handler = straight(segment); // break; // case SWITCH: // handler = swtch(segment); // break; // default: // throw new IllegalArgumentException("Missing case " + segment.type); // } // handler.segment = segment; // return handler; // } // // public SegmentHandler<T> block(Segment segment) { // return new Tracks.BlockHandler<T>(segment); // } // // public SegmentHandler<T> curve(Segment segment) { // return new Tracks.CurvedHandler<T>(segment); // } // // public SegmentHandler<T> straight(Segment segment) { // return new Tracks.StraightHandler<T>(segment); // } // // public SegmentHandler<T> signal(Segment segment) { // return new Tracks.SignalHandler<T>(segment); // } // // public SegmentHandler<T> locator(Segment segment) { // return new Tracks.LocatorHandler<T>(segment); // } // // public SegmentHandler<T> swtch(Segment segment) { // return new Tracks.SwitchHandler<T>(segment); // } // // } // Path: osgi.enroute.trains.track.manager.example.provider/src/osgi/enroute/trains/track/manager/example/provider/TrackManagerFactory.java import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.SegmentFactoryAdapter; package osgi.enroute.trains.track.manager.example.provider; class TrackManagerFactory extends SegmentFactoryAdapter<Object>{ final ExampleTrackManagerImpl owner; TrackManagerFactory(ExampleTrackManagerImpl owner) { this.owner = owner; } @Override
public Signal signal(Segment segment) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.util/src/osgi/enroute/trains/event/util/EventConvertor.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/sensor/api/SensorEvent.java // public class SensorEvent extends DTO{ // // public final static String TOPIC = "osgi/trains/sensor"; // // public enum Type { // WATER, // LIGHT, // MOTION, // DOOR, // PASSENGER // } // // public Type type; // public String segment; // public String train; // // public boolean water; // public boolean dark; // public boolean motion; // public boolean open; // public boolean passenger; // Passenger emergency brake // }
import java.lang.reflect.Field; import java.lang.reflect.Modifier; import org.osgi.service.event.Event; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.sensor.api.SensorEvent;
package osgi.enroute.trains.event.util; public class EventConvertor { public static Observation eventToObservation(Event event, DTOs dtos) throws Exception { Observation o = new Observation(); for ( Field f : o.getClass().getFields() ) { if ( Modifier.isStatic(f.getModifiers())) continue; Object rawValue = event.getProperty(f.getName()); Object value = dtos.convert(rawValue).to(f.getGenericType()); f.set(o, value); } return o; }
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/sensor/api/SensorEvent.java // public class SensorEvent extends DTO{ // // public final static String TOPIC = "osgi/trains/sensor"; // // public enum Type { // WATER, // LIGHT, // MOTION, // DOOR, // PASSENGER // } // // public Type type; // public String segment; // public String train; // // public boolean water; // public boolean dark; // public boolean motion; // public boolean open; // public boolean passenger; // Passenger emergency brake // } // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/event/util/EventConvertor.java import java.lang.reflect.Field; import java.lang.reflect.Modifier; import org.osgi.service.event.Event; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.sensor.api.SensorEvent; package osgi.enroute.trains.event.util; public class EventConvertor { public static Observation eventToObservation(Event event, DTOs dtos) throws Exception { Observation o = new Observation(); for ( Field f : o.getClass().getFields() ) { if ( Modifier.isStatic(f.getModifiers())) continue; Object rawValue = event.getProperty(f.getName()); Object value = dtos.convert(rawValue).to(f.getGenericType()); f.set(o, value); } return o; }
public static SensorEvent eventToSensorEvent(Event event, DTOs dtos) throws Exception {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/MicroSwitchSegmentImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/RFIDSegmentController.java // public interface RFIDSegmentController extends SegmentController { // // /** // * Return the last seen RFID // */ // String lastRFID(); // // /** // * Read an RFID. Resolves the promise when a new RFID is read. // * @return // */ // Promise<String> nextRFID(); // }
import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.controller.api.RFIDSegmentController;
package osgi.enroute.trains.hw.provider; /** * The MicroSwitch segment controller listens for microswitches to be triggered when a train * moves over them... * * @deprecated As of CeBit 2016 we have changed to another locator system where an RFID reader is mounted * on the train and RFID tags are spread around the track. * * @author tverbele * */ @Designate(ocd = MicroSwitchSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.microswitch", immediate = true, property = { "service.exported.interfaces=*", // Debug.COMMAND_SCOPE + "=rfid", // Debug.COMMAND_FUNCTION + "=lastrfid" }, // configurationPolicy = ConfigurationPolicy.REQUIRE)
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/controller/api/RFIDSegmentController.java // public interface RFIDSegmentController extends SegmentController { // // /** // * Return the last seen RFID // */ // String lastRFID(); // // /** // * Read an RFID. Resolves the promise when a new RFID is read. // * @return // */ // Promise<String> nextRFID(); // } // Path: osgi.enroute.trains.hw.provider/src/osgi/enroute/trains/hw/provider/MicroSwitchSegmentImpl.java import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ConfigurationPolicy; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPin; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import osgi.enroute.debug.api.Debug; import osgi.enroute.trains.controller.api.RFIDSegmentController; package osgi.enroute.trains.hw.provider; /** * The MicroSwitch segment controller listens for microswitches to be triggered when a train * moves over them... * * @deprecated As of CeBit 2016 we have changed to another locator system where an RFID reader is mounted * on the train and RFID tags are spread around the track. * * @author tverbele * */ @Designate(ocd = MicroSwitchSegmentImpl.Config.class, factory = true) @Component(name = "osgi.enroute.trains.hw.microswitch", immediate = true, property = { "service.exported.interfaces=*", // Debug.COMMAND_SCOPE + "=rfid", // Debug.COMMAND_FUNCTION + "=lastrfid" }, // configurationPolicy = ConfigurationPolicy.REQUIRE)
public class MicroSwitchSegmentImpl implements RFIDSegmentController {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/provider/RestImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // }
import java.util.List; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.TrackForSegment;
package osgi.enroute.trains.rest.provider; /** * */ @Component(name = "osgi.enroute.trains.rest", immediate=true) public class RestImpl implements REST { @Reference
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // Path: osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/provider/RestImpl.java import java.util.List; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.TrackForSegment; package osgi.enroute.trains.rest.provider; /** * */ @Component(name = "osgi.enroute.trains.rest", immediate=true) public class RestImpl implements REST { @Reference
TrackForSegment ts;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/provider/RestImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // }
import java.util.List; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.TrackForSegment;
package osgi.enroute.trains.rest.provider; /** * */ @Component(name = "osgi.enroute.trains.rest", immediate=true) public class RestImpl implements REST { @Reference TrackForSegment ts;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForSegment.java // public interface TrackForSegment extends TrackInfo { // // /** // * Send when a train has been identified at a locator segment // * // * @param rfid // * The RFID for the train // * @param segment // * The name of the segment // */ // void locatedTrainAt(String rfid, String segment); // // /** // * Indicate that a switch has been set // * // * @param segment // * the name of the switch segment // * @param alternative // * defines the normal or alternative track // */ // void switched(String segment, boolean alternative); // // /** // * Indicate that a signal changed color // * // * @param segment // * the name of the signal segment // * @param color // * the new signal color // */ // void signal(String segment, Color color); // // /** // * External indication that a segment is broken // */ // // void blocked(String segment, String reason, boolean blocked); // } // Path: osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/provider/RestImpl.java import java.util.List; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.rest.api.REST; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.TrackForSegment; package osgi.enroute.trains.rest.provider; /** * */ @Component(name = "osgi.enroute.trains.rest", immediate=true) public class RestImpl implements REST { @Reference TrackForSegment ts;
public List<Observation> getObservations(long time) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/client/TrackClient.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // }
import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.util.List; import org.osgi.service.component.annotations.Reference; import aQute.lib.converter.TypeReference; import aQute.lib.json.Decoder; import aQute.lib.json.JSONCodec; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Observation;
package osgi.enroute.trains.rest.client; public class TrackClient { static JSONCodec codec = new JSONCodec();
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // Path: osgi.enroute.trains.rest.provider/src/osgi/enroute/trains/rest/client/TrackClient.java import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.util.List; import org.osgi.service.component.annotations.Reference; import aQute.lib.converter.TypeReference; import aQute.lib.json.Decoder; import aQute.lib.json.JSONCodec; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.Observation; package osgi.enroute.trains.rest.client; public class TrackClient { static JSONCodec codec = new JSONCodec();
static TypeReference<List<Observation>> LISTOBSERVATIONS = new TypeReference<List<Observation>>() {};
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // }
import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager;
package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // } // Path: osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager; package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference
private PersonDatabase personDB;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // }
import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager;
package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference private PersonDatabase personDB; @Reference
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // } // Path: osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager; package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference private PersonDatabase personDB; @Reference
private StationsManager stations;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // }
import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager;
package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference private PersonDatabase personDB; @Reference private StationsManager stations; private Closeable tick; private Random r = new Random(System.currentTimeMillis()); @Activate void activate() throws Exception{ this.tick = scheduler.schedule(this::tick, 1000, 10000); } @Deactivate void deactivate() throws IOException { this.tick.close(); } void tick() throws Exception { // randomly try to check in a passenger at a station try {
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // } // Path: osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager; package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference private PersonDatabase personDB; @Reference private StationsManager stations; private Closeable tick; private Random r = new Random(System.currentTimeMillis()); @Activate void activate() throws Exception{ this.tick = scheduler.schedule(this::tick, 1000, 10000); } @Deactivate void deactivate() throws IOException { this.tick.close(); } void tick() throws Exception { // randomly try to check in a passenger at a station try {
Person p = personDB.getPersons().get(r.nextInt(personDB.getPersons().size()));
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // }
import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager;
package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference private PersonDatabase personDB; @Reference private StationsManager stations; private Closeable tick; private Random r = new Random(System.currentTimeMillis()); @Activate void activate() throws Exception{ this.tick = scheduler.schedule(this::tick, 1000, 10000); } @Deactivate void deactivate() throws IOException { this.tick.close(); } void tick() throws Exception { // randomly try to check in a passenger at a station try { Person p = personDB.getPersons().get(r.nextInt(personDB.getPersons().size()));
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/Station.java // public class Station extends DTO { // // /** // * Name of the station // */ // public String name; // // /** // * Segment the station is located on // */ // public String segment; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/stations/api/StationsManager.java // public interface StationsManager { // // /** // * List all known stations // * @return // */ // List<Station> getStations(); // // /** // * Return the segment for this station // * @param station // * @return // */ // String getStationSegment(String station); // // /** // * Return the station for this segment // */ // String getStation(String segment); // // /** // * List the passengers currently waiting in a station // * @param station // * @return // */ // List<Passenger> getPassengersWaiting(String station); // // /** // * List all passengers currently traveling on the train // * @param train // * @return // */ // List<Passenger> getPassengersOnTrain(String train); // // /** // * Person checks in at a station with a certain destination // * @param person // * @param station // * @param destination // */ // Passenger checkIn(String personId, String station, String destination); // // /** // * Train calls unboard to let people hop off the train // * @param train // * @param station // */ // // rename to arrive // void arrive(String train, String station); // // /** // * Train boards passengers at a given station // * @param train // * @param station // * @return the list of passengers that boarded the train (includes passengers that are still on the train) // */ // List<Passenger> leave(String train, String station); // // } // Path: osgi.enroute.trains.passengers.provider/src/osgi/enroute/trains/passengers/provider/PassengersSimulator.java import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.scheduler.api.Scheduler; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; import osgi.enroute.trains.stations.api.Station; import osgi.enroute.trains.stations.api.StationsManager; package osgi.enroute.trains.passengers.provider; /** * Listens for checkins from events * * Also randomly selects a persons to check in at a certain station * * A person might be selected twice to check in at different stations ... in this case * the StationsManager should detect this and refuse these check-ins */ @Component(name = "osgi.enroute.trains.passengers", property={"event.topics=osgi/trains/passengers/checkin"}, immediate=true) public class PassengersSimulator implements EventHandler { @Reference private Scheduler scheduler; @Reference private PersonDatabase personDB; @Reference private StationsManager stations; private Closeable tick; private Random r = new Random(System.currentTimeMillis()); @Activate void activate() throws Exception{ this.tick = scheduler.schedule(this::tick, 1000, 10000); } @Deactivate void deactivate() throws IOException { this.tick.close(); } void tick() throws Exception { // randomly try to check in a passenger at a station try { Person p = personDB.getPersons().get(r.nextInt(personDB.getPersons().size()));
List<Station> s = stations.getStations();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // }
import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Formatter; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackConfiguration;
package osgi.enroute.trains.track.util; /** * A utility to parse configuration data and turn it into managed segments. This * code makes it easier to use the track by creating a fully object linked model * of the track. * <p> * The track is typed so that it is possible to create subsclasses of each * node/segment type. This makes it possible to share the common code to manage * the bi-directional linking of the track but add your own object. For example, * layouting is easier when you can do this recursively on an object model. To * use these sub-typed nodes you have to provide your own factory. * * @param <T> * A type implemented by the used sub classes of * {@link SegmentHandler} so that you can for example use the graph * to layout or do something else */ public class Tracks<T> { static final String rootSegment = "A99_R"; final Map<String, SegmentHandler<T>> handlers = new HashMap<>();
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Formatter; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackConfiguration; package osgi.enroute.trains.track.util; /** * A utility to parse configuration data and turn it into managed segments. This * code makes it easier to use the track by creating a fully object linked model * of the track. * <p> * The track is typed so that it is possible to create subsclasses of each * node/segment type. This makes it possible to share the common code to manage * the bi-directional linking of the track but add your own object. For example, * layouting is easier when you can do this recursively on an object model. To * use these sub-typed nodes you have to provide your own factory. * * @param <T> * A type implemented by the used sub classes of * {@link SegmentHandler} so that you can for example use the graph * to layout or do something else */ public class Tracks<T> { static final String rootSegment = "A99_R"; final Map<String, SegmentHandler<T>> handlers = new HashMap<>();
final Map<String, Segment> segments = new HashMap<>();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // }
import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Formatter; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackConfiguration;
while(route.size() > marker){ route.remove(marker); } } return false; } public Collection<SegmentHandler<T>> move(boolean forward) { return Collections.singleton(forward ? next : prev); } void fixup() { segment.to = toIds(move(true)); segment.from = toIds(move(false)); segment.length = length(); } protected int length() { return 0; } protected boolean isRoot() { return segment.id.equals(rootSegment); } /** * Events should be handled in subclasses if they have relevant events */
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Formatter; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackConfiguration; while(route.size() > marker){ route.remove(marker); } } return false; } public Collection<SegmentHandler<T>> move(boolean forward) { return Collections.singleton(forward ? next : prev); } void fixup() { segment.to = toIds(move(true)); segment.from = toIds(move(false)); segment.length = length(); } protected int length() { return 0; } protected boolean isRoot() { return segment.id.equals(rootSegment); } /** * Events should be handled in subclasses if they have relevant events */
public boolean event(Observation e) {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // }
import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Formatter; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackConfiguration;
public boolean isPlain() { return false; } @Override boolean isPrevAlt(SegmentHandler<T> prev) { return prev == altPrev; } protected int length() { return toAlternate ? 35 : 32; } public void setToAlternate(boolean alternate) { this.toAlternate = alternate; } public boolean event(Observation e) { switch (e.type) { case SWITCH: setToAlternate(e.alternate); return true; default: return super.event(e); } } } public static class SignalHandler<T> extends SegmentHandler<T> {
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Color.java // public enum Color { // GREEN, YELLOW, RED // }; // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Observation.java // public class Observation extends DTO { // public final static String TOPIC = "osgi/trains/observation"; // // public enum Type { // CHANGE, // // /** // * Detected an RFID // */ // LOCATED, // /** // * Assignment changed // */ // ASSIGNMENT, // /** // * Assignment reached // */ // ASSIGNMENT_REACHED, // /** // * Signal changed color // */ // SIGNAL, // /** // * Switched changed alternate state // */ // SWITCH, // /** // * A segment is blocked // */ // BLOCKED, // /** // * A segment is dark // */ // DARK, // /** // * A train emergency occurs // */ // EMERGENCY // // } // // public Type type; // public String segment; // public String train; // public Color signal; // public String assignment; // public long time; // public long id; // public String message; // public boolean alternate; // public boolean blocked; // public boolean dark; // public boolean emergency; // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Formatter; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.cloud.api.Color; import osgi.enroute.trains.cloud.api.Observation; import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.cloud.api.TrackConfiguration; public boolean isPlain() { return false; } @Override boolean isPrevAlt(SegmentHandler<T> prev) { return prev == altPrev; } protected int length() { return toAlternate ? 35 : 32; } public void setToAlternate(boolean alternate) { this.toAlternate = alternate; } public boolean event(Observation e) { switch (e.type) { case SWITCH: setToAlternate(e.alternate); return true; default: return super.event(e); } } } public static class SignalHandler<T> extends SegmentHandler<T> {
public Color color = Color.YELLOW;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.api/src/osgi/enroute/trains/operator/api/TrainOperator.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Passenger.java // public class Passenger extends DTO { // // // which person // public Person person; // // // on which train the passenger is currently on? // public String onTrain = null; // // // in which station the passenger is currently waiting? // public String inStation = null; // // // passenger destination // public String destination = null; // // }
import java.util.List; import osgi.enroute.trains.passenger.api.Passenger;
package osgi.enroute.trains.operator.api; /** * A Train Operator will manage his fleet of trains to visit a number of stations and hence transport people * * Passengers can check in in a station via the StationsManager. If an operator has a train arriving * in a station it can pick up passengers by calling the board method of the StationManager. * * The Train Operator will also post Arrival and Departure events when trains arrive/depart in/from a station * * The Train Operator is responsible for choosing the schedule in which trains visit stations. * It uses the Command events to interact with the TrackManager * * @author tverbele * */ public interface TrainOperator { /** * List all trains of this operator * @return */ List<String> getTrains(); /** * List all passengers currently traveling on the train * @param train * @return */
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Passenger.java // public class Passenger extends DTO { // // // which person // public Person person; // // // on which train the passenger is currently on? // public String onTrain = null; // // // in which station the passenger is currently waiting? // public String inStation = null; // // // passenger destination // public String destination = null; // // } // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/operator/api/TrainOperator.java import java.util.List; import osgi.enroute.trains.passenger.api.Passenger; package osgi.enroute.trains.operator.api; /** * A Train Operator will manage his fleet of trains to visit a number of stations and hence transport people * * Passengers can check in in a station via the StationsManager. If an operator has a train arriving * in a station it can pick up passengers by calling the board method of the StationManager. * * The Train Operator will also post Arrival and Departure events when trains arrive/depart in/from a station * * The Train Operator is responsible for choosing the schedule in which trains visit stations. * It uses the Command events to interact with the TrackManager * * @author tverbele * */ public interface TrainOperator { /** * List all trains of this operator * @return */ List<String> getTrains(); /** * List all passengers currently traveling on the train * @param train * @return */
List<Passenger> getPassengersOnTrain(String train);
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.person.provider/src/osgi/enroute/trains/person/provider/util/PersonDownloader.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // }
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import osgi.enroute.trains.passenger.api.Person;
Elements nameLinks = p.select("h3 > a[href]"); for(Element link : nameLinks){ name = link.html(); } Elements pictureLinks = p.select("div.user-picture > a[href]"); for(Element link : pictureLinks){ Element child = link.children().first(); if(child!= null && child.hasAttr("src")){ image = child.attr("src"); } } Elements h5 = p.select("h5"); for(Element e : h5){ company = e.html(); } String[] split = name.split(" "); firstName = split[0]; for(int i=1;i<split.length;i++){ if(split[i].length() > 2) lastName += split[i]+" "; } lastName = lastName.trim(); if(firstName.isEmpty() || lastName.isEmpty()) continue;
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // Path: osgi.enroute.trains.person.provider/src/osgi/enroute/trains/person/provider/util/PersonDownloader.java import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import osgi.enroute.trains.passenger.api.Person; Elements nameLinks = p.select("h3 > a[href]"); for(Element link : nameLinks){ name = link.html(); } Elements pictureLinks = p.select("div.user-picture > a[href]"); for(Element link : pictureLinks){ Element child = link.children().first(); if(child!= null && child.hasAttr("src")){ image = child.attr("src"); } } Elements h5 = p.select("h5"); for(Element e : h5){ company = e.html(); } String[] split = name.split(" "); firstName = split[0]; for(int i=1;i<split.length;i++){ if(split[i].length() > 2) lastName += split[i]+" "; } lastName = lastName.trim(); if(firstName.isEmpty() || lastName.isEmpty()) continue;
Person person = new Person();
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.sensors.provider/src/osgi/enroute/trains/sensors/provider/SensorsImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForCommand.java // public interface TrackForCommand extends TrackInfo { // // /** // * Give a train an assignment. The assignment is to move itself to the given // * segment. // * // * @param train // * the train id // * @param toSegment // * the id of the requested segment // * @return true if granted,otherwise false. This function can wait up to 1 // * minute. // */ // void assign(String train, String toSegment); // // // /** // * Notify a train of an emergency // * // * @param train // * the train id // * @param reason // * cause of the emergency // * @param emergency // * whether the emergency is still applying // */ // void emergency(String train, String reason, boolean emergency); // // // /** // * External indication that a segment is broken // * // * @param Segment // * The segment that is blocked/unblocked // * @param The // * reason the segment is blocked // * @param blocked // * true if blocked, false is free // */ // void blocked(String segment, String reason, boolean blocked); // // // /** // * External indication that a segment is dark // * // * @param Segment // * The segment that is dark/light // * @param blocked // * true if dark, false is light // */ // void dark(String segment, boolean dark); // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/event/util/EventConvertor.java // public class EventConvertor { // // public static Observation eventToObservation(Event event, DTOs dtos) throws Exception { // Observation o = new Observation(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // // // public static SensorEvent eventToSensorEvent(Event event, DTOs dtos) throws Exception { // SensorEvent o = new SensorEvent(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/sensor/api/SensorEvent.java // public class SensorEvent extends DTO{ // // public final static String TOPIC = "osgi/trains/sensor"; // // public enum Type { // WATER, // LIGHT, // MOTION, // DOOR, // PASSENGER // } // // public Type type; // public String segment; // public String train; // // public boolean water; // public boolean dark; // public boolean motion; // public boolean open; // public boolean passenger; // Passenger emergency brake // }
import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.TrackForCommand; import osgi.enroute.trains.event.util.EventConvertor; import osgi.enroute.trains.sensor.api.SensorEvent;
package osgi.enroute.trains.sensors.provider; /** * */ @Component(name = "osgi.enroute.trains.sensors", property={"event.topics="+SensorEvent.TOPIC}, immediate=true) public class SensorsImpl implements EventHandler { @Reference DTOs dtos; @Reference
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForCommand.java // public interface TrackForCommand extends TrackInfo { // // /** // * Give a train an assignment. The assignment is to move itself to the given // * segment. // * // * @param train // * the train id // * @param toSegment // * the id of the requested segment // * @return true if granted,otherwise false. This function can wait up to 1 // * minute. // */ // void assign(String train, String toSegment); // // // /** // * Notify a train of an emergency // * // * @param train // * the train id // * @param reason // * cause of the emergency // * @param emergency // * whether the emergency is still applying // */ // void emergency(String train, String reason, boolean emergency); // // // /** // * External indication that a segment is broken // * // * @param Segment // * The segment that is blocked/unblocked // * @param The // * reason the segment is blocked // * @param blocked // * true if blocked, false is free // */ // void blocked(String segment, String reason, boolean blocked); // // // /** // * External indication that a segment is dark // * // * @param Segment // * The segment that is dark/light // * @param blocked // * true if dark, false is light // */ // void dark(String segment, boolean dark); // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/event/util/EventConvertor.java // public class EventConvertor { // // public static Observation eventToObservation(Event event, DTOs dtos) throws Exception { // Observation o = new Observation(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // // // public static SensorEvent eventToSensorEvent(Event event, DTOs dtos) throws Exception { // SensorEvent o = new SensorEvent(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/sensor/api/SensorEvent.java // public class SensorEvent extends DTO{ // // public final static String TOPIC = "osgi/trains/sensor"; // // public enum Type { // WATER, // LIGHT, // MOTION, // DOOR, // PASSENGER // } // // public Type type; // public String segment; // public String train; // // public boolean water; // public boolean dark; // public boolean motion; // public boolean open; // public boolean passenger; // Passenger emergency brake // } // Path: osgi.enroute.trains.sensors.provider/src/osgi/enroute/trains/sensors/provider/SensorsImpl.java import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.TrackForCommand; import osgi.enroute.trains.event.util.EventConvertor; import osgi.enroute.trains.sensor.api.SensorEvent; package osgi.enroute.trains.sensors.provider; /** * */ @Component(name = "osgi.enroute.trains.sensors", property={"event.topics="+SensorEvent.TOPIC}, immediate=true) public class SensorsImpl implements EventHandler { @Reference DTOs dtos; @Reference
TrackForCommand trains;
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.sensors.provider/src/osgi/enroute/trains/sensors/provider/SensorsImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForCommand.java // public interface TrackForCommand extends TrackInfo { // // /** // * Give a train an assignment. The assignment is to move itself to the given // * segment. // * // * @param train // * the train id // * @param toSegment // * the id of the requested segment // * @return true if granted,otherwise false. This function can wait up to 1 // * minute. // */ // void assign(String train, String toSegment); // // // /** // * Notify a train of an emergency // * // * @param train // * the train id // * @param reason // * cause of the emergency // * @param emergency // * whether the emergency is still applying // */ // void emergency(String train, String reason, boolean emergency); // // // /** // * External indication that a segment is broken // * // * @param Segment // * The segment that is blocked/unblocked // * @param The // * reason the segment is blocked // * @param blocked // * true if blocked, false is free // */ // void blocked(String segment, String reason, boolean blocked); // // // /** // * External indication that a segment is dark // * // * @param Segment // * The segment that is dark/light // * @param blocked // * true if dark, false is light // */ // void dark(String segment, boolean dark); // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/event/util/EventConvertor.java // public class EventConvertor { // // public static Observation eventToObservation(Event event, DTOs dtos) throws Exception { // Observation o = new Observation(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // // // public static SensorEvent eventToSensorEvent(Event event, DTOs dtos) throws Exception { // SensorEvent o = new SensorEvent(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/sensor/api/SensorEvent.java // public class SensorEvent extends DTO{ // // public final static String TOPIC = "osgi/trains/sensor"; // // public enum Type { // WATER, // LIGHT, // MOTION, // DOOR, // PASSENGER // } // // public Type type; // public String segment; // public String train; // // public boolean water; // public boolean dark; // public boolean motion; // public boolean open; // public boolean passenger; // Passenger emergency brake // }
import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.TrackForCommand; import osgi.enroute.trains.event.util.EventConvertor; import osgi.enroute.trains.sensor.api.SensorEvent;
package osgi.enroute.trains.sensors.provider; /** * */ @Component(name = "osgi.enroute.trains.sensors", property={"event.topics="+SensorEvent.TOPIC}, immediate=true) public class SensorsImpl implements EventHandler { @Reference DTOs dtos; @Reference TrackForCommand trains; @Override public void handleEvent(Event event) { try {
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/TrackForCommand.java // public interface TrackForCommand extends TrackInfo { // // /** // * Give a train an assignment. The assignment is to move itself to the given // * segment. // * // * @param train // * the train id // * @param toSegment // * the id of the requested segment // * @return true if granted,otherwise false. This function can wait up to 1 // * minute. // */ // void assign(String train, String toSegment); // // // /** // * Notify a train of an emergency // * // * @param train // * the train id // * @param reason // * cause of the emergency // * @param emergency // * whether the emergency is still applying // */ // void emergency(String train, String reason, boolean emergency); // // // /** // * External indication that a segment is broken // * // * @param Segment // * The segment that is blocked/unblocked // * @param The // * reason the segment is blocked // * @param blocked // * true if blocked, false is free // */ // void blocked(String segment, String reason, boolean blocked); // // // /** // * External indication that a segment is dark // * // * @param Segment // * The segment that is dark/light // * @param blocked // * true if dark, false is light // */ // void dark(String segment, boolean dark); // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/event/util/EventConvertor.java // public class EventConvertor { // // public static Observation eventToObservation(Event event, DTOs dtos) throws Exception { // Observation o = new Observation(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // // // public static SensorEvent eventToSensorEvent(Event event, DTOs dtos) throws Exception { // SensorEvent o = new SensorEvent(); // for ( Field f : o.getClass().getFields() ) { // if ( Modifier.isStatic(f.getModifiers())) // continue; // // Object rawValue = event.getProperty(f.getName()); // Object value = dtos.convert(rawValue).to(f.getGenericType()); // f.set(o, value); // } // return o; // } // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/sensor/api/SensorEvent.java // public class SensorEvent extends DTO{ // // public final static String TOPIC = "osgi/trains/sensor"; // // public enum Type { // WATER, // LIGHT, // MOTION, // DOOR, // PASSENGER // } // // public Type type; // public String segment; // public String train; // // public boolean water; // public boolean dark; // public boolean motion; // public boolean open; // public boolean passenger; // Passenger emergency brake // } // Path: osgi.enroute.trains.sensors.provider/src/osgi/enroute/trains/sensors/provider/SensorsImpl.java import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import osgi.enroute.dto.api.DTOs; import osgi.enroute.trains.cloud.api.TrackForCommand; import osgi.enroute.trains.event.util.EventConvertor; import osgi.enroute.trains.sensor.api.SensorEvent; package osgi.enroute.trains.sensors.provider; /** * */ @Component(name = "osgi.enroute.trains.sensors", property={"event.topics="+SensorEvent.TOPIC}, immediate=true) public class SensorsImpl implements EventHandler { @Reference DTOs dtos; @Reference TrackForCommand trains; @Override public void handleEvent(Event event) { try {
SensorEvent e = EventConvertor.eventToSensorEvent(event, dtos);
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/SegmentFactoryAdapter.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // }
import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler;
package osgi.enroute.trains.track.util; public class SegmentFactoryAdapter<T> implements SegmentFactory<T> { @Override
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // } // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/SegmentFactoryAdapter.java import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler; package osgi.enroute.trains.track.util; public class SegmentFactoryAdapter<T> implements SegmentFactory<T> { @Override
public SegmentHandler<T> create(Segment segment) throws Exception {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/SegmentFactoryAdapter.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // }
import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler;
package osgi.enroute.trains.track.util; public class SegmentFactoryAdapter<T> implements SegmentFactory<T> { @Override
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/cloud/api/Segment.java // public class Segment extends DTO { // // public enum Type { // STRAIGHT, CURVED, SWITCH, SIGNAL, LOCATOR, BLOCK; // } // // // /** // * Our Identity // */ // public String id; // // /** // * Type of the segment // */ // public Type type; // // /** // * Name of the track.This is the name required to get permission // * from the Track Manager. If this name starts with X then no admission is required. This // * is generally for switches. // */ // public String track; // // /** // * Sequence of the segment in the track // */ // public int sequence; // // /** // * Length of the segment in millimeters, can be zero. It an be zero because // * the relation between the controllers and the switches and the signals is // * not always 1:1 mappable to controllers. Therefore zero sized segments can // * be used to map correctly. // */ // public int length; // // /** // * Short code for RFID tag attached to this segment, or 0 for none. // */ // public int tagCode; // // /** // * The associated controller // */ // public int controller = -1; // // /** // * The next segment. Only a switch can have an additional to. The second to // * is the one selected if the switch is set to its alternative. // */ // public String to[]; // // /** // * The previous segment. Only a switch can have an additional from. The second from // * is the one selected if the switch is set to its alternative. // */ // public String from[]; // // } // // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/Tracks.java // public static class SegmentHandler<T> { // public Segment segment; // public SegmentHandler<T> next; // public SegmentHandler<T> prev; // // public SegmentHandler(Segment segment) { // this.segment = segment; // } // // boolean isPrevAlt(SegmentHandler<T> prev) { // return false; // } // // @SuppressWarnings("unchecked") // public T get() { // return (T) this; // } // // @Override // public String toString() { // return segment.id; // } // // public String getTrack(){ // return segment.track; // } // // public boolean isMerge() { // return false; // } // // public boolean isSwitch() { // return false; // } // // public boolean isPlain() { // return true; // } // // public boolean isLocator() { // return false; // } // // public boolean isSignal(){ // return false; // } // // public LinkedList<SegmentHandler<T>> findForward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, true)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // public LinkedList<SegmentHandler<T>> findBackward(SegmentHandler<T> destination) { // LinkedList<SegmentHandler<T>> route = new LinkedList<>(); // if (find(route, destination, false)) // return new LinkedList<SegmentHandler<T>>(route); // else // return null; // } // // boolean find(List<SegmentHandler<T>> route, SegmentHandler<T> destination, boolean forward) { // if (route.contains(this)){ // return false; // } // // route.add(this); // // if (this == destination){ // return true; // } // // Collection<SegmentHandler<T>> choices = move(forward); // // if (choices.size() == 1) { // return choices.iterator().next().find(route, destination, forward); // } // // int marker = route.size(); // for (SegmentHandler<T> choice : choices) { // if (choice.find(route, destination, forward)) // return true; // // // while(route.size() > marker){ // route.remove(marker); // } // } // // return false; // // } // // public Collection<SegmentHandler<T>> move(boolean forward) { // return Collections.singleton(forward ? next : prev); // } // // void fixup() { // segment.to = toIds(move(true)); // segment.from = toIds(move(false)); // segment.length = length(); // } // // protected int length() { // return 0; // } // // protected boolean isRoot() { // return segment.id.equals(rootSegment); // } // // /** // * Events should be handled in subclasses if they have relevant events // */ // public boolean event(Observation e) { // return false; // } // } // Path: osgi.enroute.trains.util/src/osgi/enroute/trains/track/util/SegmentFactoryAdapter.java import osgi.enroute.trains.cloud.api.Segment; import osgi.enroute.trains.track.util.Tracks.SegmentHandler; package osgi.enroute.trains.track.util; public class SegmentFactoryAdapter<T> implements SegmentFactory<T> { @Override
public SegmentHandler<T> create(Segment segment) throws Exception {
osgi/osgi.iot.contest.sdk
osgi.enroute.trains.person.provider/src/osgi/enroute/trains/person/provider/PersonImpl.java
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // }
import java.net.URL; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.osgi.framework.BundleContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.dto.api.DTOs; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase;
package osgi.enroute.trains.person.provider; /** * */ @Component(name = "osgi.enroute.trains.person") public class PersonImpl implements PersonDatabase { // for now just keep in memory // TODO persist this?
// Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/Person.java // public class Person extends DTO { // // public String id; // // public String firstName; // public String lastName; // // public String email; // // // urls to picture/website // public String picture; // public String website; // // // for "networking" applications? // public String company; // public String phone; // // } // // Path: osgi.enroute.trains.api/src/osgi/enroute/trains/passenger/api/PersonDatabase.java // public interface PersonDatabase { // // Person register(String email, String firstName, String lastName); // // Person register(String email, String firstName, String lastName, String company, String phone, String picture, String website); // // List<Person> getPersons(); // // Person getPerson(String id); // // } // Path: osgi.enroute.trains.person.provider/src/osgi/enroute/trains/person/provider/PersonImpl.java import java.net.URL; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.osgi.framework.BundleContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import osgi.enroute.dto.api.DTOs; import osgi.enroute.dto.api.TypeReference; import osgi.enroute.trains.passenger.api.Person; import osgi.enroute.trains.passenger.api.PersonDatabase; package osgi.enroute.trains.person.provider; /** * */ @Component(name = "osgi.enroute.trains.person") public class PersonImpl implements PersonDatabase { // for now just keep in memory // TODO persist this?
private Map<String, Person> persons = new ConcurrentHashMap<>();
celer/mouse
Mouse/source/peg/Parser.java
// Path: Mouse/source/runtime/Source.java // public interface Source // { // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // // The wrapper's constructor may encounter errors that result // // in the object not being properly initialized. // // The method returns 'false' if this is the case. // //------------------------------------------------------------------- // boolean created(); // // //------------------------------------------------------------------- // // Returns position of the last character plus 1 // // (= length of the sequence). // //------------------------------------------------------------------- // int end(); // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // char at(int p); // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // String at(int p, int q); // // //------------------------------------------------------------------- // // Describes position p in user's terms. // //------------------------------------------------------------------- // String where(int p); // }
import mouse.runtime.Source;
//========================================================================= // // This file was generated by Mouse 1.6.1 at 2014-05-13 13:03:26 GMT // from grammar 'C:\Users\Giraf\Mouse\mouse\peg\grammar.peg'. // //========================================================================= package mouse.peg; public class Parser extends mouse.runtime.ParserBase { final Semantics sem; //======================================================================= // // Initialization // //======================================================================= //------------------------------------------------------------------- // Constructor //------------------------------------------------------------------- public Parser() { sem = new Semantics(); sem.rule = this; super.sem = sem; } //------------------------------------------------------------------- // Run the parser //-------------------------------------------------------------------
// Path: Mouse/source/runtime/Source.java // public interface Source // { // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // // The wrapper's constructor may encounter errors that result // // in the object not being properly initialized. // // The method returns 'false' if this is the case. // //------------------------------------------------------------------- // boolean created(); // // //------------------------------------------------------------------- // // Returns position of the last character plus 1 // // (= length of the sequence). // //------------------------------------------------------------------- // int end(); // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // char at(int p); // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // String at(int p, int q); // // //------------------------------------------------------------------- // // Describes position p in user's terms. // //------------------------------------------------------------------- // String where(int p); // } // Path: Mouse/source/peg/Parser.java import mouse.runtime.Source; //========================================================================= // // This file was generated by Mouse 1.6.1 at 2014-05-13 13:03:26 GMT // from grammar 'C:\Users\Giraf\Mouse\mouse\peg\grammar.peg'. // //========================================================================= package mouse.peg; public class Parser extends mouse.runtime.ParserBase { final Semantics sem; //======================================================================= // // Initialization // //======================================================================= //------------------------------------------------------------------- // Constructor //------------------------------------------------------------------- public Parser() { sem = new Semantics(); sem.rule = this; super.sem = sem; } //------------------------------------------------------------------- // Run the parser //-------------------------------------------------------------------
public boolean parse(Source src)
celer/mouse
Mouse/source/runtime/ParserMemo.java
// Path: Mouse/source/runtime/Source.java // public interface Source // { // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // // The wrapper's constructor may encounter errors that result // // in the object not being properly initialized. // // The method returns 'false' if this is the case. // //------------------------------------------------------------------- // boolean created(); // // //------------------------------------------------------------------- // // Returns position of the last character plus 1 // // (= length of the sequence). // //------------------------------------------------------------------- // int end(); // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // char at(int p); // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // String at(int p, int q); // // //------------------------------------------------------------------- // // Describes position p in user's terms. // //------------------------------------------------------------------- // String where(int p); // }
import mouse.runtime.Source;
//========================================================================= // // Part of PEG parser generator Mouse. // // Copyright (C) 2009, 2010, 2013 // by Roman R. Redziejowski (www.romanredz.se). // // 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. // //------------------------------------------------------------------------- // // Change log // 090721 Created for Mouse 1.1. // Version 1.3 // 100504 Added c.diag to arguments of begin in saved and savedInner. // 100504 In Cache(String) set diag to name instead of null. // Version 1.6 // 130416 Allowed m=0 to enable performance comparisons. // //========================================================================= package mouse.runtime; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // // ParserMemo // //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH public class ParserMemo extends ParserBase { //------------------------------------------------------------------- // Cache size. //------------------------------------------------------------------- int cacheSize = 1; //------------------------------------------------------------------- // Phrase to reuse. //------------------------------------------------------------------- Phrase reuse; //------------------------------------------------------------------- // List of Cache objects for initialization. //------------------------------------------------------------------- protected Cache[] caches; //------------------------------------------------------------------- // Constructor //------------------------------------------------------------------- protected ParserMemo() {} //------------------------------------------------------------------- // Initialize //-------------------------------------------------------------------
// Path: Mouse/source/runtime/Source.java // public interface Source // { // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // // The wrapper's constructor may encounter errors that result // // in the object not being properly initialized. // // The method returns 'false' if this is the case. // //------------------------------------------------------------------- // boolean created(); // // //------------------------------------------------------------------- // // Returns position of the last character plus 1 // // (= length of the sequence). // //------------------------------------------------------------------- // int end(); // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // char at(int p); // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // String at(int p, int q); // // //------------------------------------------------------------------- // // Describes position p in user's terms. // //------------------------------------------------------------------- // String where(int p); // } // Path: Mouse/source/runtime/ParserMemo.java import mouse.runtime.Source; //========================================================================= // // Part of PEG parser generator Mouse. // // Copyright (C) 2009, 2010, 2013 // by Roman R. Redziejowski (www.romanredz.se). // // 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. // //------------------------------------------------------------------------- // // Change log // 090721 Created for Mouse 1.1. // Version 1.3 // 100504 Added c.diag to arguments of begin in saved and savedInner. // 100504 In Cache(String) set diag to name instead of null. // Version 1.6 // 130416 Allowed m=0 to enable performance comparisons. // //========================================================================= package mouse.runtime; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // // ParserMemo // //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH public class ParserMemo extends ParserBase { //------------------------------------------------------------------- // Cache size. //------------------------------------------------------------------- int cacheSize = 1; //------------------------------------------------------------------- // Phrase to reuse. //------------------------------------------------------------------- Phrase reuse; //------------------------------------------------------------------- // List of Cache objects for initialization. //------------------------------------------------------------------- protected Cache[] caches; //------------------------------------------------------------------- // Constructor //------------------------------------------------------------------- protected ParserMemo() {} //------------------------------------------------------------------- // Initialize //-------------------------------------------------------------------
public void init(Source src)
celer/mouse
Mouse/examples/example9/FileCalc.java
// Path: Mouse/source/runtime/SourceFile.java // public class SourceFile implements Source // { // //===================================================================== // // // // Data. // // // //===================================================================== // //------------------------------------------------------------------- // // The file. // //------------------------------------------------------------------- // private File f; // // //------------------------------------------------------------------- // // Memory-mapped file. // //------------------------------------------------------------------- // private String text; // // //------------------------------------------------------------------- // // Character encoding assumed for the file. // // To use encoding other than default, change as shown // // in the commented-out example. // //------------------------------------------------------------------- // private static final Charset cs = Charset.defaultCharset(); // // static final Charset cs = Charset.forName("8859_1"); // // //------------------------------------------------------------------- // // Success indicator. // //------------------------------------------------------------------- // private boolean created = false; // // // //===================================================================== // // // // Constructor. Wraps the file identified by 'fileName'. // // // //===================================================================== // public SourceFile(final String fileName) // { // try // { // // Get a Channel for the source file // f = new File(fileName); // FileInputStream fis = new FileInputStream(f); // FileChannel fc = fis.getChannel(); // // // Get a CharBuffer from the source file // ByteBuffer bb = // fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size()); // CharsetDecoder cd = cs.newDecoder(); // CharBuffer cb = cd.decode(bb); // fis.close(); // // // Convert to String // text = cb.toString(); // created = true; // } // catch (FileNotFoundException e) // { System.err.println("File '" + fileName + "' was not found."); } // catch (IOException e) // { System.err.println("Error in file '" + fileName + "' " + e.getMessage()); } // } // // // //===================================================================== // // // // Interface methods. // // // //===================================================================== // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // //------------------------------------------------------------------- // public boolean created() // { return created; } // // //------------------------------------------------------------------- // // Returns end position. // //------------------------------------------------------------------- // public int end() // { return text.length(); } // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // public char at(int p) // { return text.charAt(p); } // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // public String at(int p, int q) // { return text.substring(p,q); } // // //------------------------------------------------------------------- // // Describes position p in terms of line and column number. // // Lines and columns are numbered starting with 1. // //------------------------------------------------------------------- // public String where(int p) // { // int ln = 1; // Line number // int ls = -1; // Line start (position of preceding newline) // int nextnl; // Position of next newline or end // // while (true) // { // nextnl = text.indexOf('\n',ls+1); // if (nextnl<0) nextnl = text.length(); // if (ls<p && p<=nextnl) // return ("line " + ln + " col. " + (p-ls)); // ls = nextnl; // ln++; // } // } // // //===================================================================== // // // // File-specific method. // // // //===================================================================== // //------------------------------------------------------------------- // // Returns the file object. // //------------------------------------------------------------------- // public File file() // { return f; } // }
import mouse.runtime.SourceFile;
class FileCalc { public static void main(String argv[]) { myParser parser = new myParser(); // Instantiate Parser+Semantics
// Path: Mouse/source/runtime/SourceFile.java // public class SourceFile implements Source // { // //===================================================================== // // // // Data. // // // //===================================================================== // //------------------------------------------------------------------- // // The file. // //------------------------------------------------------------------- // private File f; // // //------------------------------------------------------------------- // // Memory-mapped file. // //------------------------------------------------------------------- // private String text; // // //------------------------------------------------------------------- // // Character encoding assumed for the file. // // To use encoding other than default, change as shown // // in the commented-out example. // //------------------------------------------------------------------- // private static final Charset cs = Charset.defaultCharset(); // // static final Charset cs = Charset.forName("8859_1"); // // //------------------------------------------------------------------- // // Success indicator. // //------------------------------------------------------------------- // private boolean created = false; // // // //===================================================================== // // // // Constructor. Wraps the file identified by 'fileName'. // // // //===================================================================== // public SourceFile(final String fileName) // { // try // { // // Get a Channel for the source file // f = new File(fileName); // FileInputStream fis = new FileInputStream(f); // FileChannel fc = fis.getChannel(); // // // Get a CharBuffer from the source file // ByteBuffer bb = // fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size()); // CharsetDecoder cd = cs.newDecoder(); // CharBuffer cb = cd.decode(bb); // fis.close(); // // // Convert to String // text = cb.toString(); // created = true; // } // catch (FileNotFoundException e) // { System.err.println("File '" + fileName + "' was not found."); } // catch (IOException e) // { System.err.println("Error in file '" + fileName + "' " + e.getMessage()); } // } // // // //===================================================================== // // // // Interface methods. // // // //===================================================================== // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // //------------------------------------------------------------------- // public boolean created() // { return created; } // // //------------------------------------------------------------------- // // Returns end position. // //------------------------------------------------------------------- // public int end() // { return text.length(); } // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // public char at(int p) // { return text.charAt(p); } // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // public String at(int p, int q) // { return text.substring(p,q); } // // //------------------------------------------------------------------- // // Describes position p in terms of line and column number. // // Lines and columns are numbered starting with 1. // //------------------------------------------------------------------- // public String where(int p) // { // int ln = 1; // Line number // int ls = -1; // Line start (position of preceding newline) // int nextnl; // Position of next newline or end // // while (true) // { // nextnl = text.indexOf('\n',ls+1); // if (nextnl<0) nextnl = text.length(); // if (ls<p && p<=nextnl) // return ("line " + ln + " col. " + (p-ls)); // ls = nextnl; // ln++; // } // } // // //===================================================================== // // // // File-specific method. // // // //===================================================================== // //------------------------------------------------------------------- // // Returns the file object. // //------------------------------------------------------------------- // public File file() // { return f; } // } // Path: Mouse/examples/example9/FileCalc.java import mouse.runtime.SourceFile; class FileCalc { public static void main(String argv[]) { myParser parser = new myParser(); // Instantiate Parser+Semantics
SourceFile src = new SourceFile(argv[0]); // Wrap the file
celer/mouse
Mouse/examples/example8/Calc.java
// Path: Mouse/source/runtime/SourceString.java // public class SourceString implements Source // { // //===================================================================== // // // // Data. // // // //===================================================================== // //------------------------------------------------------------------- // // The String. // // Note: it is the string given to the constructor, not a copy. // //------------------------------------------------------------------- // final String text; // // //===================================================================== // // // // Constructor. Wraps the string 's'. // // // //===================================================================== // public SourceString(final String s) // { text = s; } // // // //===================================================================== // // // // Interface methods. // // // //===================================================================== // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // //------------------------------------------------------------------- // public boolean created() // { return true; } // // //------------------------------------------------------------------- // // Returns end position. // //------------------------------------------------------------------- // public int end() // { return text.length(); } // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // public char at(int p) // { return text.charAt(p); } // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // public String at(int p, int q) // { return text.substring(p,q); } // // //------------------------------------------------------------------- // // Describes position p in terms of preceding text. // //------------------------------------------------------------------- // public String where(int p) // { // if (p>15) // return "After '... " + text.substring(p-15,p) + "'"; // else if (p>0) // return "After '" + text.substring(0,p) + "'"; // else // return "At start"; // } // }
import mouse.runtime.SourceString; import java.io.BufferedReader; import java.io.InputStreamReader;
class Calc { public static void main(String argv[]) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); myParser parser = new myParser(); // Instantiate Parser+Semantics while (true) { System.out.print("> "); // Print prompt String line = in.readLine(); // Read line if (line.length()==0) return; // Quit on empty line
// Path: Mouse/source/runtime/SourceString.java // public class SourceString implements Source // { // //===================================================================== // // // // Data. // // // //===================================================================== // //------------------------------------------------------------------- // // The String. // // Note: it is the string given to the constructor, not a copy. // //------------------------------------------------------------------- // final String text; // // //===================================================================== // // // // Constructor. Wraps the string 's'. // // // //===================================================================== // public SourceString(final String s) // { text = s; } // // // //===================================================================== // // // // Interface methods. // // // //===================================================================== // //------------------------------------------------------------------- // // Is the wrapper correctly initialized? // //------------------------------------------------------------------- // public boolean created() // { return true; } // // //------------------------------------------------------------------- // // Returns end position. // //------------------------------------------------------------------- // public int end() // { return text.length(); } // // //------------------------------------------------------------------- // // Returns character at position p. // //------------------------------------------------------------------- // public char at(int p) // { return text.charAt(p); } // // //------------------------------------------------------------------- // // Returns characters at positions p through q-1. // //------------------------------------------------------------------- // public String at(int p, int q) // { return text.substring(p,q); } // // //------------------------------------------------------------------- // // Describes position p in terms of preceding text. // //------------------------------------------------------------------- // public String where(int p) // { // if (p>15) // return "After '... " + text.substring(p-15,p) + "'"; // else if (p>0) // return "After '" + text.substring(0,p) + "'"; // else // return "At start"; // } // } // Path: Mouse/examples/example8/Calc.java import mouse.runtime.SourceString; import java.io.BufferedReader; import java.io.InputStreamReader; class Calc { public static void main(String argv[]) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); myParser parser = new myParser(); // Instantiate Parser+Semantics while (true) { System.out.print("> "); // Print prompt String line = in.readLine(); // Read line if (line.length()==0) return; // Quit on empty line
SourceString src = new SourceString(line); // Wrap up the line