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
roma/roma-java-client
java/client/src/test/java/jp/co/rakuten/rit/roma/client/commands/MockConnectionPool.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ConnectionPool.java // public interface ConnectionPool { // public Connection get(Node node) throws IOException; // // public void put(Node node, Connection conn) throws IOException; // // public void delete(Node node, Connection conn); // // public void deleteAll(Node node); // // public void closeAll(); // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Node.java // public class Node { // public static List<Node> create(List<String> IDs) { // List<Node> result = new ArrayList<Node>(IDs.size()); // Iterator<String> iter = IDs.iterator(); // while (iter.hasNext()) { // result.add(create(iter.next())); // } // return result; // } // // public static Node create(String ID) { // int index = ID.indexOf('_'); // String host = ID.substring(0, index); // try { // int port = Integer.parseInt(ID.substring(index + 1, ID.length())); // return new Node(host, port); // } catch (NumberFormatException e) { // throw e; // // return null; // } // } // // String host; // int port; // String ID; // // Node(String host, int port) { // this.host = host; // this.port = port; // this.ID = this.host + "_" + this.port; // } // // public String getHost() { // return host; // } // // public int getPort() { // return port; // } // // @Override // public int hashCode() { // return this.ID.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof Node)) { // return false; // } // // Node n = (Node) obj; // return n.host.equals(this.host) && n.port == this.port; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(host).append("_").append(port); // return sb.toString(); // } // }
import java.io.IOException; import jp.co.rakuten.rit.roma.client.Connection; import jp.co.rakuten.rit.roma.client.ConnectionPool; import jp.co.rakuten.rit.roma.client.Node;
package jp.co.rakuten.rit.roma.client.commands; public class MockConnectionPool implements ConnectionPool { public void closeAll() { }
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ConnectionPool.java // public interface ConnectionPool { // public Connection get(Node node) throws IOException; // // public void put(Node node, Connection conn) throws IOException; // // public void delete(Node node, Connection conn); // // public void deleteAll(Node node); // // public void closeAll(); // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Node.java // public class Node { // public static List<Node> create(List<String> IDs) { // List<Node> result = new ArrayList<Node>(IDs.size()); // Iterator<String> iter = IDs.iterator(); // while (iter.hasNext()) { // result.add(create(iter.next())); // } // return result; // } // // public static Node create(String ID) { // int index = ID.indexOf('_'); // String host = ID.substring(0, index); // try { // int port = Integer.parseInt(ID.substring(index + 1, ID.length())); // return new Node(host, port); // } catch (NumberFormatException e) { // throw e; // // return null; // } // } // // String host; // int port; // String ID; // // Node(String host, int port) { // this.host = host; // this.port = port; // this.ID = this.host + "_" + this.port; // } // // public String getHost() { // return host; // } // // public int getPort() { // return port; // } // // @Override // public int hashCode() { // return this.ID.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof Node)) { // return false; // } // // Node n = (Node) obj; // return n.host.equals(this.host) && n.port == this.port; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(host).append("_").append(port); // return sb.toString(); // } // } // Path: java/client/src/test/java/jp/co/rakuten/rit/roma/client/commands/MockConnectionPool.java import java.io.IOException; import jp.co.rakuten.rit.roma.client.Connection; import jp.co.rakuten.rit.roma.client.ConnectionPool; import jp.co.rakuten.rit.roma.client.Node; package jp.co.rakuten.rit.roma.client.commands; public class MockConnectionPool implements ConnectionPool { public void closeAll() { }
public void delete(Node node, Connection conn) {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/GetsWithCasIDCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasValue.java // public class CasValue { // private final long cas; // private final byte[] value; // // /** // * Construct a new CASValue with the given identifer and value. // * // * @param c // * the CAS identifier // * @param v // * the value // */ // public CasValue(long c, byte[] v) { // super(); // cas = c; // value = v; // } // // /** // * Get the CAS identifier. // */ // public long getCas() { // return cas; // } // // /** // * Get the object value. // */ // public byte[] getValue() { // return value; // } // // @Override // public String toString() { // return "{CasValue " + cas + "/" + value + "}"; // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // }
import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.CasValue; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection;
package jp.co.rakuten.rit.roma.client.commands; public class GetsWithCasIDCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasValue.java // public class CasValue { // private final long cas; // private final byte[] value; // // /** // * Construct a new CASValue with the given identifer and value. // * // * @param c // * the CAS identifier // * @param v // * the value // */ // public CasValue(long c, byte[] v) { // super(); // cas = c; // value = v; // } // // /** // * Get the CAS identifier. // */ // public long getCas() { // return cas; // } // // /** // * Get the object value. // */ // public byte[] getValue() { // return value; // } // // @Override // public String toString() { // return "{CasValue " + cas + "/" + value + "}"; // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/GetsWithCasIDCommand.java import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.CasValue; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; package jp.co.rakuten.rit.roma.client.commands; public class GetsWithCasIDCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override
public boolean execute(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/GetsWithCasIDCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasValue.java // public class CasValue { // private final long cas; // private final byte[] value; // // /** // * Construct a new CASValue with the given identifer and value. // * // * @param c // * the CAS identifier // * @param v // * the value // */ // public CasValue(long c, byte[] v) { // super(); // cas = c; // value = v; // } // // /** // * Get the CAS identifier. // */ // public long getCas() { // return cas; // } // // /** // * Get the object value. // */ // public byte[] getValue() { // return value; // } // // @Override // public String toString() { // return "{CasValue " + cas + "/" + value + "}"; // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // }
import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.CasValue; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection;
package jp.co.rakuten.rit.roma.client.commands; public class GetsWithCasIDCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override public boolean execute(CommandContext context) throws ClientException { try { // "gets <key>*\r\n" StringBuilder sb = new StringBuilder(); List<String> keys = (List<String>) context.get(CommandContext.KEYS); sb.append(STR_GETS); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { sb.append(STR_WHITE_SPACE) .append(iter.next()) .append(STR_ESC) .append(context.get(CommandContext.HASH_NAME)); } sb.append(STR_CRLF);
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasValue.java // public class CasValue { // private final long cas; // private final byte[] value; // // /** // * Construct a new CASValue with the given identifer and value. // * // * @param c // * the CAS identifier // * @param v // * the value // */ // public CasValue(long c, byte[] v) { // super(); // cas = c; // value = v; // } // // /** // * Get the CAS identifier. // */ // public long getCas() { // return cas; // } // // /** // * Get the object value. // */ // public byte[] getValue() { // return value; // } // // @Override // public String toString() { // return "{CasValue " + cas + "/" + value + "}"; // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/GetsWithCasIDCommand.java import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.CasValue; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; package jp.co.rakuten.rit.roma.client.commands; public class GetsWithCasIDCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override public boolean execute(CommandContext context) throws ClientException { try { // "gets <key>*\r\n" StringBuilder sb = new StringBuilder(); List<String> keys = (List<String>) context.get(CommandContext.KEYS); sb.append(STR_GETS); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { sb.append(STR_WHITE_SPACE) .append(iter.next()) .append(STR_ESC) .append(context.get(CommandContext.HASH_NAME)); } sb.append(STR_CRLF);
Connection conn = (Connection) context.get(CommandContext.CONNECTION);
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/GetsWithCasIDCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasValue.java // public class CasValue { // private final long cas; // private final byte[] value; // // /** // * Construct a new CASValue with the given identifer and value. // * // * @param c // * the CAS identifier // * @param v // * the value // */ // public CasValue(long c, byte[] v) { // super(); // cas = c; // value = v; // } // // /** // * Get the CAS identifier. // */ // public long getCas() { // return cas; // } // // /** // * Get the object value. // */ // public byte[] getValue() { // return value; // } // // @Override // public String toString() { // return "{CasValue " + cas + "/" + value + "}"; // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // }
import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.CasValue; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection;
package jp.co.rakuten.rit.roma.client.commands; public class GetsWithCasIDCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override public boolean execute(CommandContext context) throws ClientException { try { // "gets <key>*\r\n" StringBuilder sb = new StringBuilder(); List<String> keys = (List<String>) context.get(CommandContext.KEYS); sb.append(STR_GETS); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { sb.append(STR_WHITE_SPACE) .append(iter.next()) .append(STR_ESC) .append(context.get(CommandContext.HASH_NAME)); } sb.append(STR_CRLF); Connection conn = (Connection) context.get(CommandContext.CONNECTION); conn.out.write(sb.toString().getBytes()); conn.out.flush(); // VALUE foo 0 <valueLen>\r\n<value>\r\n or END\r\n
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasValue.java // public class CasValue { // private final long cas; // private final byte[] value; // // /** // * Construct a new CASValue with the given identifer and value. // * // * @param c // * the CAS identifier // * @param v // * the value // */ // public CasValue(long c, byte[] v) { // super(); // cas = c; // value = v; // } // // /** // * Get the CAS identifier. // */ // public long getCas() { // return cas; // } // // /** // * Get the object value. // */ // public byte[] getValue() { // return value; // } // // @Override // public String toString() { // return "{CasValue " + cas + "/" + value + "}"; // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/GetsWithCasIDCommand.java import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.CasValue; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; package jp.co.rakuten.rit.roma.client.commands; public class GetsWithCasIDCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override public boolean execute(CommandContext context) throws ClientException { try { // "gets <key>*\r\n" StringBuilder sb = new StringBuilder(); List<String> keys = (List<String>) context.get(CommandContext.KEYS); sb.append(STR_GETS); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { sb.append(STR_WHITE_SPACE) .append(iter.next()) .append(STR_ESC) .append(context.get(CommandContext.HASH_NAME)); } sb.append(STR_CRLF); Connection conn = (Connection) context.get(CommandContext.CONNECTION); conn.out.write(sb.toString().getBytes()); conn.out.flush(); // VALUE foo 0 <valueLen>\r\n<value>\r\n or END\r\n
Map<String, CasValue> values = null;
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/IncrCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // }
import jp.co.rakuten.rit.roma.client.ClientException;
package jp.co.rakuten.rit.roma.client.commands; public class IncrCommand extends IncrAndDecrCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/IncrCommand.java import jp.co.rakuten.rit.roma.client.ClientException; package jp.co.rakuten.rit.roma.client.commands; public class IncrCommand extends IncrAndDecrCommand { @Override
public String getCommand() throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CloseCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // }
import java.io.IOException; import jp.co.rakuten.rit.roma.client.ClientException;
package jp.co.rakuten.rit.roma.client.commands; public class CloseCommand extends AbstractCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CloseCommand.java import java.io.IOException; import jp.co.rakuten.rit.roma.client.ClientException; package jp.co.rakuten.rit.roma.client.commands; public class CloseCommand extends AbstractCommand { @Override
protected void create(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/SwapAndSizedPushCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // }
import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext;
package jp.co.rakuten.rit.roma.client.util.commands; public class SwapAndSizedPushCommand extends UpdateCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/SwapAndSizedPushCommand.java import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext; package jp.co.rakuten.rit.roma.client.util.commands; public class SwapAndSizedPushCommand extends UpdateCommand { @Override
protected void create(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/SwapAndSizedPushCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // }
import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext;
package jp.co.rakuten.rit.roma.client.util.commands; public class SwapAndSizedPushCommand extends UpdateCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/SwapAndSizedPushCommand.java import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext; package jp.co.rakuten.rit.roma.client.util.commands; public class SwapAndSizedPushCommand extends UpdateCommand { @Override
protected void create(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/MapcountUpdateCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/AbstractCommand.java // public abstract class AbstractCommand implements Command, CommandID { // protected Command next; // // protected AbstractCommand() { // this(null); // } // // protected AbstractCommand(Command next) { // this.next = next; // } // // public boolean execute(CommandContext context) throws ClientException { // try { // StringBuilder sb = new StringBuilder(); // context.put(CommandContext.STRING_DATA, sb); // create(context); // sendAndReceive(context); // return parseResult(context); // } catch (IOException e) { // throw new ClientException(e); // } // } // // protected abstract void create(CommandContext context) throws ClientException; // // protected abstract void sendAndReceive(CommandContext context) // throws IOException, ClientException; // // protected abstract boolean parseResult(CommandContext context) // throws ClientException; // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; import jp.co.rakuten.rit.roma.client.commands.AbstractCommand; import jp.co.rakuten.rit.roma.client.commands.CommandContext; import net.arnx.jsonic.JSON;
package jp.co.rakuten.rit.roma.client.util.commands; public class MapcountUpdateCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/AbstractCommand.java // public abstract class AbstractCommand implements Command, CommandID { // protected Command next; // // protected AbstractCommand() { // this(null); // } // // protected AbstractCommand(Command next) { // this.next = next; // } // // public boolean execute(CommandContext context) throws ClientException { // try { // StringBuilder sb = new StringBuilder(); // context.put(CommandContext.STRING_DATA, sb); // create(context); // sendAndReceive(context); // return parseResult(context); // } catch (IOException e) { // throw new ClientException(e); // } // } // // protected abstract void create(CommandContext context) throws ClientException; // // protected abstract void sendAndReceive(CommandContext context) // throws IOException, ClientException; // // protected abstract boolean parseResult(CommandContext context) // throws ClientException; // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/MapcountUpdateCommand.java import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; import jp.co.rakuten.rit.roma.client.commands.AbstractCommand; import jp.co.rakuten.rit.roma.client.commands.CommandContext; import net.arnx.jsonic.JSON; package jp.co.rakuten.rit.roma.client.util.commands; public class MapcountUpdateCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override
public boolean execute(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/MapcountUpdateCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/AbstractCommand.java // public abstract class AbstractCommand implements Command, CommandID { // protected Command next; // // protected AbstractCommand() { // this(null); // } // // protected AbstractCommand(Command next) { // this.next = next; // } // // public boolean execute(CommandContext context) throws ClientException { // try { // StringBuilder sb = new StringBuilder(); // context.put(CommandContext.STRING_DATA, sb); // create(context); // sendAndReceive(context); // return parseResult(context); // } catch (IOException e) { // throw new ClientException(e); // } // } // // protected abstract void create(CommandContext context) throws ClientException; // // protected abstract void sendAndReceive(CommandContext context) // throws IOException, ClientException; // // protected abstract boolean parseResult(CommandContext context) // throws ClientException; // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; import jp.co.rakuten.rit.roma.client.commands.AbstractCommand; import jp.co.rakuten.rit.roma.client.commands.CommandContext; import net.arnx.jsonic.JSON;
package jp.co.rakuten.rit.roma.client.util.commands; public class MapcountUpdateCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/AbstractCommand.java // public abstract class AbstractCommand implements Command, CommandID { // protected Command next; // // protected AbstractCommand() { // this(null); // } // // protected AbstractCommand(Command next) { // this.next = next; // } // // public boolean execute(CommandContext context) throws ClientException { // try { // StringBuilder sb = new StringBuilder(); // context.put(CommandContext.STRING_DATA, sb); // create(context); // sendAndReceive(context); // return parseResult(context); // } catch (IOException e) { // throw new ClientException(e); // } // } // // protected abstract void create(CommandContext context) throws ClientException; // // protected abstract void sendAndReceive(CommandContext context) // throws IOException, ClientException; // // protected abstract boolean parseResult(CommandContext context) // throws ClientException; // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/MapcountUpdateCommand.java import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; import jp.co.rakuten.rit.roma.client.commands.AbstractCommand; import jp.co.rakuten.rit.roma.client.commands.CommandContext; import net.arnx.jsonic.JSON; package jp.co.rakuten.rit.roma.client.util.commands; public class MapcountUpdateCommand extends AbstractCommand { @SuppressWarnings("unchecked") @Override
public boolean execute(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor1Impl.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // }
import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry;
package jp.co.rakuten.rit.roma.client.util; class StringListAdaptor1Impl implements StringListAdaptor { private static final String SEP = "_"; // "_$_$_"; private static final String SEP2 = ","; // "_$,$_"; private int listSize; private long expiry; protected StringWrapper sWrapper;
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor1Impl.java import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry; package jp.co.rakuten.rit.roma.client.util; class StringListAdaptor1Impl implements StringListAdaptor { private static final String SEP = "_"; // "_$_$_"; private static final String SEP2 = ","; // "_$,$_"; private int listSize; private long expiry; protected StringWrapper sWrapper;
StringListAdaptor1Impl(StringWrapper wrapper) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor1Impl.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // }
import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry;
ret = true; } else { // getListSize() != 0 ret = getListSize() >= rawList.size(); if (!ret) { rawList = limitListSize(rawList, getListSize()); } } return ret && sWrapper.put(key, toString(rawList)); } public boolean deleteAndPrepend(String key, String value) throws ClientException { List<String> rawList = getRawList(sWrapper, key); Date d = new Date(); if (getExpiry() != 0) { rawList = limitExpiry(rawList, d.getTime(), getExpiry()); } remove(rawList, value); rawList.add(0, value + SEP + d.getTime()); if (getListSize() != 0 && getListSize() < rawList.size()) { rawList = limitListSize(rawList, getListSize()); } return sWrapper.put(key, toString(rawList)); } public List<String> get(String key) throws ClientException { List<String> rawList = getRawList(sWrapper, key); return toStringList(rawList); }
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor1Impl.java import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry; ret = true; } else { // getListSize() != 0 ret = getListSize() >= rawList.size(); if (!ret) { rawList = limitListSize(rawList, getListSize()); } } return ret && sWrapper.put(key, toString(rawList)); } public boolean deleteAndPrepend(String key, String value) throws ClientException { List<String> rawList = getRawList(sWrapper, key); Date d = new Date(); if (getExpiry() != 0) { rawList = limitExpiry(rawList, d.getTime(), getExpiry()); } remove(rawList, value); rawList.add(0, value + SEP + d.getTime()); if (getListSize() != 0 && getListSize() < rawList.size()) { rawList = limitListSize(rawList, getListSize()); } return sWrapper.put(key, toString(rawList)); } public List<String> get(String key) throws ClientException { List<String> rawList = getRawList(sWrapper, key); return toStringList(rawList); }
public List<Entry> getEntries(String key) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/PushCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // }
import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext;
package jp.co.rakuten.rit.roma.client.util.commands; public class PushCommand extends UpdateCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/PushCommand.java import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext; package jp.co.rakuten.rit.roma.client.util.commands; public class PushCommand extends UpdateCommand { @Override
protected void create(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/PushCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // }
import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext;
package jp.co.rakuten.rit.roma.client.util.commands; public class PushCommand extends UpdateCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CommandContext.java // public class CommandContext extends HashMap<String, Object> { // private static final long serialVersionUID = 3317922575242590794L; // public static final String COMMAND_ID = "COMMAND_ID"; // public static final String RESULT = "RESULT"; // public static final String CONNECTION = "CONNECTION"; // public static final String KEY = "KEY"; // public static final String KEYS = "KEYS"; // public static final String HASH_NAME = "HASH_NAME"; // public static final String HASH = "HASH"; // public static final String VALUE = "VALUE"; // public static final String EXPIRY = "EXPIRY"; // public static final String EXCEPTION = "EXCEPTION"; // public static final String STRING_DATA = "STRING_DATA"; // public static final String NODE = "NODE"; // public static final String ROUTING_TABLE = "ROUTINGTABLE"; // public static final String CONNECTION_POOL = "CONNECTIONPOOL"; // public static final String CAS_ID = "CAS_ID"; // // public CommandContext() { // super(); // } // // @Override // public String toString() { // return super.toString(); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/PushCommand.java import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.commands.CommandContext; package jp.co.rakuten.rit.roma.client.util.commands; public class PushCommand extends UpdateCommand { @Override
protected void create(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/ExpireCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // }
import jp.co.rakuten.rit.roma.client.ClientException;
package jp.co.rakuten.rit.roma.client.commands; public class ExpireCommand extends StoreCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/ExpireCommand.java import jp.co.rakuten.rit.roma.client.ClientException; package jp.co.rakuten.rit.roma.client.commands; public class ExpireCommand extends StoreCommand { @Override
public void create(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/AddCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // }
import jp.co.rakuten.rit.roma.client.ClientException;
package jp.co.rakuten.rit.roma.client.commands; public class AddCommand extends StoreCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/AddCommand.java import jp.co.rakuten.rit.roma.client.ClientException; package jp.co.rakuten.rit.roma.client.commands; public class AddCommand extends StoreCommand { @Override
public String getCommand() throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CasCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasResponse.java // public enum CasResponse { // /** // * Status indicating that the CAS was successful and the new value is stored // * in the cache. // */ // OK, // /** // * Status indicating the value was not found in the cache (an add operation // * may be issued to store the value). // */ // NOT_FOUND, // /** // * Status indicating the value was found in the cache, but exists with a // * different CAS value than expected. In this case, the value must be // * refetched and the CAS operation tried again. // */ // EXISTS // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // }
import java.io.IOException; import java.util.Date; import jp.co.rakuten.rit.roma.client.CasResponse; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection;
package jp.co.rakuten.rit.roma.client.commands; public class CasCommand extends AbstractCommand { @Override
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasResponse.java // public enum CasResponse { // /** // * Status indicating that the CAS was successful and the new value is stored // * in the cache. // */ // OK, // /** // * Status indicating the value was not found in the cache (an add operation // * may be issued to store the value). // */ // NOT_FOUND, // /** // * Status indicating the value was found in the cache, but exists with a // * different CAS value than expected. In this case, the value must be // * refetched and the CAS operation tried again. // */ // EXISTS // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CasCommand.java import java.io.IOException; import java.util.Date; import jp.co.rakuten.rit.roma.client.CasResponse; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; package jp.co.rakuten.rit.roma.client.commands; public class CasCommand extends AbstractCommand { @Override
protected void create(CommandContext context) throws ClientException {
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CasCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasResponse.java // public enum CasResponse { // /** // * Status indicating that the CAS was successful and the new value is stored // * in the cache. // */ // OK, // /** // * Status indicating the value was not found in the cache (an add operation // * may be issued to store the value). // */ // NOT_FOUND, // /** // * Status indicating the value was found in the cache, but exists with a // * different CAS value than expected. In this case, the value must be // * refetched and the CAS operation tried again. // */ // EXISTS // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // }
import java.io.IOException; import java.util.Date; import jp.co.rakuten.rit.roma.client.CasResponse; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection;
package jp.co.rakuten.rit.roma.client.commands; public class CasCommand extends AbstractCommand { @Override protected void create(CommandContext context) throws ClientException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA); sb.append(STR_CAS) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.KEY)) .append(STR_ESC) .append(context.get(CommandContext.HASH_NAME)) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.HASH)) .append(STR_WHITE_SPACE) .append(((Date) context.get(CommandContext.EXPIRY)).getTime() / 1000) .append(STR_WHITE_SPACE) .append(((byte[]) context.get(CommandContext.VALUE)).length) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.CAS_ID)) .append(STR_CRLF); context.put(CommandContext.STRING_DATA, sb); } @Override protected void sendAndReceive(CommandContext context) throws IOException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA);
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasResponse.java // public enum CasResponse { // /** // * Status indicating that the CAS was successful and the new value is stored // * in the cache. // */ // OK, // /** // * Status indicating the value was not found in the cache (an add operation // * may be issued to store the value). // */ // NOT_FOUND, // /** // * Status indicating the value was found in the cache, but exists with a // * different CAS value than expected. In this case, the value must be // * refetched and the CAS operation tried again. // */ // EXISTS // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CasCommand.java import java.io.IOException; import java.util.Date; import jp.co.rakuten.rit.roma.client.CasResponse; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; package jp.co.rakuten.rit.roma.client.commands; public class CasCommand extends AbstractCommand { @Override protected void create(CommandContext context) throws ClientException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA); sb.append(STR_CAS) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.KEY)) .append(STR_ESC) .append(context.get(CommandContext.HASH_NAME)) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.HASH)) .append(STR_WHITE_SPACE) .append(((Date) context.get(CommandContext.EXPIRY)).getTime() / 1000) .append(STR_WHITE_SPACE) .append(((byte[]) context.get(CommandContext.VALUE)).length) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.CAS_ID)) .append(STR_CRLF); context.put(CommandContext.STRING_DATA, sb); } @Override protected void sendAndReceive(CommandContext context) throws IOException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA);
Connection conn = (Connection) context.get(CommandContext.CONNECTION);
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CasCommand.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasResponse.java // public enum CasResponse { // /** // * Status indicating that the CAS was successful and the new value is stored // * in the cache. // */ // OK, // /** // * Status indicating the value was not found in the cache (an add operation // * may be issued to store the value). // */ // NOT_FOUND, // /** // * Status indicating the value was found in the cache, but exists with a // * different CAS value than expected. In this case, the value must be // * refetched and the CAS operation tried again. // */ // EXISTS // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // }
import java.io.IOException; import java.util.Date; import jp.co.rakuten.rit.roma.client.CasResponse; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection;
.append(STR_WHITE_SPACE) .append(context.get(CommandContext.HASH)) .append(STR_WHITE_SPACE) .append(((Date) context.get(CommandContext.EXPIRY)).getTime() / 1000) .append(STR_WHITE_SPACE) .append(((byte[]) context.get(CommandContext.VALUE)).length) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.CAS_ID)) .append(STR_CRLF); context.put(CommandContext.STRING_DATA, sb); } @Override protected void sendAndReceive(CommandContext context) throws IOException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA); Connection conn = (Connection) context.get(CommandContext.CONNECTION); conn.out.write(sb.toString().getBytes()); conn.out.write(((byte[]) context.get(CommandContext.VALUE))); conn.out.write(STR_CRLF.getBytes()); conn.out.flush(); sb = new StringBuilder(); sb.append(conn.in.readLine()); context.put(CommandContext.STRING_DATA, sb); } @Override protected boolean parseResult(CommandContext context) throws ClientException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA); String ret = sb.toString(); if (ret.startsWith("STORED")) {
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/CasResponse.java // public enum CasResponse { // /** // * Status indicating that the CAS was successful and the new value is stored // * in the cache. // */ // OK, // /** // * Status indicating the value was not found in the cache (an add operation // * may be issued to store the value). // */ // NOT_FOUND, // /** // * Status indicating the value was found in the cache, but exists with a // * different CAS value than expected. In this case, the value must be // * refetched and the CAS operation tried again. // */ // EXISTS // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/Connection.java // public class Connection { // public Socket sock; // // public ExtInputStream in; // // public OutputStream out; // // /** // * Construct a connection to a ROMA process. // * // * @param sock // * - a socket of the ROMA process to connect to // * @throws IOException // * - if creating this connection fails // */ // public Connection(final Socket sock) throws IOException { // this.sock = sock; // this.in = new ExtInputStream(sock.getInputStream()); // this.out = new BufferedOutputStream(sock.getOutputStream()); // } // // public void setTimeout(int timeout) throws SocketException { // this.sock.setSoTimeout(timeout); // } // // /** // * Close this connection. // * // * @throws IOException // * - if closing this connection fails // */ // public void close() throws IOException { // if (in != null) { // in.close(); // } // if (out != null) { // out.close(); // } // if (sock != null) { // sock.close(); // } // } // // public static long TIME = 0; // // public class ExtInputStream extends BufferedInputStream { // // private byte[] one_byte = new byte[1]; // // ExtInputStream(InputStream in) { // super(in); // } // // public void read(int byteLen) throws IOException { // for (int i = 0; i < byteLen; ++i) { // super.read(one_byte); // } // } // // public String readLine() throws IOException { // StringBuilder ret = new StringBuilder(); // // long t = System.currentTimeMillis(); // // while (super.read(one_byte) > 0) { // if (one_byte[0] == 0x0d) { // \r // break; // } else { // ret.append((char) one_byte[0]); // } // } // // TIME = TIME + (System.currentTimeMillis() - t); // // super.read(one_byte); // \n // return ret.toString(); // } // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/commands/CasCommand.java import java.io.IOException; import java.util.Date; import jp.co.rakuten.rit.roma.client.CasResponse; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.Connection; .append(STR_WHITE_SPACE) .append(context.get(CommandContext.HASH)) .append(STR_WHITE_SPACE) .append(((Date) context.get(CommandContext.EXPIRY)).getTime() / 1000) .append(STR_WHITE_SPACE) .append(((byte[]) context.get(CommandContext.VALUE)).length) .append(STR_WHITE_SPACE) .append(context.get(CommandContext.CAS_ID)) .append(STR_CRLF); context.put(CommandContext.STRING_DATA, sb); } @Override protected void sendAndReceive(CommandContext context) throws IOException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA); Connection conn = (Connection) context.get(CommandContext.CONNECTION); conn.out.write(sb.toString().getBytes()); conn.out.write(((byte[]) context.get(CommandContext.VALUE))); conn.out.write(STR_CRLF.getBytes()); conn.out.flush(); sb = new StringBuilder(); sb.append(conn.in.readLine()); context.put(CommandContext.STRING_DATA, sb); } @Override protected boolean parseResult(CommandContext context) throws ClientException { StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA); String ret = sb.toString(); if (ret.startsWith("STORED")) {
context.put(CommandContext.RESULT, CasResponse.OK);
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // }
import java.util.List; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry;
package jp.co.rakuten.rit.roma.client.util; interface StringListAdaptor { void setListSize(int listSize); int getListSize(); void setExpiry(long expiry); long getExpiry(); void setStringWrapper(StringWrapper wrapper); StringWrapper getStringWrapper();
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor.java import java.util.List; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry; package jp.co.rakuten.rit.roma.client.util; interface StringListAdaptor { void setListSize(int listSize); int getListSize(); void setExpiry(long expiry); long getExpiry(); void setStringWrapper(StringWrapper wrapper); StringWrapper getStringWrapper();
boolean append(String key, String value) throws ClientException;
roma/roma-java-client
java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor.java
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // }
import java.util.List; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry;
package jp.co.rakuten.rit.roma.client.util; interface StringListAdaptor { void setListSize(int listSize); int getListSize(); void setExpiry(long expiry); long getExpiry(); void setStringWrapper(StringWrapper wrapper); StringWrapper getStringWrapper(); boolean append(String key, String value) throws ClientException; void deleteList(String key) throws ClientException; boolean delete(String key, int index) throws ClientException; boolean delete(String key, String value) throws ClientException; boolean deleteAndAppend(String key, String value) throws ClientException; boolean deleteAndPrepend(String key, String value) throws ClientException; List<String> get(String key) throws ClientException;
// Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/ClientException.java // public class ClientException extends Exception { // private static final long serialVersionUID = -7032182229500031385L; // // public ClientException() { // super(); // } // // public ClientException(Throwable cause) { // super(cause); // } // // public ClientException(String reason) { // super(reason); // } // // public ClientException(String reason, Throwable cause) { // super(reason, cause); // } // } // // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListWrapper.java // public static class Entry { // // private String value; // private long time; // // Entry(byte[] value, long time) { // this(new String(value), time); // } // // Entry(String value, long time) { // this.value = value; // this.time = time; // } // // public String getValue() { // return value; // } // // public long getTime() { // return time; // } // // @Override // public String toString() { // return value + "_" + time; // } // } // Path: java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/StringListAdaptor.java import java.util.List; import jp.co.rakuten.rit.roma.client.ClientException; import jp.co.rakuten.rit.roma.client.util.StringListWrapper.Entry; package jp.co.rakuten.rit.roma.client.util; interface StringListAdaptor { void setListSize(int listSize); int getListSize(); void setExpiry(long expiry); long getExpiry(); void setStringWrapper(StringWrapper wrapper); StringWrapper getStringWrapper(); boolean append(String key, String value) throws ClientException; void deleteList(String key) throws ClientException; boolean delete(String key, int index) throws ClientException; boolean delete(String key, String value) throws ClientException; boolean deleteAndAppend(String key, String value) throws ClientException; boolean deleteAndPrepend(String key, String value) throws ClientException; List<String> get(String key) throws ClientException;
List<Entry> getEntries(String key) throws ClientException;
AVMf/avmf
src/main/java/org/avmframework/initialization/DefaultInitializer.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // }
import org.avmframework.Vector;
package org.avmframework.initialization; public class DefaultInitializer extends Initializer { @Override
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // Path: src/main/java/org/avmframework/initialization/DefaultInitializer.java import org.avmframework.Vector; package org.avmframework.initialization; public class DefaultInitializer extends Initializer { @Override
public void initialize(Vector vector) {
AVMf/avmf
src/main/java/org/avmframework/examples/requirementassignment/TestObject.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // }
import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List;
package org.avmframework.examples.requirementassignment; public class TestObject { static final int INIT = 0; static final int MIN = -1; // The value -1 means the requirement is not assigned to any stakeholder // set up the vector to be optimized
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // Path: src/main/java/org/avmframework/examples/requirementassignment/TestObject.java import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List; package org.avmframework.examples.requirementassignment; public class TestObject { static final int INIT = 0; static final int MIN = -1; // The value -1 means the requirement is not assigned to any stakeholder // set up the vector to be optimized
public Vector setUpVector(int size, int numStakeholder) {
AVMf/avmf
src/main/java/org/avmframework/examples/requirementassignment/TestObject.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // }
import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List;
package org.avmframework.examples.requirementassignment; public class TestObject { static final int INIT = 0; static final int MIN = -1; // The value -1 means the requirement is not assigned to any stakeholder // set up the vector to be optimized public Vector setUpVector(int size, int numStakeholder) { Vector vector = new Vector(); for (int i = 0; i < size; i++) {
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // Path: src/main/java/org/avmframework/examples/requirementassignment/TestObject.java import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List; package org.avmframework.examples.requirementassignment; public class TestObject { static final int INIT = 0; static final int MIN = -1; // The value -1 means the requirement is not assigned to any stakeholder // set up the vector to be optimized public Vector setUpVector(int size, int numStakeholder) { Vector vector = new Vector(); for (int i = 0; i < size; i++) {
vector.addVariable(new IntegerVariable(INIT, MIN, numStakeholder - 1));
AVMf/avmf
src/test/java/org/avmframework/ObjectiveFunctions.java
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // }
import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable;
package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // } // Path: src/test/java/org/avmframework/ObjectiveFunctions.java import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable; package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override
protected ObjectiveValue computeObjectiveValue(Vector vector) {
AVMf/avmf
src/test/java/org/avmframework/ObjectiveFunctions.java
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // }
import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable;
package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) {
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // } // Path: src/test/java/org/avmframework/ObjectiveFunctions.java import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable; package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) {
return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0);
AVMf/avmf
src/test/java/org/avmframework/ObjectiveFunctions.java
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // }
import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable;
package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); } }; return objFun; } public static ObjectiveFunction allZeros() { return new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { int distance = 0;
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // } // Path: src/test/java/org/avmframework/ObjectiveFunctions.java import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable; package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); } }; return objFun; } public static ObjectiveFunction allZeros() { return new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { int distance = 0;
for (Variable var : vector.getVariables()) {
AVMf/avmf
src/test/java/org/avmframework/ObjectiveFunctions.java
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // }
import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable;
package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); } }; return objFun; } public static ObjectiveFunction allZeros() { return new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { int distance = 0; for (Variable var : vector.getVariables()) {
// Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // } // Path: src/test/java/org/avmframework/ObjectiveFunctions.java import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.IntegerVariable; import org.avmframework.variable.Variable; package org.avmframework; public class ObjectiveFunctions { public static ObjectiveFunction flat() { ObjectiveFunction objFun = new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); } }; return objFun; } public static ObjectiveFunction allZeros() { return new ObjectiveFunction() { @Override protected ObjectiveValue computeObjectiveValue(Vector vector) { int distance = 0; for (Variable var : vector.getVariables()) {
distance += Math.abs(((IntegerVariable) var).getValue());
AVMf/avmf
src/main/java/org/avmframework/examples/testoptimization/SelectionObjectiveFunction.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // }
import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.Variable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
// in selection the order does not matter, so we include the coverage and execution time of all // the selected test cases public ObjectiveValue computeObjectiveValue(Vector vector) { List<TestCase> selectedTestSuite = new ArrayList<TestCase>(); selectedTestSuite = selectTestCases(vector); double executionTime = 0; double fdc = 0; Set<String> coveredCoverageSet = new HashSet<String>(); for (int i = 0; i < selectedTestSuite.size(); i++) { TestCase tempCase = selectedTestSuite.get(i); coveredCoverageSet.addAll(tempCase.getApiCovered()); executionTime += tempCase.getTime(); fdc += tempCase.getFaultDetection(); } double fitness; // convert time budget from percentage to real number if (executionTime <= (transitionStateCoverage.getExecutionTime() * timeBudget / 100)) { double objCoverage; double objFaultDetectionCoverage; objCoverage = coveredCoverageSet.size() / transitionStateCoverage.getCoverage().size(); objFaultDetectionCoverage = fdc / transitionStateCoverage.getFaultDetection(); // subtract 1 for minimization fitness = (1 - objCoverage) * this.weightCoverage + (1 - objFaultDetectionCoverage) * this.weightFaultDetection; } else { fitness = 1; // this solution is bad since it exceeds the alloted time budget }
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // } // Path: src/main/java/org/avmframework/examples/testoptimization/SelectionObjectiveFunction.java import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.Variable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; // in selection the order does not matter, so we include the coverage and execution time of all // the selected test cases public ObjectiveValue computeObjectiveValue(Vector vector) { List<TestCase> selectedTestSuite = new ArrayList<TestCase>(); selectedTestSuite = selectTestCases(vector); double executionTime = 0; double fdc = 0; Set<String> coveredCoverageSet = new HashSet<String>(); for (int i = 0; i < selectedTestSuite.size(); i++) { TestCase tempCase = selectedTestSuite.get(i); coveredCoverageSet.addAll(tempCase.getApiCovered()); executionTime += tempCase.getTime(); fdc += tempCase.getFaultDetection(); } double fitness; // convert time budget from percentage to real number if (executionTime <= (transitionStateCoverage.getExecutionTime() * timeBudget / 100)) { double objCoverage; double objFaultDetectionCoverage; objCoverage = coveredCoverageSet.size() / transitionStateCoverage.getCoverage().size(); objFaultDetectionCoverage = fdc / transitionStateCoverage.getFaultDetection(); // subtract 1 for minimization fitness = (1 - objCoverage) * this.weightCoverage + (1 - objFaultDetectionCoverage) * this.weightFaultDetection; } else { fitness = 1; // this solution is bad since it exceeds the alloted time budget }
return NumericObjectiveValue.lowerIsBetterObjectiveValue(fitness, 0);
AVMf/avmf
src/main/java/org/avmframework/examples/testoptimization/SelectionObjectiveFunction.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // }
import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.Variable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
Set<String> coveredCoverageSet = new HashSet<String>(); for (int i = 0; i < selectedTestSuite.size(); i++) { TestCase tempCase = selectedTestSuite.get(i); coveredCoverageSet.addAll(tempCase.getApiCovered()); executionTime += tempCase.getTime(); fdc += tempCase.getFaultDetection(); } double fitness; // convert time budget from percentage to real number if (executionTime <= (transitionStateCoverage.getExecutionTime() * timeBudget / 100)) { double objCoverage; double objFaultDetectionCoverage; objCoverage = coveredCoverageSet.size() / transitionStateCoverage.getCoverage().size(); objFaultDetectionCoverage = fdc / transitionStateCoverage.getFaultDetection(); // subtract 1 for minimization fitness = (1 - objCoverage) * this.weightCoverage + (1 - objFaultDetectionCoverage) * this.weightFaultDetection; } else { fitness = 1; // this solution is bad since it exceeds the alloted time budget } return NumericObjectiveValue.lowerIsBetterObjectiveValue(fitness, 0); } // select the test cases and return them protected List<TestCase> selectTestCases(Vector vector) { List<TestCase> selectedTestSuite = new ArrayList<TestCase>(); int count = 0;
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // // Path: src/main/java/org/avmframework/variable/Variable.java // public interface Variable { // // void setValueToInitial(); // // void setValueToRandom(RandomGenerator randomGenerator); // // Variable deepCopy(); // } // Path: src/main/java/org/avmframework/examples/testoptimization/SelectionObjectiveFunction.java import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import org.avmframework.variable.Variable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; Set<String> coveredCoverageSet = new HashSet<String>(); for (int i = 0; i < selectedTestSuite.size(); i++) { TestCase tempCase = selectedTestSuite.get(i); coveredCoverageSet.addAll(tempCase.getApiCovered()); executionTime += tempCase.getTime(); fdc += tempCase.getFaultDetection(); } double fitness; // convert time budget from percentage to real number if (executionTime <= (transitionStateCoverage.getExecutionTime() * timeBudget / 100)) { double objCoverage; double objFaultDetectionCoverage; objCoverage = coveredCoverageSet.size() / transitionStateCoverage.getCoverage().size(); objFaultDetectionCoverage = fdc / transitionStateCoverage.getFaultDetection(); // subtract 1 for minimization fitness = (1 - objCoverage) * this.weightCoverage + (1 - objFaultDetectionCoverage) * this.weightFaultDetection; } else { fitness = 1; // this solution is bad since it exceeds the alloted time budget } return NumericObjectiveValue.lowerIsBetterObjectiveValue(fitness, 0); } // select the test cases and return them protected List<TestCase> selectTestCases(Vector vector) { List<TestCase> selectedTestSuite = new ArrayList<TestCase>(); int count = 0;
for (Variable variable : vector.getVariables()) {
AVMf/avmf
src/main/java/org/avmframework/examples/testoptimization/PrioritizationObjectiveFunction.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set;
coveredCoverageSet.addAll(testCase.getApiCovered()); // to get the number of unique apis covered by this test case int afterCoverage = coveredCoverageSet.size() - beforeCoverage; coverageCal += ((double) (afterCoverage)) * ((double) (orderedTestSuite.size() - i) / orderedTestSuite.size()); fdcCal += ((double) (testCase.getFaultDetection())) * ((double) (orderedTestSuite.size() - i) / orderedTestSuite.size()); timeCalc += ((double) (testCase.getTime())) * ((double) (orderedTestSuite.size() - i) / orderedTestSuite.size()); } } double objCoverage; double objFaultDetectionCoverage; double objTime; // divide by maximum of all the test cases in the test suite objCoverage = coverageCal / transitionStateCoverage.getCoverage().size(); objFaultDetectionCoverage = fdcCal / transitionStateCoverage.getFaultDetection(); objTime = timeCalc / transitionStateCoverage.getExecutionTime(); // subtract 1 for minimization, 1 is not subtracted for objTime because minimum time is better double fitness = (1 - objCoverage) * this.weightCoverage + (1 - objFaultDetectionCoverage) * this.weightFaultDetection + objTime * this.weightTime;
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/examples/testoptimization/PrioritizationObjectiveFunction.java import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; coveredCoverageSet.addAll(testCase.getApiCovered()); // to get the number of unique apis covered by this test case int afterCoverage = coveredCoverageSet.size() - beforeCoverage; coverageCal += ((double) (afterCoverage)) * ((double) (orderedTestSuite.size() - i) / orderedTestSuite.size()); fdcCal += ((double) (testCase.getFaultDetection())) * ((double) (orderedTestSuite.size() - i) / orderedTestSuite.size()); timeCalc += ((double) (testCase.getTime())) * ((double) (orderedTestSuite.size() - i) / orderedTestSuite.size()); } } double objCoverage; double objFaultDetectionCoverage; double objTime; // divide by maximum of all the test cases in the test suite objCoverage = coverageCal / transitionStateCoverage.getCoverage().size(); objFaultDetectionCoverage = fdcCal / transitionStateCoverage.getFaultDetection(); objTime = timeCalc / transitionStateCoverage.getExecutionTime(); // subtract 1 for minimization, 1 is not subtracted for objTime because minimum time is better double fitness = (1 - objCoverage) * this.weightCoverage + (1 - objFaultDetectionCoverage) * this.weightFaultDetection + objTime * this.weightTime;
return NumericObjectiveValue.lowerIsBetterObjectiveValue(fitness, 0);
AVMf/avmf
src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class IteratedPatternSearch extends PatternSearch { public IteratedPatternSearch() {} public IteratedPatternSearch(int accelerationFactor) { super(accelerationFactor); }
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class IteratedPatternSearch extends PatternSearch { public IteratedPatternSearch() {} public IteratedPatternSearch(int accelerationFactor) { super(accelerationFactor); }
protected void performSearch() throws TerminationException {
AVMf/avmf
src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class IteratedPatternSearch extends PatternSearch { public IteratedPatternSearch() {} public IteratedPatternSearch(int accelerationFactor) { super(accelerationFactor); } protected void performSearch() throws TerminationException {
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class IteratedPatternSearch extends PatternSearch { public IteratedPatternSearch() {} public IteratedPatternSearch(int accelerationFactor) { super(accelerationFactor); } protected void performSearch() throws TerminationException {
ObjectiveValue next = objFun.evaluate(vector);
AVMf/avmf
src/test/java/org/avmframework/TestTermination.java
// Path: src/test/java/org/avmframework/AlternatingVariableMethods.java // public static AlternatingVariableMethod anyAlternatingVariableMethodWithTerminationPolicy( // TerminationPolicy tp) { // return new AlternatingVariableMethod(new IteratedPatternSearch(), tp, new DefaultInitializer()); // } // // Path: src/test/java/org/avmframework/ObjectiveFunctions.java // public static ObjectiveFunction flat() { // ObjectiveFunction objFun = // new ObjectiveFunction() { // @Override // protected ObjectiveValue computeObjectiveValue(Vector vector) { // return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); // } // }; // return objFun; // } // // Path: src/test/java/org/avmframework/Vectors.java // public static Vector singleIntegerVector() { // return integerVector(1); // }
import static junit.framework.TestCase.assertTrue; import static org.avmframework.AlternatingVariableMethods.anyAlternatingVariableMethodWithTerminationPolicy; import static org.avmframework.ObjectiveFunctions.flat; import static org.avmframework.Vectors.singleIntegerVector; import static org.junit.Assert.assertEquals; import org.junit.Test;
package org.avmframework; public class TestTermination { @Test public void testNoRestart() { testRestarts(0); } @Test public void testOneRestart() { testRestarts(1); } @Test public void testTwoRestarts() { testRestarts(2); } protected void testRestarts(int limit) { TerminationPolicy tp = TerminationPolicy.createMaxRestartsTerminationPolicy(limit);
// Path: src/test/java/org/avmframework/AlternatingVariableMethods.java // public static AlternatingVariableMethod anyAlternatingVariableMethodWithTerminationPolicy( // TerminationPolicy tp) { // return new AlternatingVariableMethod(new IteratedPatternSearch(), tp, new DefaultInitializer()); // } // // Path: src/test/java/org/avmframework/ObjectiveFunctions.java // public static ObjectiveFunction flat() { // ObjectiveFunction objFun = // new ObjectiveFunction() { // @Override // protected ObjectiveValue computeObjectiveValue(Vector vector) { // return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); // } // }; // return objFun; // } // // Path: src/test/java/org/avmframework/Vectors.java // public static Vector singleIntegerVector() { // return integerVector(1); // } // Path: src/test/java/org/avmframework/TestTermination.java import static junit.framework.TestCase.assertTrue; import static org.avmframework.AlternatingVariableMethods.anyAlternatingVariableMethodWithTerminationPolicy; import static org.avmframework.ObjectiveFunctions.flat; import static org.avmframework.Vectors.singleIntegerVector; import static org.junit.Assert.assertEquals; import org.junit.Test; package org.avmframework; public class TestTermination { @Test public void testNoRestart() { testRestarts(0); } @Test public void testOneRestart() { testRestarts(1); } @Test public void testTwoRestarts() { testRestarts(2); } protected void testRestarts(int limit) { TerminationPolicy tp = TerminationPolicy.createMaxRestartsTerminationPolicy(limit);
AlternatingVariableMethod avm = anyAlternatingVariableMethodWithTerminationPolicy(tp);
AVMf/avmf
src/test/java/org/avmframework/TestTermination.java
// Path: src/test/java/org/avmframework/AlternatingVariableMethods.java // public static AlternatingVariableMethod anyAlternatingVariableMethodWithTerminationPolicy( // TerminationPolicy tp) { // return new AlternatingVariableMethod(new IteratedPatternSearch(), tp, new DefaultInitializer()); // } // // Path: src/test/java/org/avmframework/ObjectiveFunctions.java // public static ObjectiveFunction flat() { // ObjectiveFunction objFun = // new ObjectiveFunction() { // @Override // protected ObjectiveValue computeObjectiveValue(Vector vector) { // return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); // } // }; // return objFun; // } // // Path: src/test/java/org/avmframework/Vectors.java // public static Vector singleIntegerVector() { // return integerVector(1); // }
import static junit.framework.TestCase.assertTrue; import static org.avmframework.AlternatingVariableMethods.anyAlternatingVariableMethodWithTerminationPolicy; import static org.avmframework.ObjectiveFunctions.flat; import static org.avmframework.Vectors.singleIntegerVector; import static org.junit.Assert.assertEquals; import org.junit.Test;
package org.avmframework; public class TestTermination { @Test public void testNoRestart() { testRestarts(0); } @Test public void testOneRestart() { testRestarts(1); } @Test public void testTwoRestarts() { testRestarts(2); } protected void testRestarts(int limit) { TerminationPolicy tp = TerminationPolicy.createMaxRestartsTerminationPolicy(limit); AlternatingVariableMethod avm = anyAlternatingVariableMethodWithTerminationPolicy(tp);
// Path: src/test/java/org/avmframework/AlternatingVariableMethods.java // public static AlternatingVariableMethod anyAlternatingVariableMethodWithTerminationPolicy( // TerminationPolicy tp) { // return new AlternatingVariableMethod(new IteratedPatternSearch(), tp, new DefaultInitializer()); // } // // Path: src/test/java/org/avmframework/ObjectiveFunctions.java // public static ObjectiveFunction flat() { // ObjectiveFunction objFun = // new ObjectiveFunction() { // @Override // protected ObjectiveValue computeObjectiveValue(Vector vector) { // return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); // } // }; // return objFun; // } // // Path: src/test/java/org/avmframework/Vectors.java // public static Vector singleIntegerVector() { // return integerVector(1); // } // Path: src/test/java/org/avmframework/TestTermination.java import static junit.framework.TestCase.assertTrue; import static org.avmframework.AlternatingVariableMethods.anyAlternatingVariableMethodWithTerminationPolicy; import static org.avmframework.ObjectiveFunctions.flat; import static org.avmframework.Vectors.singleIntegerVector; import static org.junit.Assert.assertEquals; import org.junit.Test; package org.avmframework; public class TestTermination { @Test public void testNoRestart() { testRestarts(0); } @Test public void testOneRestart() { testRestarts(1); } @Test public void testTwoRestarts() { testRestarts(2); } protected void testRestarts(int limit) { TerminationPolicy tp = TerminationPolicy.createMaxRestartsTerminationPolicy(limit); AlternatingVariableMethod avm = anyAlternatingVariableMethodWithTerminationPolicy(tp);
Monitor monitor = avm.search(singleIntegerVector(), flat());
AVMf/avmf
src/test/java/org/avmframework/TestTermination.java
// Path: src/test/java/org/avmframework/AlternatingVariableMethods.java // public static AlternatingVariableMethod anyAlternatingVariableMethodWithTerminationPolicy( // TerminationPolicy tp) { // return new AlternatingVariableMethod(new IteratedPatternSearch(), tp, new DefaultInitializer()); // } // // Path: src/test/java/org/avmframework/ObjectiveFunctions.java // public static ObjectiveFunction flat() { // ObjectiveFunction objFun = // new ObjectiveFunction() { // @Override // protected ObjectiveValue computeObjectiveValue(Vector vector) { // return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); // } // }; // return objFun; // } // // Path: src/test/java/org/avmframework/Vectors.java // public static Vector singleIntegerVector() { // return integerVector(1); // }
import static junit.framework.TestCase.assertTrue; import static org.avmframework.AlternatingVariableMethods.anyAlternatingVariableMethodWithTerminationPolicy; import static org.avmframework.ObjectiveFunctions.flat; import static org.avmframework.Vectors.singleIntegerVector; import static org.junit.Assert.assertEquals; import org.junit.Test;
package org.avmframework; public class TestTermination { @Test public void testNoRestart() { testRestarts(0); } @Test public void testOneRestart() { testRestarts(1); } @Test public void testTwoRestarts() { testRestarts(2); } protected void testRestarts(int limit) { TerminationPolicy tp = TerminationPolicy.createMaxRestartsTerminationPolicy(limit); AlternatingVariableMethod avm = anyAlternatingVariableMethodWithTerminationPolicy(tp);
// Path: src/test/java/org/avmframework/AlternatingVariableMethods.java // public static AlternatingVariableMethod anyAlternatingVariableMethodWithTerminationPolicy( // TerminationPolicy tp) { // return new AlternatingVariableMethod(new IteratedPatternSearch(), tp, new DefaultInitializer()); // } // // Path: src/test/java/org/avmframework/ObjectiveFunctions.java // public static ObjectiveFunction flat() { // ObjectiveFunction objFun = // new ObjectiveFunction() { // @Override // protected ObjectiveValue computeObjectiveValue(Vector vector) { // return NumericObjectiveValue.higherIsBetterObjectiveValue(1.0); // } // }; // return objFun; // } // // Path: src/test/java/org/avmframework/Vectors.java // public static Vector singleIntegerVector() { // return integerVector(1); // } // Path: src/test/java/org/avmframework/TestTermination.java import static junit.framework.TestCase.assertTrue; import static org.avmframework.AlternatingVariableMethods.anyAlternatingVariableMethodWithTerminationPolicy; import static org.avmframework.ObjectiveFunctions.flat; import static org.avmframework.Vectors.singleIntegerVector; import static org.junit.Assert.assertEquals; import org.junit.Test; package org.avmframework; public class TestTermination { @Test public void testNoRestart() { testRestarts(0); } @Test public void testOneRestart() { testRestarts(1); } @Test public void testTwoRestarts() { testRestarts(2); } protected void testRestarts(int limit) { TerminationPolicy tp = TerminationPolicy.createMaxRestartsTerminationPolicy(limit); AlternatingVariableMethod avm = anyAlternatingVariableMethodWithTerminationPolicy(tp);
Monitor monitor = avm.search(singleIntegerVector(), flat());
AVMf/avmf
src/main/java/org/avmframework/localsearch/LocalSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/variable/AtomicVariable.java // public abstract class AtomicVariable implements Variable { // // protected int min; // protected int max; // // protected int initialValue; // protected int value; // // public AtomicVariable(int initialValue, int min, int max) { // this.initialValue = initialValue; // this.min = min; // this.max = max; // } // // public int getMin() { // return min; // } // // public int getMax() { // return max; // } // // @Override // public void setValueToInitial() { // setValue(initialValue); // } // // @Override // public void setValueToRandom(RandomGenerator randomGenerator) { // int range = max - min + 1; // int randomValue = randomGenerator.nextInt(range); // setValue(min + randomValue); // } // // public void setValue(int value) { // if (value > max) { // value = max; // } // // if (value < min) { // value = min; // } // // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // AtomicVariable that = (AtomicVariable) obj; // // if (min != that.min) { // return false; // } // if (max != that.max) { // return false; // } // if (initialValue != that.initialValue) { // return false; // } // return value == that.value; // } // // @Override // public int hashCode() { // int result = min; // result = 31 * result + max; // result = 31 * result + initialValue; // result = 31 * result + value; // return result; // } // }
import org.avmframework.TerminationException; import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.variable.AtomicVariable;
package org.avmframework.localsearch; public abstract class LocalSearch { protected AtomicVariable var;
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/variable/AtomicVariable.java // public abstract class AtomicVariable implements Variable { // // protected int min; // protected int max; // // protected int initialValue; // protected int value; // // public AtomicVariable(int initialValue, int min, int max) { // this.initialValue = initialValue; // this.min = min; // this.max = max; // } // // public int getMin() { // return min; // } // // public int getMax() { // return max; // } // // @Override // public void setValueToInitial() { // setValue(initialValue); // } // // @Override // public void setValueToRandom(RandomGenerator randomGenerator) { // int range = max - min + 1; // int randomValue = randomGenerator.nextInt(range); // setValue(min + randomValue); // } // // public void setValue(int value) { // if (value > max) { // value = max; // } // // if (value < min) { // value = min; // } // // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // AtomicVariable that = (AtomicVariable) obj; // // if (min != that.min) { // return false; // } // if (max != that.max) { // return false; // } // if (initialValue != that.initialValue) { // return false; // } // return value == that.value; // } // // @Override // public int hashCode() { // int result = min; // result = 31 * result + max; // result = 31 * result + initialValue; // result = 31 * result + value; // return result; // } // } // Path: src/main/java/org/avmframework/localsearch/LocalSearch.java import org.avmframework.TerminationException; import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.variable.AtomicVariable; package org.avmframework.localsearch; public abstract class LocalSearch { protected AtomicVariable var;
protected Vector vector;
AVMf/avmf
src/main/java/org/avmframework/localsearch/LocalSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/variable/AtomicVariable.java // public abstract class AtomicVariable implements Variable { // // protected int min; // protected int max; // // protected int initialValue; // protected int value; // // public AtomicVariable(int initialValue, int min, int max) { // this.initialValue = initialValue; // this.min = min; // this.max = max; // } // // public int getMin() { // return min; // } // // public int getMax() { // return max; // } // // @Override // public void setValueToInitial() { // setValue(initialValue); // } // // @Override // public void setValueToRandom(RandomGenerator randomGenerator) { // int range = max - min + 1; // int randomValue = randomGenerator.nextInt(range); // setValue(min + randomValue); // } // // public void setValue(int value) { // if (value > max) { // value = max; // } // // if (value < min) { // value = min; // } // // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // AtomicVariable that = (AtomicVariable) obj; // // if (min != that.min) { // return false; // } // if (max != that.max) { // return false; // } // if (initialValue != that.initialValue) { // return false; // } // return value == that.value; // } // // @Override // public int hashCode() { // int result = min; // result = 31 * result + max; // result = 31 * result + initialValue; // result = 31 * result + value; // return result; // } // }
import org.avmframework.TerminationException; import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.variable.AtomicVariable;
package org.avmframework.localsearch; public abstract class LocalSearch { protected AtomicVariable var; protected Vector vector;
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/variable/AtomicVariable.java // public abstract class AtomicVariable implements Variable { // // protected int min; // protected int max; // // protected int initialValue; // protected int value; // // public AtomicVariable(int initialValue, int min, int max) { // this.initialValue = initialValue; // this.min = min; // this.max = max; // } // // public int getMin() { // return min; // } // // public int getMax() { // return max; // } // // @Override // public void setValueToInitial() { // setValue(initialValue); // } // // @Override // public void setValueToRandom(RandomGenerator randomGenerator) { // int range = max - min + 1; // int randomValue = randomGenerator.nextInt(range); // setValue(min + randomValue); // } // // public void setValue(int value) { // if (value > max) { // value = max; // } // // if (value < min) { // value = min; // } // // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // AtomicVariable that = (AtomicVariable) obj; // // if (min != that.min) { // return false; // } // if (max != that.max) { // return false; // } // if (initialValue != that.initialValue) { // return false; // } // return value == that.value; // } // // @Override // public int hashCode() { // int result = min; // result = 31 * result + max; // result = 31 * result + initialValue; // result = 31 * result + value; // return result; // } // } // Path: src/main/java/org/avmframework/localsearch/LocalSearch.java import org.avmframework.TerminationException; import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.variable.AtomicVariable; package org.avmframework.localsearch; public abstract class LocalSearch { protected AtomicVariable var; protected Vector vector;
protected ObjectiveFunction objFun;
AVMf/avmf
src/main/java/org/avmframework/localsearch/LocalSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/variable/AtomicVariable.java // public abstract class AtomicVariable implements Variable { // // protected int min; // protected int max; // // protected int initialValue; // protected int value; // // public AtomicVariable(int initialValue, int min, int max) { // this.initialValue = initialValue; // this.min = min; // this.max = max; // } // // public int getMin() { // return min; // } // // public int getMax() { // return max; // } // // @Override // public void setValueToInitial() { // setValue(initialValue); // } // // @Override // public void setValueToRandom(RandomGenerator randomGenerator) { // int range = max - min + 1; // int randomValue = randomGenerator.nextInt(range); // setValue(min + randomValue); // } // // public void setValue(int value) { // if (value > max) { // value = max; // } // // if (value < min) { // value = min; // } // // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // AtomicVariable that = (AtomicVariable) obj; // // if (min != that.min) { // return false; // } // if (max != that.max) { // return false; // } // if (initialValue != that.initialValue) { // return false; // } // return value == that.value; // } // // @Override // public int hashCode() { // int result = min; // result = 31 * result + max; // result = 31 * result + initialValue; // result = 31 * result + value; // return result; // } // }
import org.avmframework.TerminationException; import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.variable.AtomicVariable;
package org.avmframework.localsearch; public abstract class LocalSearch { protected AtomicVariable var; protected Vector vector; protected ObjectiveFunction objFun; public void search(AtomicVariable var, Vector vector, ObjectiveFunction objFun)
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/variable/AtomicVariable.java // public abstract class AtomicVariable implements Variable { // // protected int min; // protected int max; // // protected int initialValue; // protected int value; // // public AtomicVariable(int initialValue, int min, int max) { // this.initialValue = initialValue; // this.min = min; // this.max = max; // } // // public int getMin() { // return min; // } // // public int getMax() { // return max; // } // // @Override // public void setValueToInitial() { // setValue(initialValue); // } // // @Override // public void setValueToRandom(RandomGenerator randomGenerator) { // int range = max - min + 1; // int randomValue = randomGenerator.nextInt(range); // setValue(min + randomValue); // } // // public void setValue(int value) { // if (value > max) { // value = max; // } // // if (value < min) { // value = min; // } // // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // // AtomicVariable that = (AtomicVariable) obj; // // if (min != that.min) { // return false; // } // if (max != that.max) { // return false; // } // if (initialValue != that.initialValue) { // return false; // } // return value == that.value; // } // // @Override // public int hashCode() { // int result = min; // result = 31 * result + max; // result = 31 * result + initialValue; // result = 31 * result + value; // return result; // } // } // Path: src/main/java/org/avmframework/localsearch/LocalSearch.java import org.avmframework.TerminationException; import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.variable.AtomicVariable; package org.avmframework.localsearch; public abstract class LocalSearch { protected AtomicVariable var; protected Vector vector; protected ObjectiveFunction objFun; public void search(AtomicVariable var, Vector vector, ObjectiveFunction objFun)
throws TerminationException {
AVMf/avmf
src/main/java/org/avmframework/examples/inputdatageneration/BranchTargetObjectiveFunction.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.examples.inputdatageneration; public abstract class BranchTargetObjectiveFunction extends ObjectiveFunction { protected Branch target; protected ControlDependenceChain controlDependenceChain; protected ExecutionTrace trace; public BranchTargetObjectiveFunction(Branch target) { this.target = target; this.controlDependenceChain = getControlDependenceChainForTarget(); } protected abstract ControlDependenceChain getControlDependenceChainForTarget();
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/examples/inputdatageneration/BranchTargetObjectiveFunction.java import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; package org.avmframework.examples.inputdatageneration; public abstract class BranchTargetObjectiveFunction extends ObjectiveFunction { protected Branch target; protected ControlDependenceChain controlDependenceChain; protected ExecutionTrace trace; public BranchTargetObjectiveFunction(Branch target) { this.target = target; this.controlDependenceChain = getControlDependenceChainForTarget(); } protected abstract ControlDependenceChain getControlDependenceChainForTarget();
protected ObjectiveValue computeObjectiveValue(Vector vector) {
AVMf/avmf
src/main/java/org/avmframework/examples/inputdatageneration/BranchTargetObjectiveFunction.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.examples.inputdatageneration; public abstract class BranchTargetObjectiveFunction extends ObjectiveFunction { protected Branch target; protected ControlDependenceChain controlDependenceChain; protected ExecutionTrace trace; public BranchTargetObjectiveFunction(Branch target) { this.target = target; this.controlDependenceChain = getControlDependenceChainForTarget(); } protected abstract ControlDependenceChain getControlDependenceChainForTarget();
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/examples/inputdatageneration/BranchTargetObjectiveFunction.java import org.avmframework.Vector; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; package org.avmframework.examples.inputdatageneration; public abstract class BranchTargetObjectiveFunction extends ObjectiveFunction { protected Branch target; protected ControlDependenceChain controlDependenceChain; protected ExecutionTrace trace; public BranchTargetObjectiveFunction(Branch target) { this.target = target; this.controlDependenceChain = getControlDependenceChainForTarget(); } protected abstract ControlDependenceChain getControlDependenceChainForTarget();
protected ObjectiveValue computeObjectiveValue(Vector vector) {
AVMf/avmf
src/test/java/org/avmframework/localsearch/TestIntegerFibonacciNumbers.java
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int maxPosition() { // return numbers.size(); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // }
import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.maxPosition; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test;
package org.avmframework.localsearch; public class TestIntegerFibonacciNumbers { @Test public void testSequence() {
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int maxPosition() { // return numbers.size(); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // Path: src/test/java/org/avmframework/localsearch/TestIntegerFibonacciNumbers.java import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.maxPosition; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test; package org.avmframework.localsearch; public class TestIntegerFibonacciNumbers { @Test public void testSequence() {
for (int i = 2; i < maxPosition(); i++) {
AVMf/avmf
src/test/java/org/avmframework/localsearch/TestIntegerFibonacciNumbers.java
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int maxPosition() { // return numbers.size(); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // }
import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.maxPosition; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test;
package org.avmframework.localsearch; public class TestIntegerFibonacciNumbers { @Test public void testSequence() { for (int i = 2; i < maxPosition(); i++) {
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int maxPosition() { // return numbers.size(); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // Path: src/test/java/org/avmframework/localsearch/TestIntegerFibonacciNumbers.java import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.maxPosition; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test; package org.avmframework.localsearch; public class TestIntegerFibonacciNumbers { @Test public void testSequence() { for (int i = 2; i < maxPosition(); i++) {
assertEquals(fibonacci(i), fibonacci(i - 1) + fibonacci(i - 2));
AVMf/avmf
src/test/java/org/avmframework/localsearch/TestIntegerFibonacciNumbers.java
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int maxPosition() { // return numbers.size(); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // }
import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.maxPosition; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test;
package org.avmframework.localsearch; public class TestIntegerFibonacciNumbers { @Test public void testSequence() { for (int i = 2; i < maxPosition(); i++) { assertEquals(fibonacci(i), fibonacci(i - 1) + fibonacci(i - 2)); } } @Test public void testIndexOflowestFibonacciGreaterThan() {
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int maxPosition() { // return numbers.size(); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // Path: src/test/java/org/avmframework/localsearch/TestIntegerFibonacciNumbers.java import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.maxPosition; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test; package org.avmframework.localsearch; public class TestIntegerFibonacciNumbers { @Test public void testSequence() { for (int i = 2; i < maxPosition(); i++) { assertEquals(fibonacci(i), fibonacci(i - 1) + fibonacci(i - 2)); } } @Test public void testIndexOflowestFibonacciGreaterThan() {
assertEquals(0, positionOfSmallestFibonacciNumberGreaterOrEqualTo(0));
AVMf/avmf
src/test/java/org/avmframework/examples/inputdatageneration/line/TestLineObjectiveFunction.java
// Path: src/main/java/org/avmframework/examples/inputdatageneration/ExecutionTrace.java // public class ExecutionTrace { // // protected List<BranchExection> branchExecutions = new LinkedList<>(); // // public boolean isTrue(int id, boolean bool) { // return equals(id, bool, true); // } // // public boolean isFalse(int id, boolean bool) { // return equals(id, bool, false); // } // // public boolean equals(int id, boolean bool1, boolean bool2) { // return equals(id, bool1 ? 1.0 : 0, bool2 ? 1.0 : 0); // } // // public boolean equals(int id, double num1, double num2) { // boolean outcome = (num1 == num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.notEquals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.equals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean notEquals(int id, boolean bool1, boolean bool2) { // return equals(id, bool1 ? 1.0 : 0, bool2 ? 1.0 : 0); // } // // public boolean notEquals(int id, double num1, double num2) { // boolean outcome = (num1 != num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.equals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.notEquals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean lessThanOrEquals(int id, double num1, double num2) { // boolean outcome = (num1 <= num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.greaterThan(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.lessThanOrEquals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean lessThan(int id, double num1, double num2) { // boolean outcome = (num1 < num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.greaterThanOrEquals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.lessThan(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean greaterThanOrEquals(int id, double num1, double num2) { // boolean outcome = (num1 >= num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.lessThan(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.greaterThanOrEquals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean greaterThan(int id, double num1, double num2) { // boolean outcome = (num1 > num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.lessThanOrEquals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.greaterThan(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public List<BranchExection> getBranchExecutions() { // return new LinkedList<>(branchExecutions); // } // // public BranchExection getBranchExecution(int index) { // return branchExecutions.get(index); // } // // @Override // public String toString() { // return branchExecutions.toString(); // } // }
import static org.junit.Assert.assertEquals; import org.avmframework.examples.inputdatageneration.ExecutionTrace; import org.junit.Test;
package org.avmframework.examples.inputdatageneration.line; public class TestLineObjectiveFunction { class LineObjectiveFunctionTrace extends LineBranchTargetObjectiveFunction { public LineObjectiveFunctionTrace() { super(null); }
// Path: src/main/java/org/avmframework/examples/inputdatageneration/ExecutionTrace.java // public class ExecutionTrace { // // protected List<BranchExection> branchExecutions = new LinkedList<>(); // // public boolean isTrue(int id, boolean bool) { // return equals(id, bool, true); // } // // public boolean isFalse(int id, boolean bool) { // return equals(id, bool, false); // } // // public boolean equals(int id, boolean bool1, boolean bool2) { // return equals(id, bool1 ? 1.0 : 0, bool2 ? 1.0 : 0); // } // // public boolean equals(int id, double num1, double num2) { // boolean outcome = (num1 == num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.notEquals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.equals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean notEquals(int id, boolean bool1, boolean bool2) { // return equals(id, bool1 ? 1.0 : 0, bool2 ? 1.0 : 0); // } // // public boolean notEquals(int id, double num1, double num2) { // boolean outcome = (num1 != num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.equals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.notEquals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean lessThanOrEquals(int id, double num1, double num2) { // boolean outcome = (num1 <= num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.greaterThan(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.lessThanOrEquals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean lessThan(int id, double num1, double num2) { // boolean outcome = (num1 < num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.greaterThanOrEquals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.lessThan(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean greaterThanOrEquals(int id, double num1, double num2) { // boolean outcome = (num1 >= num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.lessThan(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.greaterThanOrEquals(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public boolean greaterThan(int id, double num1, double num2) { // boolean outcome = (num1 > num2); // double distanceToAlternative; // if (outcome) { // distanceToAlternative = DistanceFunctions.lessThanOrEquals(num1, num2); // } else { // distanceToAlternative = DistanceFunctions.greaterThan(num1, num2); // } // branchExecutions.add(new BranchExection(id, outcome, distanceToAlternative)); // return outcome; // } // // public List<BranchExection> getBranchExecutions() { // return new LinkedList<>(branchExecutions); // } // // public BranchExection getBranchExecution(int index) { // return branchExecutions.get(index); // } // // @Override // public String toString() { // return branchExecutions.toString(); // } // } // Path: src/test/java/org/avmframework/examples/inputdatageneration/line/TestLineObjectiveFunction.java import static org.junit.Assert.assertEquals; import org.avmframework.examples.inputdatageneration.ExecutionTrace; import org.junit.Test; package org.avmframework.examples.inputdatageneration.line; public class TestLineObjectiveFunction { class LineObjectiveFunctionTrace extends LineBranchTargetObjectiveFunction { public LineObjectiveFunctionTrace() { super(null); }
public ExecutionTrace getTrace(Line line1, Line line2) {
AVMf/avmf
src/main/java/org/avmframework/examples/requirementassignment/RequirementObjectiveFunction.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List;
} famAvg = totalFm / assignedNumber; for (int i = 0; i < wl.length; i++) { if (number[i] != 0) { wl[i] = wl[i] / number[i]; } } for (int i = 0; i < numberOfStakeholders - 1; i++) { for (int j = i + 1; j < numberOfStakeholders; j++) { webOntologyLanguageDiffAvg += Math.abs(wl[i] - wl[j]); } } webOntologyLanguageDiffAvg = webOntologyLanguageDiffAvg / (numberOfStakeholders * (numberOfStakeholders - 1)); double objAssignedDis; double objFamAvg; double objWebOntologyLanguageDiffAvg; objAssignedDis = numFormat(assignedDis); objFamAvg = numFormat(famAvg); objWebOntologyLanguageDiffAvg = numFormat(webOntologyLanguageDiffAvg); // fitness need to be minimized so we subtract 1 from objAssignedDis and objFamAvg double fitness = (1 - objAssignedDis) * this.weightAssignedDis + (1 - objFamAvg) * this.weightFamAvg + (objWebOntologyLanguageDiffAvg) * this.weightWlDiff;
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/objective/NumericObjectiveValue.java // public class NumericObjectiveValue extends ObjectiveValue<NumericObjectiveValue> { // // protected double value; // protected boolean higherIsBetter; // // protected boolean haveOptimum = false; // protected double optimum; // // public NumericObjectiveValue(double value, boolean higherIsBetter) { // this.value = value; // this.higherIsBetter = higherIsBetter; // } // // public NumericObjectiveValue(double value, boolean higherIsBetter, double optimum) { // this(value, higherIsBetter); // this.haveOptimum = true; // this.optimum = optimum; // } // // public double getValue() { // return value; // } // // @Override // public boolean isOptimal() { // if (!haveOptimum) { // return false; // } // // if (higherIsBetter) { // return value >= optimum; // } else { // return value <= optimum; // } // } // // @Override // public int compareTo(NumericObjectiveValue other) { // if (value == other.value) { // return 0; // } else if (value < other.value) { // return higherIsBetter ? -1 : 1; // } else { // return higherIsBetter ? 1 : -1; // } // } // // @Override // public String toString() { // return "" + getValue(); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, true); // } // // public static NumericObjectiveValue higherIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, true, optimum); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value) { // return new NumericObjectiveValue(value, false); // } // // public static NumericObjectiveValue lowerIsBetterObjectiveValue(double value, double optimum) { // return new NumericObjectiveValue(value, false, optimum); // } // } // // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java // public abstract class ObjectiveFunction { // // public static final boolean USE_CACHE_DEFAULT = true; // // protected boolean useCache = USE_CACHE_DEFAULT; // protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); // protected Monitor monitor; // // public void setMonitor(Monitor monitor) { // this.monitor = monitor; // } // // public ObjectiveValue evaluate(Vector vector) throws TerminationException { // monitor.observeVector(); // // if (useCache && previousVals.containsKey(vector)) { // return previousVals.get(vector); // } // // ObjectiveValue objVal = computeObjectiveValue(vector); // // if (useCache) { // previousVals.put(vector.deepCopy(), objVal); // } // // if (monitor != null) { // monitor.observePreviouslyUnseenVector(vector, objVal); // } // // return objVal; // } // // protected abstract ObjectiveValue computeObjectiveValue(Vector vector); // } // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/examples/requirementassignment/RequirementObjectiveFunction.java import org.avmframework.Vector; import org.avmframework.objective.NumericObjectiveValue; import org.avmframework.objective.ObjectiveFunction; import org.avmframework.objective.ObjectiveValue; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; } famAvg = totalFm / assignedNumber; for (int i = 0; i < wl.length; i++) { if (number[i] != 0) { wl[i] = wl[i] / number[i]; } } for (int i = 0; i < numberOfStakeholders - 1; i++) { for (int j = i + 1; j < numberOfStakeholders; j++) { webOntologyLanguageDiffAvg += Math.abs(wl[i] - wl[j]); } } webOntologyLanguageDiffAvg = webOntologyLanguageDiffAvg / (numberOfStakeholders * (numberOfStakeholders - 1)); double objAssignedDis; double objFamAvg; double objWebOntologyLanguageDiffAvg; objAssignedDis = numFormat(assignedDis); objFamAvg = numFormat(famAvg); objWebOntologyLanguageDiffAvg = numFormat(webOntologyLanguageDiffAvg); // fitness need to be minimized so we subtract 1 from objAssignedDis and objFamAvg double fitness = (1 - objAssignedDis) * this.weightAssignedDis + (1 - objFamAvg) * this.weightFamAvg + (objWebOntologyLanguageDiffAvg) * this.weightWlDiff;
return NumericObjectiveValue.lowerIsBetterObjectiveValue(fitness, 0);
AVMf/avmf
src/main/java/org/avmframework/localsearch/LatticeSearch.java
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); }
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/LatticeSearch.java import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); }
protected void performEliminationSearch(int left, int right) throws TerminationException {
AVMf/avmf
src/main/java/org/avmframework/localsearch/LatticeSearch.java
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { int interval = right - left + 2;
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/LatticeSearch.java import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { int interval = right - left + 2;
int num = positionOfSmallestFibonacciNumberGreaterOrEqualTo(interval);
AVMf/avmf
src/main/java/org/avmframework/localsearch/LatticeSearch.java
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { int interval = right - left + 2; int num = positionOfSmallestFibonacciNumberGreaterOrEqualTo(interval); while (num > 3) {
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/LatticeSearch.java import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { int interval = right - left + 2; int num = positionOfSmallestFibonacciNumberGreaterOrEqualTo(interval); while (num > 3) {
int mid = left + fibonacci(num - 2) - 1;
AVMf/avmf
src/main/java/org/avmframework/localsearch/LatticeSearch.java
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { int interval = right - left + 2; int num = positionOfSmallestFibonacciNumberGreaterOrEqualTo(interval); while (num > 3) { int mid = left + fibonacci(num - 2) - 1; int midRight = left + fibonacci(num - 1) - 1; if (midRight <= right) { var.setValue(mid);
// Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int fibonacci(int position) { // if (position < 0 || position >= maxPosition()) { // throw new IntegerFibonacciNumberException( // "Cannot return fibonacci number at position " // + position // + " in sequences. Positions range from 0 to " // + maxPosition()); // } // return numbers.get(position); // } // // Path: src/main/java/org/avmframework/localsearch/IntegerFibonacciNumbers.java // static int positionOfSmallestFibonacciNumberGreaterOrEqualTo(int target) { // int num = -1; // do { // num++; // } // while (num < maxPosition() && fibonacci(num) < target); // return num; // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/LatticeSearch.java import static org.avmframework.localsearch.IntegerFibonacciNumbers.fibonacci; import static org.avmframework.localsearch.IntegerFibonacciNumbers.positionOfSmallestFibonacciNumberGreaterOrEqualTo; import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class LatticeSearch extends PatternThenEliminationSearch { public LatticeSearch() {} public LatticeSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { int interval = right - left + 2; int num = positionOfSmallestFibonacciNumberGreaterOrEqualTo(interval); while (num > 3) { int mid = left + fibonacci(num - 2) - 1; int midRight = left + fibonacci(num - 1) - 1; if (midRight <= right) { var.setValue(mid);
ObjectiveValue midObjVal = objFun.evaluate(vector);
AVMf/avmf
src/main/java/org/avmframework/localsearch/GeometricSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class GeometricSearch extends PatternThenEliminationSearch { public GeometricSearch() {} public GeometricSearch(int accelerationFactor) { super(accelerationFactor); }
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/GeometricSearch.java import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class GeometricSearch extends PatternThenEliminationSearch { public GeometricSearch() {} public GeometricSearch(int accelerationFactor) { super(accelerationFactor); }
protected void performEliminationSearch(int left, int right) throws TerminationException {
AVMf/avmf
src/main/java/org/avmframework/localsearch/GeometricSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class GeometricSearch extends PatternThenEliminationSearch { public GeometricSearch() {} public GeometricSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { while (left < right) { int mid = (int) Math.floor((left + right) / 2.0); int midRight = mid + 1; var.setValue(mid);
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/GeometricSearch.java import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class GeometricSearch extends PatternThenEliminationSearch { public GeometricSearch() {} public GeometricSearch(int accelerationFactor) { super(accelerationFactor); } protected void performEliminationSearch(int left, int right) throws TerminationException { while (left < right) { int mid = (int) Math.floor((left + right) / 2.0); int midRight = mid + 1; var.setValue(mid);
ObjectiveValue midObjVal = objFun.evaluate(vector);
AVMf/avmf
src/main/java/org/avmframework/localsearch/PatternThenEliminationSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {}
import org.avmframework.TerminationException;
package org.avmframework.localsearch; public abstract class PatternThenEliminationSearch extends PatternSearch { public PatternThenEliminationSearch() {} public PatternThenEliminationSearch(int accelerationFactor) { super(accelerationFactor); }
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // Path: src/main/java/org/avmframework/localsearch/PatternThenEliminationSearch.java import org.avmframework.TerminationException; package org.avmframework.localsearch; public abstract class PatternThenEliminationSearch extends PatternSearch { public PatternThenEliminationSearch() {} public PatternThenEliminationSearch(int accelerationFactor) { super(accelerationFactor); }
protected void performSearch() throws TerminationException {
AVMf/avmf
src/main/java/org/avmframework/examples/inputdatageneration/ExecutionTrace.java
// Path: src/main/java/org/avmframework/objective/DistanceFunctions.java // public class DistanceFunctions { // // public static double K = 1.0; // // public static double equals(boolean bool1, boolean bool2) { // if (bool1 == bool2) { // return 0; // } // return K; // } // // public static double equals(double num1, double num2) { // return Math.abs(num1 - num2) + K; // } // // public static double notEquals(boolean bool1, boolean bool2) { // if (bool1 != bool2) { // return 0; // } // return K; // } // // public static double notEquals(double num1, double num2) { // if (num1 == num2) { // return K; // } // return 0; // } // // public static double greaterThan(double num1, double num2) { // if (num1 > num2) { // return 0; // } // return (num2 - num1) + K; // } // // public static double greaterThanOrEquals(double num1, double num2) { // if (num1 >= num2) { // return 0; // } // return (num2 - num1) + K; // } // // public static double lessThan(double num1, double num2) { // if (num1 < num2) { // return 0; // } // return (num1 - num2) + K; // } // // public static double lessThanOrEquals(double num1, double num2) { // if (num1 <= num2) { // return 0; // } // return (num1 - num2) + K; // } // }
import org.avmframework.objective.DistanceFunctions; import java.util.LinkedList; import java.util.List;
package org.avmframework.examples.inputdatageneration; public class ExecutionTrace { protected List<BranchExection> branchExecutions = new LinkedList<>(); public boolean isTrue(int id, boolean bool) { return equals(id, bool, true); } public boolean isFalse(int id, boolean bool) { return equals(id, bool, false); } public boolean equals(int id, boolean bool1, boolean bool2) { return equals(id, bool1 ? 1.0 : 0, bool2 ? 1.0 : 0); } public boolean equals(int id, double num1, double num2) { boolean outcome = (num1 == num2); double distanceToAlternative; if (outcome) {
// Path: src/main/java/org/avmframework/objective/DistanceFunctions.java // public class DistanceFunctions { // // public static double K = 1.0; // // public static double equals(boolean bool1, boolean bool2) { // if (bool1 == bool2) { // return 0; // } // return K; // } // // public static double equals(double num1, double num2) { // return Math.abs(num1 - num2) + K; // } // // public static double notEquals(boolean bool1, boolean bool2) { // if (bool1 != bool2) { // return 0; // } // return K; // } // // public static double notEquals(double num1, double num2) { // if (num1 == num2) { // return K; // } // return 0; // } // // public static double greaterThan(double num1, double num2) { // if (num1 > num2) { // return 0; // } // return (num2 - num1) + K; // } // // public static double greaterThanOrEquals(double num1, double num2) { // if (num1 >= num2) { // return 0; // } // return (num2 - num1) + K; // } // // public static double lessThan(double num1, double num2) { // if (num1 < num2) { // return 0; // } // return (num1 - num2) + K; // } // // public static double lessThanOrEquals(double num1, double num2) { // if (num1 <= num2) { // return 0; // } // return (num1 - num2) + K; // } // } // Path: src/main/java/org/avmframework/examples/inputdatageneration/ExecutionTrace.java import org.avmframework.objective.DistanceFunctions; import java.util.LinkedList; import java.util.List; package org.avmframework.examples.inputdatageneration; public class ExecutionTrace { protected List<BranchExection> branchExecutions = new LinkedList<>(); public boolean isTrue(int id, boolean bool) { return equals(id, bool, true); } public boolean isFalse(int id, boolean bool) { return equals(id, bool, false); } public boolean equals(int id, boolean bool1, boolean bool2) { return equals(id, bool1 ? 1.0 : 0, bool2 ? 1.0 : 0); } public boolean equals(int id, double num1, double num2) { boolean outcome = (num1 == num2); double distanceToAlternative; if (outcome) {
distanceToAlternative = DistanceFunctions.notEquals(num1, num2);
AVMf/avmf
src/main/java/org/avmframework/examples/util/ArgsParser.java
// Path: src/main/java/org/avmframework/localsearch/LocalSearch.java // public abstract class LocalSearch { // // protected AtomicVariable var; // protected Vector vector; // protected ObjectiveFunction objFun; // // public void search(AtomicVariable var, Vector vector, ObjectiveFunction objFun) // throws TerminationException { // this.var = var; // this.objFun = objFun; // this.vector = vector; // // performSearch(); // } // // protected abstract void performSearch() throws TerminationException; // // public static LocalSearch instantiate(String name) { // try { // String localSearchClassName = "org.avmframework.localsearch." + name; // Class<?> localSearchClass = Class.forName(localSearchClassName); // return (LocalSearch) localSearchClass.newInstance(); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException exception) { // throw new RuntimeException("Unable to instantiate search \"" + name + "\""); // } // } // }
import org.apache.commons.lang3.StringUtils; import org.avmframework.localsearch.LocalSearch; import java.util.LinkedHashMap; import java.util.Map;
"[search]", "an optional parameter denoting which search to use " + "(e.g., \"IteratedPatternSearch\", \"GeometricSearch\" or \"LatticeSearch\")"); } public void addParam(String name, String description) { params.put(name, description); } public void error(String error) { System.out.println("ERROR: " + error); usage(); System.exit(1); } public void usage() { String usage = "USAGE: java " + classWithMainMethod + " " + StringUtils.join(params.keySet(), " ") + " \n" + " where: \n"; for (String paramName : params.keySet()) { usage += " - " + paramName + " is " + params.get(paramName) + "\n"; } System.out.println(usage); }
// Path: src/main/java/org/avmframework/localsearch/LocalSearch.java // public abstract class LocalSearch { // // protected AtomicVariable var; // protected Vector vector; // protected ObjectiveFunction objFun; // // public void search(AtomicVariable var, Vector vector, ObjectiveFunction objFun) // throws TerminationException { // this.var = var; // this.objFun = objFun; // this.vector = vector; // // performSearch(); // } // // protected abstract void performSearch() throws TerminationException; // // public static LocalSearch instantiate(String name) { // try { // String localSearchClassName = "org.avmframework.localsearch." + name; // Class<?> localSearchClass = Class.forName(localSearchClassName); // return (LocalSearch) localSearchClass.newInstance(); // } catch (ClassNotFoundException | InstantiationException | IllegalAccessException exception) { // throw new RuntimeException("Unable to instantiate search \"" + name + "\""); // } // } // } // Path: src/main/java/org/avmframework/examples/util/ArgsParser.java import org.apache.commons.lang3.StringUtils; import org.avmframework.localsearch.LocalSearch; import java.util.LinkedHashMap; import java.util.Map; "[search]", "an optional parameter denoting which search to use " + "(e.g., \"IteratedPatternSearch\", \"GeometricSearch\" or \"LatticeSearch\")"); } public void addParam(String name, String description) { params.put(name, description); } public void error(String error) { System.out.println("ERROR: " + error); usage(); System.exit(1); } public void usage() { String usage = "USAGE: java " + classWithMainMethod + " " + StringUtils.join(params.keySet(), " ") + " \n" + " where: \n"; for (String paramName : params.keySet()) { usage += " - " + paramName + " is " + params.get(paramName) + "\n"; } System.out.println(usage); }
public LocalSearch parseSearchParam(String defaultSearch) {
AVMf/avmf
src/main/java/org/avmframework/localsearch/PatternSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class PatternSearch extends LocalSearch { public static int ACCELERATION_FACTOR_DEFAULT = 2; protected int accelerationFactor = ACCELERATION_FACTOR_DEFAULT;
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/PatternSearch.java import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class PatternSearch extends LocalSearch { public static int ACCELERATION_FACTOR_DEFAULT = 2; protected int accelerationFactor = ACCELERATION_FACTOR_DEFAULT;
protected ObjectiveValue initial;
AVMf/avmf
src/main/java/org/avmframework/localsearch/PatternSearch.java
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // }
import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue;
package org.avmframework.localsearch; public class PatternSearch extends LocalSearch { public static int ACCELERATION_FACTOR_DEFAULT = 2; protected int accelerationFactor = ACCELERATION_FACTOR_DEFAULT; protected ObjectiveValue initial; protected ObjectiveValue last; protected ObjectiveValue next; protected int modifier; protected int num; protected int dir; public PatternSearch() {} public PatternSearch(int accelerationFactor) { this.accelerationFactor = accelerationFactor; }
// Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/objective/ObjectiveValue.java // public abstract class ObjectiveValue<T extends ObjectiveValue> implements Comparable<T> { // // public abstract boolean isOptimal(); // // public boolean betterThan(T other) { // return compareTo(other) > 0; // } // // public boolean sameAs(T other) { // return compareTo(other) == 0; // } // // public boolean worseThan(T other) { // return compareTo(other) < 0; // } // } // Path: src/main/java/org/avmframework/localsearch/PatternSearch.java import org.avmframework.TerminationException; import org.avmframework.objective.ObjectiveValue; package org.avmframework.localsearch; public class PatternSearch extends LocalSearch { public static int ACCELERATION_FACTOR_DEFAULT = 2; protected int accelerationFactor = ACCELERATION_FACTOR_DEFAULT; protected ObjectiveValue initial; protected ObjectiveValue last; protected ObjectiveValue next; protected int modifier; protected int num; protected int dir; public PatternSearch() {} public PatternSearch(int accelerationFactor) { this.accelerationFactor = accelerationFactor; }
protected void performSearch() throws TerminationException {
AVMf/avmf
src/main/java/org/avmframework/objective/ObjectiveFunction.java
// Path: src/main/java/org/avmframework/Monitor.java // public class Monitor { // // /** The termination policy being used by the search. */ // protected TerminationPolicy tp; // // /** The best objective value observed so far during hte search. */ // protected ObjectiveValue bestObjVal; // // /** The vector with the best objective value observed so far by the search. */ // protected Vector bestVector; // // /** // * The number of objective function evaluations that have taken place so far. The count includes // * non-unique vectors. So if the same vector is evaluated twice, both evaluations will be recorded // * by this counter. // */ // protected int numEvaluations; // // /** // * The number of unique objective function evaluations that have taken place so far. If a vector // * is evaluated more than once, this count should not increase. // */ // protected int numUniqueEvaluations; // // /** The number of times the AVM search has been restarted. */ // protected int numRestarts; // // /** The system time (in milliseconds) that the search was started. */ // protected long startTime; // // /** The system time (in milliseconds) that the search was ended. */ // protected long endTime; // // /** // * Constructs a Monitor instance. // * // * @param tp The termination policy being used by the search. // */ // public Monitor(TerminationPolicy tp) { // this.tp = tp; // bestObjVal = null; // bestVector = null; // numEvaluations = 0; // numUniqueEvaluations = 0; // numRestarts = 0; // startTime = System.currentTimeMillis(); // } // // /** // * Gets the best objective value observed by the search so far. // * // * @return THe best objective value. // */ // public ObjectiveValue getBestObjVal() { // return bestObjVal; // } // // /** // * Gets the vector with the best objective value observed by the search so far. // * // * @return The best vector. // */ // public Vector getBestVector() { // return bestVector; // } // // /** // * Gets the number of objective function evaluations that have taken place so far. The count // * includes non-unique vectors. So if the same vector is evaluated twice, both evaluations will be // * recorded by this counter. // * // * @return The number of objective function evaluations. // */ // public int getNumEvaluations() { // return numEvaluations; // } // // /** // * Gets the number of unique objective function evaluations that have taken place so far. If a // * vector is evaluated more than once, this count should not increase. // * // * @return The number of unique objective function evaluations. // */ // public int getNumUniqueEvaluations() { // return numUniqueEvaluations; // } // // /** // * Get the number of times the AVM search has been restarted (following hitting a local optimum). // * // * @return The number of times the AVM search has been restarted. // */ // public int getNumRestarts() { // return numRestarts; // } // // /** // * Gets the running time (in milliseconds) of the search from start to finish. If the search has // * not terminated, the value is undefined. // * // * @return The run time of the search. // */ // // TODO: should this return the running time also. // public long getRunningTime() { // return endTime - startTime; // } // // // TODO: Better name? No parameter. // public void observeVector() throws TerminationException { // tp.checkExhaustedEvaluations(this); // tp.checkExhaustedTime(this); // numEvaluations++; // } // // public void observePreviouslyUnseenVector(Vector vector, ObjectiveValue objVal) // throws TerminationException { // if (bestObjVal == null || objVal.betterThan(bestObjVal)) { // bestObjVal = objVal; // bestVector = vector.deepCopy(); // } // numUniqueEvaluations++; // // tp.checkFoundOptimal(this); // } // // public void observeRestart() throws TerminationException { // tp.checkExhaustedRestarts(this); // tp.checkExhaustedTime(this); // numRestarts++; // } // // public void observeTermination() { // endTime = System.currentTimeMillis(); // } // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // }
import org.avmframework.Monitor; import org.avmframework.TerminationException; import org.avmframework.Vector; import java.util.HashMap; import java.util.Map;
package org.avmframework.objective; public abstract class ObjectiveFunction { public static final boolean USE_CACHE_DEFAULT = true; protected boolean useCache = USE_CACHE_DEFAULT;
// Path: src/main/java/org/avmframework/Monitor.java // public class Monitor { // // /** The termination policy being used by the search. */ // protected TerminationPolicy tp; // // /** The best objective value observed so far during hte search. */ // protected ObjectiveValue bestObjVal; // // /** The vector with the best objective value observed so far by the search. */ // protected Vector bestVector; // // /** // * The number of objective function evaluations that have taken place so far. The count includes // * non-unique vectors. So if the same vector is evaluated twice, both evaluations will be recorded // * by this counter. // */ // protected int numEvaluations; // // /** // * The number of unique objective function evaluations that have taken place so far. If a vector // * is evaluated more than once, this count should not increase. // */ // protected int numUniqueEvaluations; // // /** The number of times the AVM search has been restarted. */ // protected int numRestarts; // // /** The system time (in milliseconds) that the search was started. */ // protected long startTime; // // /** The system time (in milliseconds) that the search was ended. */ // protected long endTime; // // /** // * Constructs a Monitor instance. // * // * @param tp The termination policy being used by the search. // */ // public Monitor(TerminationPolicy tp) { // this.tp = tp; // bestObjVal = null; // bestVector = null; // numEvaluations = 0; // numUniqueEvaluations = 0; // numRestarts = 0; // startTime = System.currentTimeMillis(); // } // // /** // * Gets the best objective value observed by the search so far. // * // * @return THe best objective value. // */ // public ObjectiveValue getBestObjVal() { // return bestObjVal; // } // // /** // * Gets the vector with the best objective value observed by the search so far. // * // * @return The best vector. // */ // public Vector getBestVector() { // return bestVector; // } // // /** // * Gets the number of objective function evaluations that have taken place so far. The count // * includes non-unique vectors. So if the same vector is evaluated twice, both evaluations will be // * recorded by this counter. // * // * @return The number of objective function evaluations. // */ // public int getNumEvaluations() { // return numEvaluations; // } // // /** // * Gets the number of unique objective function evaluations that have taken place so far. If a // * vector is evaluated more than once, this count should not increase. // * // * @return The number of unique objective function evaluations. // */ // public int getNumUniqueEvaluations() { // return numUniqueEvaluations; // } // // /** // * Get the number of times the AVM search has been restarted (following hitting a local optimum). // * // * @return The number of times the AVM search has been restarted. // */ // public int getNumRestarts() { // return numRestarts; // } // // /** // * Gets the running time (in milliseconds) of the search from start to finish. If the search has // * not terminated, the value is undefined. // * // * @return The run time of the search. // */ // // TODO: should this return the running time also. // public long getRunningTime() { // return endTime - startTime; // } // // // TODO: Better name? No parameter. // public void observeVector() throws TerminationException { // tp.checkExhaustedEvaluations(this); // tp.checkExhaustedTime(this); // numEvaluations++; // } // // public void observePreviouslyUnseenVector(Vector vector, ObjectiveValue objVal) // throws TerminationException { // if (bestObjVal == null || objVal.betterThan(bestObjVal)) { // bestObjVal = objVal; // bestVector = vector.deepCopy(); // } // numUniqueEvaluations++; // // tp.checkFoundOptimal(this); // } // // public void observeRestart() throws TerminationException { // tp.checkExhaustedRestarts(this); // tp.checkExhaustedTime(this); // numRestarts++; // } // // public void observeTermination() { // endTime = System.currentTimeMillis(); // } // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java import org.avmframework.Monitor; import org.avmframework.TerminationException; import org.avmframework.Vector; import java.util.HashMap; import java.util.Map; package org.avmframework.objective; public abstract class ObjectiveFunction { public static final boolean USE_CACHE_DEFAULT = true; protected boolean useCache = USE_CACHE_DEFAULT;
protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>();
AVMf/avmf
src/main/java/org/avmframework/objective/ObjectiveFunction.java
// Path: src/main/java/org/avmframework/Monitor.java // public class Monitor { // // /** The termination policy being used by the search. */ // protected TerminationPolicy tp; // // /** The best objective value observed so far during hte search. */ // protected ObjectiveValue bestObjVal; // // /** The vector with the best objective value observed so far by the search. */ // protected Vector bestVector; // // /** // * The number of objective function evaluations that have taken place so far. The count includes // * non-unique vectors. So if the same vector is evaluated twice, both evaluations will be recorded // * by this counter. // */ // protected int numEvaluations; // // /** // * The number of unique objective function evaluations that have taken place so far. If a vector // * is evaluated more than once, this count should not increase. // */ // protected int numUniqueEvaluations; // // /** The number of times the AVM search has been restarted. */ // protected int numRestarts; // // /** The system time (in milliseconds) that the search was started. */ // protected long startTime; // // /** The system time (in milliseconds) that the search was ended. */ // protected long endTime; // // /** // * Constructs a Monitor instance. // * // * @param tp The termination policy being used by the search. // */ // public Monitor(TerminationPolicy tp) { // this.tp = tp; // bestObjVal = null; // bestVector = null; // numEvaluations = 0; // numUniqueEvaluations = 0; // numRestarts = 0; // startTime = System.currentTimeMillis(); // } // // /** // * Gets the best objective value observed by the search so far. // * // * @return THe best objective value. // */ // public ObjectiveValue getBestObjVal() { // return bestObjVal; // } // // /** // * Gets the vector with the best objective value observed by the search so far. // * // * @return The best vector. // */ // public Vector getBestVector() { // return bestVector; // } // // /** // * Gets the number of objective function evaluations that have taken place so far. The count // * includes non-unique vectors. So if the same vector is evaluated twice, both evaluations will be // * recorded by this counter. // * // * @return The number of objective function evaluations. // */ // public int getNumEvaluations() { // return numEvaluations; // } // // /** // * Gets the number of unique objective function evaluations that have taken place so far. If a // * vector is evaluated more than once, this count should not increase. // * // * @return The number of unique objective function evaluations. // */ // public int getNumUniqueEvaluations() { // return numUniqueEvaluations; // } // // /** // * Get the number of times the AVM search has been restarted (following hitting a local optimum). // * // * @return The number of times the AVM search has been restarted. // */ // public int getNumRestarts() { // return numRestarts; // } // // /** // * Gets the running time (in milliseconds) of the search from start to finish. If the search has // * not terminated, the value is undefined. // * // * @return The run time of the search. // */ // // TODO: should this return the running time also. // public long getRunningTime() { // return endTime - startTime; // } // // // TODO: Better name? No parameter. // public void observeVector() throws TerminationException { // tp.checkExhaustedEvaluations(this); // tp.checkExhaustedTime(this); // numEvaluations++; // } // // public void observePreviouslyUnseenVector(Vector vector, ObjectiveValue objVal) // throws TerminationException { // if (bestObjVal == null || objVal.betterThan(bestObjVal)) { // bestObjVal = objVal; // bestVector = vector.deepCopy(); // } // numUniqueEvaluations++; // // tp.checkFoundOptimal(this); // } // // public void observeRestart() throws TerminationException { // tp.checkExhaustedRestarts(this); // tp.checkExhaustedTime(this); // numRestarts++; // } // // public void observeTermination() { // endTime = System.currentTimeMillis(); // } // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // }
import org.avmframework.Monitor; import org.avmframework.TerminationException; import org.avmframework.Vector; import java.util.HashMap; import java.util.Map;
package org.avmframework.objective; public abstract class ObjectiveFunction { public static final boolean USE_CACHE_DEFAULT = true; protected boolean useCache = USE_CACHE_DEFAULT; protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>();
// Path: src/main/java/org/avmframework/Monitor.java // public class Monitor { // // /** The termination policy being used by the search. */ // protected TerminationPolicy tp; // // /** The best objective value observed so far during hte search. */ // protected ObjectiveValue bestObjVal; // // /** The vector with the best objective value observed so far by the search. */ // protected Vector bestVector; // // /** // * The number of objective function evaluations that have taken place so far. The count includes // * non-unique vectors. So if the same vector is evaluated twice, both evaluations will be recorded // * by this counter. // */ // protected int numEvaluations; // // /** // * The number of unique objective function evaluations that have taken place so far. If a vector // * is evaluated more than once, this count should not increase. // */ // protected int numUniqueEvaluations; // // /** The number of times the AVM search has been restarted. */ // protected int numRestarts; // // /** The system time (in milliseconds) that the search was started. */ // protected long startTime; // // /** The system time (in milliseconds) that the search was ended. */ // protected long endTime; // // /** // * Constructs a Monitor instance. // * // * @param tp The termination policy being used by the search. // */ // public Monitor(TerminationPolicy tp) { // this.tp = tp; // bestObjVal = null; // bestVector = null; // numEvaluations = 0; // numUniqueEvaluations = 0; // numRestarts = 0; // startTime = System.currentTimeMillis(); // } // // /** // * Gets the best objective value observed by the search so far. // * // * @return THe best objective value. // */ // public ObjectiveValue getBestObjVal() { // return bestObjVal; // } // // /** // * Gets the vector with the best objective value observed by the search so far. // * // * @return The best vector. // */ // public Vector getBestVector() { // return bestVector; // } // // /** // * Gets the number of objective function evaluations that have taken place so far. The count // * includes non-unique vectors. So if the same vector is evaluated twice, both evaluations will be // * recorded by this counter. // * // * @return The number of objective function evaluations. // */ // public int getNumEvaluations() { // return numEvaluations; // } // // /** // * Gets the number of unique objective function evaluations that have taken place so far. If a // * vector is evaluated more than once, this count should not increase. // * // * @return The number of unique objective function evaluations. // */ // public int getNumUniqueEvaluations() { // return numUniqueEvaluations; // } // // /** // * Get the number of times the AVM search has been restarted (following hitting a local optimum). // * // * @return The number of times the AVM search has been restarted. // */ // public int getNumRestarts() { // return numRestarts; // } // // /** // * Gets the running time (in milliseconds) of the search from start to finish. If the search has // * not terminated, the value is undefined. // * // * @return The run time of the search. // */ // // TODO: should this return the running time also. // public long getRunningTime() { // return endTime - startTime; // } // // // TODO: Better name? No parameter. // public void observeVector() throws TerminationException { // tp.checkExhaustedEvaluations(this); // tp.checkExhaustedTime(this); // numEvaluations++; // } // // public void observePreviouslyUnseenVector(Vector vector, ObjectiveValue objVal) // throws TerminationException { // if (bestObjVal == null || objVal.betterThan(bestObjVal)) { // bestObjVal = objVal; // bestVector = vector.deepCopy(); // } // numUniqueEvaluations++; // // tp.checkFoundOptimal(this); // } // // public void observeRestart() throws TerminationException { // tp.checkExhaustedRestarts(this); // tp.checkExhaustedTime(this); // numRestarts++; // } // // public void observeTermination() { // endTime = System.currentTimeMillis(); // } // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java import org.avmframework.Monitor; import org.avmframework.TerminationException; import org.avmframework.Vector; import java.util.HashMap; import java.util.Map; package org.avmframework.objective; public abstract class ObjectiveFunction { public static final boolean USE_CACHE_DEFAULT = true; protected boolean useCache = USE_CACHE_DEFAULT; protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>();
protected Monitor monitor;
AVMf/avmf
src/main/java/org/avmframework/objective/ObjectiveFunction.java
// Path: src/main/java/org/avmframework/Monitor.java // public class Monitor { // // /** The termination policy being used by the search. */ // protected TerminationPolicy tp; // // /** The best objective value observed so far during hte search. */ // protected ObjectiveValue bestObjVal; // // /** The vector with the best objective value observed so far by the search. */ // protected Vector bestVector; // // /** // * The number of objective function evaluations that have taken place so far. The count includes // * non-unique vectors. So if the same vector is evaluated twice, both evaluations will be recorded // * by this counter. // */ // protected int numEvaluations; // // /** // * The number of unique objective function evaluations that have taken place so far. If a vector // * is evaluated more than once, this count should not increase. // */ // protected int numUniqueEvaluations; // // /** The number of times the AVM search has been restarted. */ // protected int numRestarts; // // /** The system time (in milliseconds) that the search was started. */ // protected long startTime; // // /** The system time (in milliseconds) that the search was ended. */ // protected long endTime; // // /** // * Constructs a Monitor instance. // * // * @param tp The termination policy being used by the search. // */ // public Monitor(TerminationPolicy tp) { // this.tp = tp; // bestObjVal = null; // bestVector = null; // numEvaluations = 0; // numUniqueEvaluations = 0; // numRestarts = 0; // startTime = System.currentTimeMillis(); // } // // /** // * Gets the best objective value observed by the search so far. // * // * @return THe best objective value. // */ // public ObjectiveValue getBestObjVal() { // return bestObjVal; // } // // /** // * Gets the vector with the best objective value observed by the search so far. // * // * @return The best vector. // */ // public Vector getBestVector() { // return bestVector; // } // // /** // * Gets the number of objective function evaluations that have taken place so far. The count // * includes non-unique vectors. So if the same vector is evaluated twice, both evaluations will be // * recorded by this counter. // * // * @return The number of objective function evaluations. // */ // public int getNumEvaluations() { // return numEvaluations; // } // // /** // * Gets the number of unique objective function evaluations that have taken place so far. If a // * vector is evaluated more than once, this count should not increase. // * // * @return The number of unique objective function evaluations. // */ // public int getNumUniqueEvaluations() { // return numUniqueEvaluations; // } // // /** // * Get the number of times the AVM search has been restarted (following hitting a local optimum). // * // * @return The number of times the AVM search has been restarted. // */ // public int getNumRestarts() { // return numRestarts; // } // // /** // * Gets the running time (in milliseconds) of the search from start to finish. If the search has // * not terminated, the value is undefined. // * // * @return The run time of the search. // */ // // TODO: should this return the running time also. // public long getRunningTime() { // return endTime - startTime; // } // // // TODO: Better name? No parameter. // public void observeVector() throws TerminationException { // tp.checkExhaustedEvaluations(this); // tp.checkExhaustedTime(this); // numEvaluations++; // } // // public void observePreviouslyUnseenVector(Vector vector, ObjectiveValue objVal) // throws TerminationException { // if (bestObjVal == null || objVal.betterThan(bestObjVal)) { // bestObjVal = objVal; // bestVector = vector.deepCopy(); // } // numUniqueEvaluations++; // // tp.checkFoundOptimal(this); // } // // public void observeRestart() throws TerminationException { // tp.checkExhaustedRestarts(this); // tp.checkExhaustedTime(this); // numRestarts++; // } // // public void observeTermination() { // endTime = System.currentTimeMillis(); // } // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // }
import org.avmframework.Monitor; import org.avmframework.TerminationException; import org.avmframework.Vector; import java.util.HashMap; import java.util.Map;
package org.avmframework.objective; public abstract class ObjectiveFunction { public static final boolean USE_CACHE_DEFAULT = true; protected boolean useCache = USE_CACHE_DEFAULT; protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); protected Monitor monitor; public void setMonitor(Monitor monitor) { this.monitor = monitor; }
// Path: src/main/java/org/avmframework/Monitor.java // public class Monitor { // // /** The termination policy being used by the search. */ // protected TerminationPolicy tp; // // /** The best objective value observed so far during hte search. */ // protected ObjectiveValue bestObjVal; // // /** The vector with the best objective value observed so far by the search. */ // protected Vector bestVector; // // /** // * The number of objective function evaluations that have taken place so far. The count includes // * non-unique vectors. So if the same vector is evaluated twice, both evaluations will be recorded // * by this counter. // */ // protected int numEvaluations; // // /** // * The number of unique objective function evaluations that have taken place so far. If a vector // * is evaluated more than once, this count should not increase. // */ // protected int numUniqueEvaluations; // // /** The number of times the AVM search has been restarted. */ // protected int numRestarts; // // /** The system time (in milliseconds) that the search was started. */ // protected long startTime; // // /** The system time (in milliseconds) that the search was ended. */ // protected long endTime; // // /** // * Constructs a Monitor instance. // * // * @param tp The termination policy being used by the search. // */ // public Monitor(TerminationPolicy tp) { // this.tp = tp; // bestObjVal = null; // bestVector = null; // numEvaluations = 0; // numUniqueEvaluations = 0; // numRestarts = 0; // startTime = System.currentTimeMillis(); // } // // /** // * Gets the best objective value observed by the search so far. // * // * @return THe best objective value. // */ // public ObjectiveValue getBestObjVal() { // return bestObjVal; // } // // /** // * Gets the vector with the best objective value observed by the search so far. // * // * @return The best vector. // */ // public Vector getBestVector() { // return bestVector; // } // // /** // * Gets the number of objective function evaluations that have taken place so far. The count // * includes non-unique vectors. So if the same vector is evaluated twice, both evaluations will be // * recorded by this counter. // * // * @return The number of objective function evaluations. // */ // public int getNumEvaluations() { // return numEvaluations; // } // // /** // * Gets the number of unique objective function evaluations that have taken place so far. If a // * vector is evaluated more than once, this count should not increase. // * // * @return The number of unique objective function evaluations. // */ // public int getNumUniqueEvaluations() { // return numUniqueEvaluations; // } // // /** // * Get the number of times the AVM search has been restarted (following hitting a local optimum). // * // * @return The number of times the AVM search has been restarted. // */ // public int getNumRestarts() { // return numRestarts; // } // // /** // * Gets the running time (in milliseconds) of the search from start to finish. If the search has // * not terminated, the value is undefined. // * // * @return The run time of the search. // */ // // TODO: should this return the running time also. // public long getRunningTime() { // return endTime - startTime; // } // // // TODO: Better name? No parameter. // public void observeVector() throws TerminationException { // tp.checkExhaustedEvaluations(this); // tp.checkExhaustedTime(this); // numEvaluations++; // } // // public void observePreviouslyUnseenVector(Vector vector, ObjectiveValue objVal) // throws TerminationException { // if (bestObjVal == null || objVal.betterThan(bestObjVal)) { // bestObjVal = objVal; // bestVector = vector.deepCopy(); // } // numUniqueEvaluations++; // // tp.checkFoundOptimal(this); // } // // public void observeRestart() throws TerminationException { // tp.checkExhaustedRestarts(this); // tp.checkExhaustedTime(this); // numRestarts++; // } // // public void observeTermination() { // endTime = System.currentTimeMillis(); // } // } // // Path: src/main/java/org/avmframework/TerminationException.java // public class TerminationException extends Exception {} // // Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // Path: src/main/java/org/avmframework/objective/ObjectiveFunction.java import org.avmframework.Monitor; import org.avmframework.TerminationException; import org.avmframework.Vector; import java.util.HashMap; import java.util.Map; package org.avmframework.objective; public abstract class ObjectiveFunction { public static final boolean USE_CACHE_DEFAULT = true; protected boolean useCache = USE_CACHE_DEFAULT; protected Map<Vector, ObjectiveValue> previousVals = new HashMap<>(); protected Monitor monitor; public void setMonitor(Monitor monitor) { this.monitor = monitor; }
public ObjectiveValue evaluate(Vector vector) throws TerminationException {
AVMf/avmf
src/main/java/org/avmframework/initialization/RandomInitializer.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // }
import org.apache.commons.math3.random.RandomGenerator; import org.avmframework.Vector;
package org.avmframework.initialization; public class RandomInitializer extends Initializer { protected RandomGenerator rg; public RandomInitializer(RandomGenerator rg) { this.rg = rg; } @Override
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // Path: src/main/java/org/avmframework/initialization/RandomInitializer.java import org.apache.commons.math3.random.RandomGenerator; import org.avmframework.Vector; package org.avmframework.initialization; public class RandomInitializer extends Initializer { protected RandomGenerator rg; public RandomInitializer(RandomGenerator rg) { this.rg = rg; } @Override
public void initialize(Vector vector) {
AVMf/avmf
src/main/java/org/avmframework/examples/testoptimization/PrioritizationObject.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/FixedPointVariable.java // public class FixedPointVariable extends AtomicVariable { // // protected int precision; // // public FixedPointVariable(double initialValue, int precision, double min, double max) { // super( // doubleToInt(initialValue, precision), // doubleToInt(min, precision), // doubleToInt(max, precision)); // this.precision = precision; // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public double asDouble() { // return intToDouble(value, precision); // } // // @Override // public FixedPointVariable deepCopy() { // FixedPointVariable copy = new FixedPointVariable(initialValue, precision, min, max); // copy.value = value; // return copy; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (!(obj instanceof FixedPointVariable)) { // return false; // } // if (!super.equals(obj)) { // return false; // } // // FixedPointVariable that = (FixedPointVariable) obj; // // return precision == that.precision; // } // // @Override // public int hashCode() { // int result = super.hashCode(); // result = 31 * result + precision; // return result; // } // // @Override // public String toString() { // return String.format("%." + precision + "f", asDouble()); // } // // private static int doubleToInt(double value, int precision) { // return (int) Math.round(value * Math.pow(10, precision)); // } // // private static double intToDouble(int value, int precision) { // return ((double) value) * Math.pow(10, -precision); // } // }
import org.avmframework.Vector; import org.avmframework.variable.FixedPointVariable; import java.util.List;
package org.avmframework.examples.testoptimization; public class PrioritizationObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/FixedPointVariable.java // public class FixedPointVariable extends AtomicVariable { // // protected int precision; // // public FixedPointVariable(double initialValue, int precision, double min, double max) { // super( // doubleToInt(initialValue, precision), // doubleToInt(min, precision), // doubleToInt(max, precision)); // this.precision = precision; // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public double asDouble() { // return intToDouble(value, precision); // } // // @Override // public FixedPointVariable deepCopy() { // FixedPointVariable copy = new FixedPointVariable(initialValue, precision, min, max); // copy.value = value; // return copy; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (!(obj instanceof FixedPointVariable)) { // return false; // } // if (!super.equals(obj)) { // return false; // } // // FixedPointVariable that = (FixedPointVariable) obj; // // return precision == that.precision; // } // // @Override // public int hashCode() { // int result = super.hashCode(); // result = 31 * result + precision; // return result; // } // // @Override // public String toString() { // return String.format("%." + precision + "f", asDouble()); // } // // private static int doubleToInt(double value, int precision) { // return (int) Math.round(value * Math.pow(10, precision)); // } // // private static double intToDouble(int value, int precision) { // return ((double) value) * Math.pow(10, -precision); // } // } // Path: src/main/java/org/avmframework/examples/testoptimization/PrioritizationObject.java import org.avmframework.Vector; import org.avmframework.variable.FixedPointVariable; import java.util.List; package org.avmframework.examples.testoptimization; public class PrioritizationObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized
public Vector setUpVector(int size) {
AVMf/avmf
src/main/java/org/avmframework/examples/testoptimization/PrioritizationObject.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/FixedPointVariable.java // public class FixedPointVariable extends AtomicVariable { // // protected int precision; // // public FixedPointVariable(double initialValue, int precision, double min, double max) { // super( // doubleToInt(initialValue, precision), // doubleToInt(min, precision), // doubleToInt(max, precision)); // this.precision = precision; // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public double asDouble() { // return intToDouble(value, precision); // } // // @Override // public FixedPointVariable deepCopy() { // FixedPointVariable copy = new FixedPointVariable(initialValue, precision, min, max); // copy.value = value; // return copy; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (!(obj instanceof FixedPointVariable)) { // return false; // } // if (!super.equals(obj)) { // return false; // } // // FixedPointVariable that = (FixedPointVariable) obj; // // return precision == that.precision; // } // // @Override // public int hashCode() { // int result = super.hashCode(); // result = 31 * result + precision; // return result; // } // // @Override // public String toString() { // return String.format("%." + precision + "f", asDouble()); // } // // private static int doubleToInt(double value, int precision) { // return (int) Math.round(value * Math.pow(10, precision)); // } // // private static double intToDouble(int value, int precision) { // return ((double) value) * Math.pow(10, -precision); // } // }
import org.avmframework.Vector; import org.avmframework.variable.FixedPointVariable; import java.util.List;
package org.avmframework.examples.testoptimization; public class PrioritizationObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized public Vector setUpVector(int size) { Vector vector = new Vector(); for (int i = 0; i < size; i++) {
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/FixedPointVariable.java // public class FixedPointVariable extends AtomicVariable { // // protected int precision; // // public FixedPointVariable(double initialValue, int precision, double min, double max) { // super( // doubleToInt(initialValue, precision), // doubleToInt(min, precision), // doubleToInt(max, precision)); // this.precision = precision; // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public double asDouble() { // return intToDouble(value, precision); // } // // @Override // public FixedPointVariable deepCopy() { // FixedPointVariable copy = new FixedPointVariable(initialValue, precision, min, max); // copy.value = value; // return copy; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (!(obj instanceof FixedPointVariable)) { // return false; // } // if (!super.equals(obj)) { // return false; // } // // FixedPointVariable that = (FixedPointVariable) obj; // // return precision == that.precision; // } // // @Override // public int hashCode() { // int result = super.hashCode(); // result = 31 * result + precision; // return result; // } // // @Override // public String toString() { // return String.format("%." + precision + "f", asDouble()); // } // // private static int doubleToInt(double value, int precision) { // return (int) Math.round(value * Math.pow(10, precision)); // } // // private static double intToDouble(int value, int precision) { // return ((double) value) * Math.pow(10, -precision); // } // } // Path: src/main/java/org/avmframework/examples/testoptimization/PrioritizationObject.java import org.avmframework.Vector; import org.avmframework.variable.FixedPointVariable; import java.util.List; package org.avmframework.examples.testoptimization; public class PrioritizationObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized public Vector setUpVector(int size) { Vector vector = new Vector(); for (int i = 0; i < size; i++) {
vector.addVariable(new FixedPointVariable(INIT, 1, MIN, size)); // precision of 1
AVMf/avmf
src/main/java/org/avmframework/examples/testoptimization/SelectionObject.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // }
import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List;
package org.avmframework.examples.testoptimization; public class SelectionObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // Path: src/main/java/org/avmframework/examples/testoptimization/SelectionObject.java import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List; package org.avmframework.examples.testoptimization; public class SelectionObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized
public Vector setUpVector(int size) {
AVMf/avmf
src/main/java/org/avmframework/examples/testoptimization/SelectionObject.java
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // }
import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List;
package org.avmframework.examples.testoptimization; public class SelectionObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized public Vector setUpVector(int size) { Vector vector = new Vector(); for (int i = 0; i < size; i++) {
// Path: src/main/java/org/avmframework/Vector.java // public class Vector extends AbstractVector { // // public void addVariable(Variable variable) { // variables.add(variable); // } // // public List<Variable> getVariables() { // return new ArrayList<>(variables); // } // // public void setVariablesToInitial() { // for (Variable var : variables) { // var.setValueToInitial(); // } // } // // public void setVariablesToRandom(RandomGenerator rg) { // for (Variable var : variables) { // var.setValueToRandom(rg); // } // } // // public Vector deepCopy() { // Vector copy = new Vector(); // deepCopyVariables(copy); // return copy; // } // } // // Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // Path: src/main/java/org/avmframework/examples/testoptimization/SelectionObject.java import org.avmframework.Vector; import org.avmframework.variable.IntegerVariable; import java.util.List; package org.avmframework.examples.testoptimization; public class SelectionObject { static final int INIT = 0; static final int MIN = 0; static final int MAX = 1; // set up the vector to be optimized public Vector setUpVector(int size) { Vector vector = new Vector(); for (int i = 0; i < size; i++) {
vector.addVariable(new IntegerVariable(INIT, MIN, MAX));
AVMf/avmf
src/test/java/org/avmframework/Vectors.java
// Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // }
import org.avmframework.variable.IntegerVariable;
package org.avmframework; public class Vectors { public static Vector emptyVector() { return new Vector(); } public static Vector singleIntegerVector() { return integerVector(1); } public static Vector integerVector(int length) { return integerVector(length, 0); } public static Vector integerVector(int length, int initialValue) { Vector vector = new Vector(); for (int i = 0; i < length; i++) {
// Path: src/main/java/org/avmframework/variable/IntegerVariable.java // public class IntegerVariable extends AtomicVariable { // // public IntegerVariable(int initialValue, int min, int max) { // super(initialValue, min, max); // if (min > max) { // throw new MinGreaterThanMaxException(min, max); // } // setValueToInitial(); // } // // public int asInt() { // return value; // } // // @Override // public IntegerVariable deepCopy() { // IntegerVariable copy = new IntegerVariable(initialValue, min, max); // copy.value = value; // return copy; // } // // @Override // public String toString() { // return "" + asInt(); // } // } // Path: src/test/java/org/avmframework/Vectors.java import org.avmframework.variable.IntegerVariable; package org.avmframework; public class Vectors { public static Vector emptyVector() { return new Vector(); } public static Vector singleIntegerVector() { return integerVector(1); } public static Vector integerVector(int length) { return integerVector(length, 0); } public static Vector integerVector(int length, int initialValue) { Vector vector = new Vector(); for (int i = 0; i < length; i++) {
vector.addVariable(new IntegerVariable(initialValue, -100, 100));
AVMf/avmf
src/test/java/org/avmframework/AlternatingVariableMethods.java
// Path: src/main/java/org/avmframework/initialization/DefaultInitializer.java // public class DefaultInitializer extends Initializer { // // @Override // public void initialize(Vector vector) { // vector.setVariablesToInitial(); // } // } // // Path: src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java // public class IteratedPatternSearch extends PatternSearch { // // public IteratedPatternSearch() {} // // public IteratedPatternSearch(int accelerationFactor) { // super(accelerationFactor); // } // // protected void performSearch() throws TerminationException { // ObjectiveValue next = objFun.evaluate(vector); // ObjectiveValue last; // // do { // initialize(); // if (establishDirection()) { // patternSearch(); // } // // last = next; // next = objFun.evaluate(vector); // } // while (next.betterThan(last)); // } // }
import org.avmframework.initialization.DefaultInitializer; import org.avmframework.localsearch.IteratedPatternSearch;
package org.avmframework; public class AlternatingVariableMethods { public static AlternatingVariableMethod anyAlternatingVariableMethod() { return new AlternatingVariableMethod(
// Path: src/main/java/org/avmframework/initialization/DefaultInitializer.java // public class DefaultInitializer extends Initializer { // // @Override // public void initialize(Vector vector) { // vector.setVariablesToInitial(); // } // } // // Path: src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java // public class IteratedPatternSearch extends PatternSearch { // // public IteratedPatternSearch() {} // // public IteratedPatternSearch(int accelerationFactor) { // super(accelerationFactor); // } // // protected void performSearch() throws TerminationException { // ObjectiveValue next = objFun.evaluate(vector); // ObjectiveValue last; // // do { // initialize(); // if (establishDirection()) { // patternSearch(); // } // // last = next; // next = objFun.evaluate(vector); // } // while (next.betterThan(last)); // } // } // Path: src/test/java/org/avmframework/AlternatingVariableMethods.java import org.avmframework.initialization.DefaultInitializer; import org.avmframework.localsearch.IteratedPatternSearch; package org.avmframework; public class AlternatingVariableMethods { public static AlternatingVariableMethod anyAlternatingVariableMethod() { return new AlternatingVariableMethod(
new IteratedPatternSearch(),
AVMf/avmf
src/test/java/org/avmframework/AlternatingVariableMethods.java
// Path: src/main/java/org/avmframework/initialization/DefaultInitializer.java // public class DefaultInitializer extends Initializer { // // @Override // public void initialize(Vector vector) { // vector.setVariablesToInitial(); // } // } // // Path: src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java // public class IteratedPatternSearch extends PatternSearch { // // public IteratedPatternSearch() {} // // public IteratedPatternSearch(int accelerationFactor) { // super(accelerationFactor); // } // // protected void performSearch() throws TerminationException { // ObjectiveValue next = objFun.evaluate(vector); // ObjectiveValue last; // // do { // initialize(); // if (establishDirection()) { // patternSearch(); // } // // last = next; // next = objFun.evaluate(vector); // } // while (next.betterThan(last)); // } // }
import org.avmframework.initialization.DefaultInitializer; import org.avmframework.localsearch.IteratedPatternSearch;
package org.avmframework; public class AlternatingVariableMethods { public static AlternatingVariableMethod anyAlternatingVariableMethod() { return new AlternatingVariableMethod( new IteratedPatternSearch(), TerminationPolicy.createMaxEvaluationsTerminationPolicy(100),
// Path: src/main/java/org/avmframework/initialization/DefaultInitializer.java // public class DefaultInitializer extends Initializer { // // @Override // public void initialize(Vector vector) { // vector.setVariablesToInitial(); // } // } // // Path: src/main/java/org/avmframework/localsearch/IteratedPatternSearch.java // public class IteratedPatternSearch extends PatternSearch { // // public IteratedPatternSearch() {} // // public IteratedPatternSearch(int accelerationFactor) { // super(accelerationFactor); // } // // protected void performSearch() throws TerminationException { // ObjectiveValue next = objFun.evaluate(vector); // ObjectiveValue last; // // do { // initialize(); // if (establishDirection()) { // patternSearch(); // } // // last = next; // next = objFun.evaluate(vector); // } // while (next.betterThan(last)); // } // } // Path: src/test/java/org/avmframework/AlternatingVariableMethods.java import org.avmframework.initialization.DefaultInitializer; import org.avmframework.localsearch.IteratedPatternSearch; package org.avmframework; public class AlternatingVariableMethods { public static AlternatingVariableMethod anyAlternatingVariableMethod() { return new AlternatingVariableMethod( new IteratedPatternSearch(), TerminationPolicy.createMaxEvaluationsTerminationPolicy(100),
new DefaultInitializer());
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/messaging/support/TenantContextMessageInterceptorTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // }
import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.messaging.support; /** * Created with IntelliJ IDEA. * User: in329dei * Date: 4-6-13 * Time: 11:06 * To change this template use File | Settings | File Templates. */ public class TenantContextMessageInterceptorTest { private Message message; private TenantContextMessageInterceptor interceptor = new TenantContextMessageInterceptor(); @Before public void before() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/messaging/support/TenantContextMessageInterceptorTest.java import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.messaging.support; /** * Created with IntelliJ IDEA. * User: in329dei * Date: 4-6-13 * Time: 11:06 * To change this template use File | Settings | File Templates. */ public class TenantContextMessageInterceptorTest { private Message message; private TenantContextMessageInterceptor interceptor = new TenantContextMessageInterceptor(); @Before public void before() {
TenantContextHolder.clearContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/messaging/support/TenantContextMessageInterceptorTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // }
import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.messaging.support; /** * Created with IntelliJ IDEA. * User: in329dei * Date: 4-6-13 * Time: 11:06 * To change this template use File | Settings | File Templates. */ public class TenantContextMessageInterceptorTest { private Message message; private TenantContextMessageInterceptor interceptor = new TenantContextMessageInterceptor(); @Before public void before() { TenantContextHolder.clearContext(); this.message = new GenericMessage("dummy-test-payload"); } @After public void after() { TenantContextHolder.clearContext(); } @Test public void whenNoContextIsSetThenNoContextHeaderShouldBeSet() { Message msg = this.interceptor.preSend(message, null); String context = msg.getHeaders().get(this.interceptor.getHeaderName(), String.class); assertThat(context, is(nullValue())); } @Test public void whenContextIsSetThenTheContextHeaderShouldBeSet() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/messaging/support/TenantContextMessageInterceptorTest.java import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.messaging.support; /** * Created with IntelliJ IDEA. * User: in329dei * Date: 4-6-13 * Time: 11:06 * To change this template use File | Settings | File Templates. */ public class TenantContextMessageInterceptorTest { private Message message; private TenantContextMessageInterceptor interceptor = new TenantContextMessageInterceptor(); @Before public void before() { TenantContextHolder.clearContext(); this.message = new GenericMessage("dummy-test-payload"); } @After public void after() { TenantContextHolder.clearContext(); } @Test public void whenNoContextIsSetThenNoContextHeaderShouldBeSet() { Message msg = this.interceptor.preSend(message, null); String context = msg.getHeaders().get(this.interceptor.getHeaderName(), String.class); assertThat(context, is(nullValue())); } @Test public void whenContextIsSetThenTheContextHeaderShouldBeSet() {
TenantContextTestUtil.setCurrentTenant("test");
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/messaging/support/TenantContextMessageInterceptor.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.ChannelInterceptorAdapter; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.StringUtils; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.messaging.support; /** * {@code ChannelInterceptor} which reads and writes the context from/to a header in the message. * * @author Marten Deinum * @since 1.3.0 */ public class TenantContextMessageInterceptor extends ChannelInterceptorAdapter { private static final String DEFAULT_HEADER_NAME = TenantContextHolder.class.getName() + ".CONTEXT"; private final Logger logger = LoggerFactory.getLogger(TenantContextMessageInterceptor.class); private String headerName = DEFAULT_HEADER_NAME; @Override public Message<?> preSend(Message<?> message, MessageChannel messageChannel) { String tenant = TenantContextHolder.getContext().getTenant(); if (StringUtils.hasText(tenant)) { return MessageBuilder .fromMessage(message) .setHeader(this.headerName, tenant) .build(); } return message; } @Override public Message<?> postReceive(Message<?> message, MessageChannel messageChannel) { String tenant = message.getHeaders().get(this.headerName, String.class); this.logger.debug("Using tenant: {}", tenant); if (StringUtils.hasText(tenant)) {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/messaging/support/TenantContextMessageInterceptor.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.ChannelInterceptorAdapter; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.StringUtils; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.messaging.support; /** * {@code ChannelInterceptor} which reads and writes the context from/to a header in the message. * * @author Marten Deinum * @since 1.3.0 */ public class TenantContextMessageInterceptor extends ChannelInterceptorAdapter { private static final String DEFAULT_HEADER_NAME = TenantContextHolder.class.getName() + ".CONTEXT"; private final Logger logger = LoggerFactory.getLogger(TenantContextMessageInterceptor.class); private String headerName = DEFAULT_HEADER_NAME; @Override public Message<?> preSend(Message<?> message, MessageChannel messageChannel) { String tenant = TenantContextHolder.getContext().getTenant(); if (StringUtils.hasText(tenant)) { return MessageBuilder .fromMessage(message) .setHeader(this.headerName, tenant) .build(); } return message; } @Override public Message<?> postReceive(Message<?> message, MessageChannel messageChannel) { String tenant = message.getHeaders().get(this.headerName, String.class); this.logger.debug("Using tenant: {}", tenant); if (StringUtils.hasText(tenant)) {
TenantContext context = TenantContextHolder.createEmptyContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/server/TenantContextEndpointInterceptorTests.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // }
import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.Matchers.is;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.server; /** * Tests for the {@code ContextEndpointInterceptorTests}. * * @author Marten Deinum */ public class TenantContextEndpointInterceptorTests { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "context-header"; private static final String HEADER_VAL = "context"; private final TenantContextEndpointInterceptor interceptor = new TenantContextEndpointInterceptor();
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/server/TenantContextEndpointInterceptorTests.java import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.Matchers.is; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.server; /** * Tests for the {@code ContextEndpointInterceptorTests}. * * @author Marten Deinum */ public class TenantContextEndpointInterceptorTests { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "context-header"; private static final String HEADER_VAL = "context"; private final TenantContextEndpointInterceptor interceptor = new TenantContextEndpointInterceptor();
private MockWebServiceConnection connection;
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/server/TenantContextEndpointInterceptorTests.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // }
import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.Matchers.is;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.server; /** * Tests for the {@code ContextEndpointInterceptorTests}. * * @author Marten Deinum */ public class TenantContextEndpointInterceptorTests { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "context-header"; private static final String HEADER_VAL = "context"; private final TenantContextEndpointInterceptor interceptor = new TenantContextEndpointInterceptor(); private MockWebServiceConnection connection; @Before public void setup() { // Setup TransportContext this.connection = mock(MockWebServiceConnection.class); DefaultTransportContext context = new DefaultTransportContext(connection); TransportContextHolder.setTransportContext(context); } @After public void cleanUp() { TransportContextHolder.setTransportContext(null);
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/server/TenantContextEndpointInterceptorTests.java import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.Collections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.Matchers.is; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.server; /** * Tests for the {@code ContextEndpointInterceptorTests}. * * @author Marten Deinum */ public class TenantContextEndpointInterceptorTests { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "context-header"; private static final String HEADER_VAL = "context"; private final TenantContextEndpointInterceptor interceptor = new TenantContextEndpointInterceptor(); private MockWebServiceConnection connection; @Before public void setup() { // Setup TransportContext this.connection = mock(MockWebServiceConnection.class); DefaultTransportContext context = new DefaultTransportContext(connection); TransportContextHolder.setTransportContext(context); } @After public void cleanUp() { TransportContextHolder.setTransportContext(null);
TenantContextHolder.clearContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/concurrent/TenantContextCallable.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // }
import java.util.concurrent.Callable; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.concurrent; /** * {@link Callable} extension which sets the {@link TenantContext} before actually calling the method. * * @param <T> the type * * @author Marten Deinum * @since 1.3 */ public abstract class TenantContextCallable<T> implements Callable<T> { private final TenantContext context; protected TenantContextCallable(TenantContext context) { this.context = context; } @Override public final T call() throws Exception {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/concurrent/TenantContextCallable.java import java.util.concurrent.Callable; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.concurrent; /** * {@link Callable} extension which sets the {@link TenantContext} before actually calling the method. * * @param <T> the type * * @author Marten Deinum * @since 1.3 */ public abstract class TenantContextCallable<T> implements Callable<T> { private final TenantContext context; protected TenantContextCallable(TenantContext context) { this.context = context; } @Override public final T call() throws Exception {
final TenantContext previousContext = TenantContextHolder.getContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/hibernate/context/TenantContextCurrentTenantIdentifierResolverTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // }
import org.junit.After; import org.junit.Before; import org.junit.Test; import biz.deinum.multitenant.context.TenantContextHolder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package biz.deinum.multitenant.hibernate.context; /** * @author marten */ public class TenantContextCurrentTenantIdentifierResolverTest { private static final String TENANT = "TEST_TENANT"; private final TenantContextCurrentTenantIdentifierResolver resolver = new TenantContextCurrentTenantIdentifierResolver(); @Before public void setup() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/hibernate/context/TenantContextCurrentTenantIdentifierResolverTest.java import org.junit.After; import org.junit.Before; import org.junit.Test; import biz.deinum.multitenant.context.TenantContextHolder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package biz.deinum.multitenant.hibernate.context; /** * @author marten */ public class TenantContextCurrentTenantIdentifierResolverTest { private static final String TENANT = "TEST_TENANT"; private final TenantContextCurrentTenantIdentifierResolver resolver = new TenantContextCurrentTenantIdentifierResolver(); @Before public void setup() {
TenantContextHolder.getContext().setTenant(TENANT);
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/client/TentantContextClientInterceptorTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // }
import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.client.WebServiceIOException; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.MatcherAssert.assertThat;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.client; /** * @author marten */ public class TentantContextClientInterceptorTest { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "tenant-header"; private static final String HEADER_VAL = "tenant"; private final TentantContextClientInterceptor interceptor = new TentantContextClientInterceptor();
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/client/TentantContextClientInterceptorTest.java import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.client.WebServiceIOException; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.MatcherAssert.assertThat; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.client; /** * @author marten */ public class TentantContextClientInterceptorTest { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "tenant-header"; private static final String HEADER_VAL = "tenant"; private final TentantContextClientInterceptor interceptor = new TentantContextClientInterceptor();
private MockWebServiceConnection connection;
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/client/TentantContextClientInterceptorTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // }
import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.client.WebServiceIOException; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.MatcherAssert.assertThat;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.client; /** * @author marten */ public class TentantContextClientInterceptorTest { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "tenant-header"; private static final String HEADER_VAL = "tenant"; private final TentantContextClientInterceptor interceptor = new TentantContextClientInterceptor(); private MockWebServiceConnection connection; @Before public void setup() { // Setup TransportContext this.connection = mock(MockWebServiceConnection.class); DefaultTransportContext context = new DefaultTransportContext(this.connection); TransportContextHolder.setTransportContext(context); } @After public void cleanUp() { TransportContextHolder.setTransportContext(null);
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/client/TentantContextClientInterceptorTest.java import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.client.WebServiceIOException; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.MatcherAssert.assertThat; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.ws.client; /** * @author marten */ public class TentantContextClientInterceptorTest { private static final String DEFAULT_HEADER = "biz.deinum.multitenant.context.TenantContextHolder.CONTEXT"; private static final String HEADER_NAME = "tenant-header"; private static final String HEADER_VAL = "tenant"; private final TentantContextClientInterceptor interceptor = new TentantContextClientInterceptor(); private MockWebServiceConnection connection; @Before public void setup() { // Setup TransportContext this.connection = mock(MockWebServiceConnection.class); DefaultTransportContext context = new DefaultTransportContext(this.connection); TransportContextHolder.setTransportContext(context); } @After public void cleanUp() { TransportContextHolder.setTransportContext(null);
TenantContextHolder.clearContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/client/TentantContextClientInterceptorTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // }
import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.client.WebServiceIOException; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.MatcherAssert.assertThat;
TenantContextHolder.clearContext(); } @Test public void checkPreConditions() { assertThat(this.interceptor.getHeaderName(), is(DEFAULT_HEADER)); assertThat(this.interceptor.handleFault(null), is(true)); assertThat(this.interceptor.handleResponse(null), is(true)); } @Test public void headerNameShouldChange() { this.interceptor.setHeaderName(HEADER_NAME); assertThat(this.interceptor.getHeaderName(), is(HEADER_NAME)); } @Test public void whenNoTenantSetNoHeaderShouldBeSet() throws Exception { TenantContextHolder.clearContext(); this.interceptor.handleRequest(null); verify(this.connection, never()).addRequestHeader(any(String.class), any(String.class)); } @Test public void whenTenantSetHeaderShouldBeSet() throws Exception {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/MockWebServiceConnection.java // public abstract class MockWebServiceConnection implements WebServiceConnection, // HeadersAwareReceiverWebServiceConnection, // HeadersAwareSenderWebServiceConnection { // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/ws/client/TentantContextClientInterceptorTest.java import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.ws.client.WebServiceIOException; import org.springframework.ws.transport.context.DefaultTransportContext; import org.springframework.ws.transport.context.TransportContextHolder; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import biz.deinum.multitenant.ws.MockWebServiceConnection; import static org.hamcrest.MatcherAssert.assertThat; TenantContextHolder.clearContext(); } @Test public void checkPreConditions() { assertThat(this.interceptor.getHeaderName(), is(DEFAULT_HEADER)); assertThat(this.interceptor.handleFault(null), is(true)); assertThat(this.interceptor.handleResponse(null), is(true)); } @Test public void headerNameShouldChange() { this.interceptor.setHeaderName(HEADER_NAME); assertThat(this.interceptor.getHeaderName(), is(HEADER_NAME)); } @Test public void whenNoTenantSetNoHeaderShouldBeSet() throws Exception { TenantContextHolder.clearContext(); this.interceptor.handleRequest(null); verify(this.connection, never()).addRequestHeader(any(String.class), any(String.class)); } @Test public void whenTenantSetHeaderShouldBeSet() throws Exception {
TenantContextTestUtil.setCurrentTenant(HEADER_VAL);
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptor.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code HandlerInterceptor} which sets the context from the current request. * Delegates the actual lookup to a {@link TenantIdentificationStrategy}. * * <p>When no context is found an IllegalStateException is thrown, this can be * switched of by setting the {@code throwExceptionOnMissingTenant} property. * * @author Marten Deinum * @since 1.3 */ public class TenantContextHandlerInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(TenantContextHandlerInterceptor.class);
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptor.java import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code HandlerInterceptor} which sets the context from the current request. * Delegates the actual lookup to a {@link TenantIdentificationStrategy}. * * <p>When no context is found an IllegalStateException is thrown, this can be * switched of by setting the {@code throwExceptionOnMissingTenant} property. * * @author Marten Deinum * @since 1.3 */ public class TenantContextHandlerInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(TenantContextHandlerInterceptor.class);
private final List<TenantIdentificationStrategy> strategies;
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptor.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code HandlerInterceptor} which sets the context from the current request. * Delegates the actual lookup to a {@link TenantIdentificationStrategy}. * * <p>When no context is found an IllegalStateException is thrown, this can be * switched of by setting the {@code throwExceptionOnMissingTenant} property. * * @author Marten Deinum * @since 1.3 */ public class TenantContextHandlerInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(TenantContextHandlerInterceptor.class); private final List<TenantIdentificationStrategy> strategies; private boolean throwExceptionOnMissingTenant = true; public TenantContextHandlerInterceptor(List<TenantIdentificationStrategy> strategies) { super(); this.strategies = strategies; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptor.java import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code HandlerInterceptor} which sets the context from the current request. * Delegates the actual lookup to a {@link TenantIdentificationStrategy}. * * <p>When no context is found an IllegalStateException is thrown, this can be * switched of by setting the {@code throwExceptionOnMissingTenant} property. * * @author Marten Deinum * @since 1.3 */ public class TenantContextHandlerInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(TenantContextHandlerInterceptor.class); private final List<TenantIdentificationStrategy> strategies; private boolean throwExceptionOnMissingTenant = true; public TenantContextHandlerInterceptor(List<TenantIdentificationStrategy> strategies) { super(); this.strategies = strategies; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
TenantContext context = determineTenantContext(request);
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptor.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code HandlerInterceptor} which sets the context from the current request. * Delegates the actual lookup to a {@link TenantIdentificationStrategy}. * * <p>When no context is found an IllegalStateException is thrown, this can be * switched of by setting the {@code throwExceptionOnMissingTenant} property. * * @author Marten Deinum * @since 1.3 */ public class TenantContextHandlerInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(TenantContextHandlerInterceptor.class); private final List<TenantIdentificationStrategy> strategies; private boolean throwExceptionOnMissingTenant = true; public TenantContextHandlerInterceptor(List<TenantIdentificationStrategy> strategies) { super(); this.strategies = strategies; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { TenantContext context = determineTenantContext(request); this.logger.debug("Using context: {}", context);
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptor.java import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code HandlerInterceptor} which sets the context from the current request. * Delegates the actual lookup to a {@link TenantIdentificationStrategy}. * * <p>When no context is found an IllegalStateException is thrown, this can be * switched of by setting the {@code throwExceptionOnMissingTenant} property. * * @author Marten Deinum * @since 1.3 */ public class TenantContextHandlerInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(TenantContextHandlerInterceptor.class); private final List<TenantIdentificationStrategy> strategies; private boolean throwExceptionOnMissingTenant = true; public TenantContextHandlerInterceptor(List<TenantIdentificationStrategy> strategies) { super(); this.strategies = strategies; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { TenantContext context = determineTenantContext(request); this.logger.debug("Using context: {}", context);
TenantContextHolder.setContext(context);
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptorTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * Tests for the {@link TenantContextHandlerInterceptor}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextHandlerInterceptorTest { @Mock
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptorTest.java import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * Tests for the {@link TenantContextHandlerInterceptor}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextHandlerInterceptorTest { @Mock
private TenantIdentificationStrategy strategy;
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptorTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * Tests for the {@link TenantContextHandlerInterceptor}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextHandlerInterceptorTest { @Mock private TenantIdentificationStrategy strategy; private HttpServletRequest request = new MockHttpServletRequest(); private HttpServletResponse response = new MockHttpServletResponse(); private TenantContextHandlerInterceptor interceptor; @Before public void before() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextHandlerInterceptorTest.java import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * Tests for the {@link TenantContextHandlerInterceptor}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextHandlerInterceptorTest { @Mock private TenantIdentificationStrategy strategy; private HttpServletRequest request = new MockHttpServletRequest(); private HttpServletResponse response = new MockHttpServletResponse(); private TenantContextHandlerInterceptor interceptor; @Before public void before() {
TenantContextHolder.clearContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/http/client/TenantContextHeaderInterceptorTest.java
// Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // }
import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.response.MockRestResponseCreators; import org.springframework.web.client.RestTemplate; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.springframework.http.HttpMethod.GET; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.http.client; /** * @author marten */ public class TenantContextHeaderInterceptorTest { private TenantContextHeaderInterceptor interceptor = new TenantContextHeaderInterceptor(); @Test public void shouldSetHeaderOnRequest() { this.interceptor.setHeaderName("context"); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(this.interceptor); RestTemplate template = new RestTemplate(); template.setInterceptors(interceptors); MockRestServiceServer mockServer = MockRestServiceServer.createServer(template); mockServer.expect(requestTo("/test")) .andExpect(method(GET)) .andExpect(header("context", "test-context")) .andRespond(MockRestResponseCreators.withSuccess());
// Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/http/client/TenantContextHeaderInterceptorTest.java import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.response.MockRestResponseCreators; import org.springframework.web.client.RestTemplate; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.springframework.http.HttpMethod.GET; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.http.client; /** * @author marten */ public class TenantContextHeaderInterceptorTest { private TenantContextHeaderInterceptor interceptor = new TenantContextHeaderInterceptor(); @Test public void shouldSetHeaderOnRequest() { this.interceptor.setHeaderName("context"); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(this.interceptor); RestTemplate template = new RestTemplate(); template.setInterceptors(interceptors); MockRestServiceServer mockServer = MockRestServiceServer.createServer(template); mockServer.expect(requestTo("/test")) .andExpect(method(GET)) .andExpect(header("context", "test-context")) .andRespond(MockRestResponseCreators.withSuccess());
TenantContextTestUtil.setCurrentTenant("test-context");
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/filter/TenantContextFilter.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import biz.deinum.multitenant.web.TenantIdentificationStrategy; import java.io.IOException; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * <p>{@code javax.servlet.Filter} which sets the context from the current request. * * <p>Delegates the actual lookup to a {@code TenantIdentificationStrategy}. * * <p>When no context is found an {@code IllegalStateException} is thrown, this can be * switched off by setting the {@code throwExceptionOnMissingTenant}property. * * @author Marten Deinum * @since 1.3 **/ public class TenantContextFilter extends OncePerRequestFilter { private final Logger logger = LoggerFactory.getLogger(TenantContextFilter.class);
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/filter/TenantContextFilter.java import biz.deinum.multitenant.web.TenantIdentificationStrategy; import java.io.IOException; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * <p>{@code javax.servlet.Filter} which sets the context from the current request. * * <p>Delegates the actual lookup to a {@code TenantIdentificationStrategy}. * * <p>When no context is found an {@code IllegalStateException} is thrown, this can be * switched off by setting the {@code throwExceptionOnMissingTenant}property. * * @author Marten Deinum * @since 1.3 **/ public class TenantContextFilter extends OncePerRequestFilter { private final Logger logger = LoggerFactory.getLogger(TenantContextFilter.class);
private final List<TenantIdentificationStrategy> strategies;
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/filter/TenantContextFilter.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import biz.deinum.multitenant.web.TenantIdentificationStrategy; import java.io.IOException; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * <p>{@code javax.servlet.Filter} which sets the context from the current request. * * <p>Delegates the actual lookup to a {@code TenantIdentificationStrategy}. * * <p>When no context is found an {@code IllegalStateException} is thrown, this can be * switched off by setting the {@code throwExceptionOnMissingTenant}property. * * @author Marten Deinum * @since 1.3 **/ public class TenantContextFilter extends OncePerRequestFilter { private final Logger logger = LoggerFactory.getLogger(TenantContextFilter.class); private final List<TenantIdentificationStrategy> strategies; private boolean throwExceptionOnMissingTenant = true; public TenantContextFilter(List<TenantIdentificationStrategy> strategies) { super(); Assert.notEmpty(strategies, "At least one TenantIdentificationStrategy is required."); this.strategies = strategies; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/filter/TenantContextFilter.java import biz.deinum.multitenant.web.TenantIdentificationStrategy; import java.io.IOException; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * <p>{@code javax.servlet.Filter} which sets the context from the current request. * * <p>Delegates the actual lookup to a {@code TenantIdentificationStrategy}. * * <p>When no context is found an {@code IllegalStateException} is thrown, this can be * switched off by setting the {@code throwExceptionOnMissingTenant}property. * * @author Marten Deinum * @since 1.3 **/ public class TenantContextFilter extends OncePerRequestFilter { private final Logger logger = LoggerFactory.getLogger(TenantContextFilter.class); private final List<TenantIdentificationStrategy> strategies; private boolean throwExceptionOnMissingTenant = true; public TenantContextFilter(List<TenantIdentificationStrategy> strategies) { super(); Assert.notEmpty(strategies, "At least one TenantIdentificationStrategy is required."); this.strategies = strategies; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try {
TenantContext context = determineTenantContext(request);
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextThemeResolver.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; import org.springframework.web.servlet.theme.AbstractThemeResolver; import biz.deinum.multitenant.context.TenantContextHolder;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code ThemeResolver} implementation which returns the current Context as * the name of the theme to use. * * Optionally a {@code prefix} and {@code suffix} can be applied. * * @author Marten Deinum * @since 1.3 */ public class TenantContextThemeResolver extends AbstractThemeResolver { private String prefix = ""; private String suffix = ""; @Override public String resolveThemeName(HttpServletRequest request) {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/servlet/TenantContextThemeResolver.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; import org.springframework.web.servlet.theme.AbstractThemeResolver; import biz.deinum.multitenant.context.TenantContextHolder; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * {@code ThemeResolver} implementation which returns the current Context as * the name of the theme to use. * * Optionally a {@code prefix} and {@code suffix} can be applied. * * @author Marten Deinum * @since 1.3 */ public class TenantContextThemeResolver extends AbstractThemeResolver { private String prefix = ""; private String suffix = ""; @Override public String resolveThemeName(HttpServletRequest request) {
String tenant = TenantContextHolder.getContext().getTenant();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/concurrent/TenantContextRunnable.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // }
import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.concurrent; /** * {@link Runnable} which will set the current {@link TenantContext} before further executing. * * @author Marten Deinum * @since 1.3 */ public abstract class TenantContextRunnable implements Runnable { private final TenantContext context; protected TenantContextRunnable(TenantContext context) { this.context = context; } @Override public final void run() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContext.java // public interface TenantContext extends Serializable { // // // /** // * Get the tenant // * @return the tenant // */ // String getTenant(); // // /** // * Set the tenant. // * // * @param tenant the tenant // */ // void setTenant(String tenant); // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/concurrent/TenantContextRunnable.java import biz.deinum.multitenant.context.TenantContext; import biz.deinum.multitenant.context.TenantContextHolder; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.concurrent; /** * {@link Runnable} which will set the current {@link TenantContext} before further executing. * * @author Marten Deinum * @since 1.3 */ public abstract class TenantContextRunnable implements Runnable { private final TenantContext context; protected TenantContextRunnable(TenantContext context) { this.context = context; } @Override public final void run() {
final TenantContext previousContext = TenantContextHolder.getContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/hibernate/context/TenantContextCurrentTenantIdentifierResolver.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // }
import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import biz.deinum.multitenant.context.TenantContextHolder;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.hibernate.context; /** * {@code CurrentTenantIdentifierResolver} which simply delegates to the {@link TenantContextHolder} to * determine the current tenant identifier. * * @author Marten Deinum * @since 1.3.0 */ public class TenantContextCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver { private boolean validateExistingCurrentSessions = true; @Override public String resolveCurrentTenantIdentifier() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/hibernate/context/TenantContextCurrentTenantIdentifierResolver.java import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import biz.deinum.multitenant.context.TenantContextHolder; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.hibernate.context; /** * {@code CurrentTenantIdentifierResolver} which simply delegates to the {@link TenantContextHolder} to * determine the current tenant identifier. * * @author Marten Deinum * @since 1.3.0 */ public class TenantContextCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver { private boolean validateExistingCurrentSessions = true; @Override public String resolveCurrentTenantIdentifier() {
return TenantContextHolder.getContext().getTenant();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/filter/TenantContextFilterTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import java.io.IOException; import java.util.Arrays; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.when;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * Tests for the {@link TenantContextFilter}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextFilterTest { @Mock
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/filter/TenantContextFilterTest.java import java.io.IOException; import java.util.Arrays; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.when; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * Tests for the {@link TenantContextFilter}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextFilterTest { @Mock
private TenantIdentificationStrategy strategy;
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/filter/TenantContextFilterTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // }
import java.io.IOException; import java.util.Arrays; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.when;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * Tests for the {@link TenantContextFilter}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextFilterTest { @Mock private TenantIdentificationStrategy strategy; private HttpServletRequest request = new MockHttpServletRequest(); private HttpServletResponse response = new MockHttpServletResponse(); private FilterChain mockChain = new MockFilterChain(); private TenantContextFilter filter; @Before public void before() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/web/TenantIdentificationStrategy.java // public interface TenantIdentificationStrategy { // // /** // * Determine the tenant based on the current request. If the strategy // * cannot determine a tenant, return {@code null}. // * // * @param request the current request // * @return the tenant or {@code null}. // */ // String getTenant(HttpServletRequest request); // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/filter/TenantContextFilterTest.java import java.io.IOException; import java.util.Arrays; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.web.TenantIdentificationStrategy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.when; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.filter; /** * Tests for the {@link TenantContextFilter}. * * @author Marten Deinum */ @RunWith(MockitoJUnitRunner.class) public class TenantContextFilterTest { @Mock private TenantIdentificationStrategy strategy; private HttpServletRequest request = new MockHttpServletRequest(); private HttpServletResponse response = new MockHttpServletResponse(); private FilterChain mockChain = new MockFilterChain(); private TenantContextFilter filter; @Before public void before() {
TenantContextHolder.clearContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextThemeResolverTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // }
import org.junit.Before; import org.junit.Test; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * @author marten */ public class TenantContextThemeResolverTest { private final TenantContextThemeResolver resolver = new TenantContextThemeResolver(); @Before public void setup() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextThemeResolverTest.java import org.junit.Before; import org.junit.Test; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * @author marten */ public class TenantContextThemeResolverTest { private final TenantContextThemeResolver resolver = new TenantContextThemeResolver(); @Before public void setup() {
TenantContextHolder.clearContext();
mdeinum/spring-multi-tenancy
spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextThemeResolverTest.java
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // }
import org.junit.Before; import org.junit.Test; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
/* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * @author marten */ public class TenantContextThemeResolverTest { private final TenantContextThemeResolver resolver = new TenantContextThemeResolver(); @Before public void setup() { TenantContextHolder.clearContext(); } @Test public void whenNoContextSetReturnTheDefaultTheme() { String theme = this.resolver.resolveThemeName(null); assertThat(theme, is("theme")); } @Test public void whenContextSetReturnThatContextAsTheme() {
// Path: spring-multi-tenancy-core/src/main/java/biz/deinum/multitenant/context/TenantContextHolder.java // public abstract class TenantContextHolder { // // public static final String MODE_THREADLOCAL = "MODE_THREADLOCAL"; // public static final String MODE_INHERITABLETHREADLOCAL = "MODE_INHERITABLETHREADLOCAL"; // public static final String MODE_GLOBAL = "MODE_GLOBAL"; // public static final String SYSTEM_PROPERTY = "multi_tenant.strategy"; // // private static String strategyName = System.getProperty(SYSTEM_PROPERTY, MODE_THREADLOCAL); // // private static TenantContextHolderStrategy strategy; // // static { // initialize(); // } // // private static void initialize() { // if ((strategyName == null) || "".equals(strategyName)) { // // Set default // strategyName = MODE_THREADLOCAL; // } // // if (strategyName.equals(MODE_THREADLOCAL)) { // strategy = new ThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { // strategy = new InheritableThreadLocalTenantContextHolderStrategy(); // } // else if (strategyName.equals(MODE_GLOBAL)) { // strategy = new GlobalTenantContextHolderStrategy(); // } // else { // // Try to load a custom strategy // try { // Class<?> clazz = Class.forName(strategyName); // Constructor<?> customStrategy = clazz.getConstructor(); // strategy = (TenantContextHolderStrategy) customStrategy.newInstance(); // } // catch (Exception ex) { // ReflectionUtils.handleReflectionException(ex); // } // } // } // // public static TenantContext getContext() { // TenantContext context = strategy.getContext(); // return context; // } // // public static void setContext(final TenantContext context) { // strategy.setContext(context); // } // // public static void clearContext() { // strategy.clearContext(); // } // // public static TenantContext createEmptyContext() { // return strategy.createEmptyContext(); // } // // /** // * Changes the preferred strategy. Do <em>NOT</em> call this method more than once for // * a given JVM, as it will re-initialize the strategy and adversely affect any // * existing threads using the old strategy. // * // * @param strategyName the fully qualified class name of the strategy that should be // * used. // */ // public static void setStrategyName(String strategyName) { // TenantContextHolder.strategyName = strategyName; // initialize(); // } // // @Override // public String toString() { // return String.format("TenantContextHolder [strategy=%s]", strategyName); // } // } // // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/context/TenantContextTestUtil.java // public abstract class TenantContextTestUtil { // // public static void setCurrentTenant(String tenant) { // // TenantContext mockContext = new MockTenantContext(); // mockContext.setTenant(tenant); // // TenantContextHolder.setContext(mockContext); // // } // // } // Path: spring-multi-tenancy-core/src/test/java/biz/deinum/multitenant/web/servlet/TenantContextThemeResolverTest.java import org.junit.Before; import org.junit.Test; import biz.deinum.multitenant.context.TenantContextHolder; import biz.deinum.multitenant.context.TenantContextTestUtil; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /* * Copyright 2007-2016 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 * * 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 biz.deinum.multitenant.web.servlet; /** * @author marten */ public class TenantContextThemeResolverTest { private final TenantContextThemeResolver resolver = new TenantContextThemeResolver(); @Before public void setup() { TenantContextHolder.clearContext(); } @Test public void whenNoContextSetReturnTheDefaultTheme() { String theme = this.resolver.resolveThemeName(null); assertThat(theme, is("theme")); } @Test public void whenContextSetReturnThatContextAsTheme() {
TenantContextTestUtil.setCurrentTenant("test-theme");
pac4j/jax-rs-pac4j
jersey225/src/test/java/org/pac4j/jax/rs/rules/JerseyGrizzlyServletRule.java
// Path: jersey225/src/test/java/org/pac4j/jax/rs/resources/JerseyResource.java // @Path("/containerSpecific") // public class JerseyResource { // // @Context // private Providers providers; // // @Inject // private ContainerRequestContext requestContext; // // @POST // @Path("/securitycontext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directSecurityContext() { // // Note: SecurityContext injected via @Context can't be cast // SecurityContext context = requestContext.getSecurityContext(); // if (context != null) { // if (context instanceof Pac4JSecurityContext) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("/context") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext() { // JaxRsContext context = new ProvidersContext(providers).resolveNotNull(JaxRsContextFactory.class) // .provides(requestContext); // if (context != null) { // return "ok"; // } else { // return "fail"; // } // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/servlet/features/ServletJaxRsContextFactoryProvider.java // public class ServletJaxRsContextFactoryProvider extends JaxRsContextFactoryProvider { // // @Inject // private Provider<HttpServletRequest> requestProvider; // // @Override // public JaxRsContextFactory getContext(Class<?> type) { // return context -> new ServletJaxRsContext(getProviders(), context, getConfig().getSessionStore(), requestProvider.get()); // } // }
import java.util.Set; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.glassfish.jersey.test.DeploymentContext; import org.glassfish.jersey.test.ServletDeploymentContext; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.glassfish.jersey.test.spi.TestContainerFactory; import org.pac4j.jax.rs.resources.JerseyResource; import org.pac4j.jax.rs.servlet.features.ServletJaxRsContextFactoryProvider;
package org.pac4j.jax.rs.rules; public class JerseyGrizzlyServletRule extends JerseyRule implements SessionContainerRule { @Override public Set<Class<?>> getResources() { Set<Class<?>> resources = SessionContainerRule.super.getResources();
// Path: jersey225/src/test/java/org/pac4j/jax/rs/resources/JerseyResource.java // @Path("/containerSpecific") // public class JerseyResource { // // @Context // private Providers providers; // // @Inject // private ContainerRequestContext requestContext; // // @POST // @Path("/securitycontext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directSecurityContext() { // // Note: SecurityContext injected via @Context can't be cast // SecurityContext context = requestContext.getSecurityContext(); // if (context != null) { // if (context instanceof Pac4JSecurityContext) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("/context") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext() { // JaxRsContext context = new ProvidersContext(providers).resolveNotNull(JaxRsContextFactory.class) // .provides(requestContext); // if (context != null) { // return "ok"; // } else { // return "fail"; // } // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/servlet/features/ServletJaxRsContextFactoryProvider.java // public class ServletJaxRsContextFactoryProvider extends JaxRsContextFactoryProvider { // // @Inject // private Provider<HttpServletRequest> requestProvider; // // @Override // public JaxRsContextFactory getContext(Class<?> type) { // return context -> new ServletJaxRsContext(getProviders(), context, getConfig().getSessionStore(), requestProvider.get()); // } // } // Path: jersey225/src/test/java/org/pac4j/jax/rs/rules/JerseyGrizzlyServletRule.java import java.util.Set; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.glassfish.jersey.test.DeploymentContext; import org.glassfish.jersey.test.ServletDeploymentContext; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.glassfish.jersey.test.spi.TestContainerFactory; import org.pac4j.jax.rs.resources.JerseyResource; import org.pac4j.jax.rs.servlet.features.ServletJaxRsContextFactoryProvider; package org.pac4j.jax.rs.rules; public class JerseyGrizzlyServletRule extends JerseyRule implements SessionContainerRule { @Override public Set<Class<?>> getResources() { Set<Class<?>> resources = SessionContainerRule.super.getResources();
resources.add(JerseyResource.class);
pac4j/jax-rs-pac4j
jersey225/src/test/java/org/pac4j/jax/rs/rules/JerseyGrizzlyServletRule.java
// Path: jersey225/src/test/java/org/pac4j/jax/rs/resources/JerseyResource.java // @Path("/containerSpecific") // public class JerseyResource { // // @Context // private Providers providers; // // @Inject // private ContainerRequestContext requestContext; // // @POST // @Path("/securitycontext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directSecurityContext() { // // Note: SecurityContext injected via @Context can't be cast // SecurityContext context = requestContext.getSecurityContext(); // if (context != null) { // if (context instanceof Pac4JSecurityContext) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("/context") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext() { // JaxRsContext context = new ProvidersContext(providers).resolveNotNull(JaxRsContextFactory.class) // .provides(requestContext); // if (context != null) { // return "ok"; // } else { // return "fail"; // } // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/servlet/features/ServletJaxRsContextFactoryProvider.java // public class ServletJaxRsContextFactoryProvider extends JaxRsContextFactoryProvider { // // @Inject // private Provider<HttpServletRequest> requestProvider; // // @Override // public JaxRsContextFactory getContext(Class<?> type) { // return context -> new ServletJaxRsContext(getProviders(), context, getConfig().getSessionStore(), requestProvider.get()); // } // }
import java.util.Set; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.glassfish.jersey.test.DeploymentContext; import org.glassfish.jersey.test.ServletDeploymentContext; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.glassfish.jersey.test.spi.TestContainerFactory; import org.pac4j.jax.rs.resources.JerseyResource; import org.pac4j.jax.rs.servlet.features.ServletJaxRsContextFactoryProvider;
package org.pac4j.jax.rs.rules; public class JerseyGrizzlyServletRule extends JerseyRule implements SessionContainerRule { @Override public Set<Class<?>> getResources() { Set<Class<?>> resources = SessionContainerRule.super.getResources(); resources.add(JerseyResource.class); return resources; } @Override protected TestContainerFactory getTestContainerFactory() { return new GrizzlyWebTestContainerFactory(); } @Override protected DeploymentContext configureDeployment(ResourceConfig config) { return ServletDeploymentContext.forServlet(new ServletContainer(config)).build(); } @Override protected ResourceConfig configureResourceConfig(ResourceConfig config) { return super .configureResourceConfig(config)
// Path: jersey225/src/test/java/org/pac4j/jax/rs/resources/JerseyResource.java // @Path("/containerSpecific") // public class JerseyResource { // // @Context // private Providers providers; // // @Inject // private ContainerRequestContext requestContext; // // @POST // @Path("/securitycontext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directSecurityContext() { // // Note: SecurityContext injected via @Context can't be cast // SecurityContext context = requestContext.getSecurityContext(); // if (context != null) { // if (context instanceof Pac4JSecurityContext) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("/context") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext() { // JaxRsContext context = new ProvidersContext(providers).resolveNotNull(JaxRsContextFactory.class) // .provides(requestContext); // if (context != null) { // return "ok"; // } else { // return "fail"; // } // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/servlet/features/ServletJaxRsContextFactoryProvider.java // public class ServletJaxRsContextFactoryProvider extends JaxRsContextFactoryProvider { // // @Inject // private Provider<HttpServletRequest> requestProvider; // // @Override // public JaxRsContextFactory getContext(Class<?> type) { // return context -> new ServletJaxRsContext(getProviders(), context, getConfig().getSessionStore(), requestProvider.get()); // } // } // Path: jersey225/src/test/java/org/pac4j/jax/rs/rules/JerseyGrizzlyServletRule.java import java.util.Set; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.glassfish.jersey.test.DeploymentContext; import org.glassfish.jersey.test.ServletDeploymentContext; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; import org.glassfish.jersey.test.spi.TestContainerFactory; import org.pac4j.jax.rs.resources.JerseyResource; import org.pac4j.jax.rs.servlet.features.ServletJaxRsContextFactoryProvider; package org.pac4j.jax.rs.rules; public class JerseyGrizzlyServletRule extends JerseyRule implements SessionContainerRule { @Override public Set<Class<?>> getResources() { Set<Class<?>> resources = SessionContainerRule.super.getResources(); resources.add(JerseyResource.class); return resources; } @Override protected TestContainerFactory getTestContainerFactory() { return new GrizzlyWebTestContainerFactory(); } @Override protected DeploymentContext configureDeployment(ResourceConfig config) { return ServletDeploymentContext.forServlet(new ServletContainer(config)).build(); } @Override protected ResourceConfig configureResourceConfig(ResourceConfig config) { return super .configureResourceConfig(config)
.register(ServletJaxRsContextFactoryProvider.class);
pac4j/jax-rs-pac4j
testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java
// Path: testing/src/main/java/org/pac4j/jax/rs/TestConfig.java // public interface TestConfig { // // String DEFAULT_CLIENT = "default-form"; // // default Config getConfig() { // // login not used because the ajax resolver always answer true // Authenticator<UsernamePasswordCredentials> auth = new SimpleTestUsernamePasswordAuthenticator(); // FormClient client = new FormClient("notUsedLoginUrl", auth); // DirectFormClient client2 = new DirectFormClient(auth); // DirectFormClient client3 = new DirectFormClient(auth); // client3.setName(DEFAULT_CLIENT); // // Clients clients = new Clients("notUsedCallbackUrl", client, client2, client3); // // in case of invalid credentials, we simply want the error, not a redirect to the login url // clients.setAjaxRequestResolver(new JaxRsAjaxRequestResolver()); // // // so that callback url have the correct prefix w.r.t. the container's context // clients.setUrlResolver(new JaxRsUrlResolver()); // // clients.setDefaultSecurityClients(DEFAULT_CLIENT); // // return new Config(clients); // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestClassLevelResource.java // @Path("/class") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public class TestClassLevelResource { // // @GET // @Path("no") // @Pac4JSecurity(ignore = true) // public String get() { // return "ok"; // } // // @POST // @Path("direct") // public String direct() { // return "ok"; // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestProxyResource.java // @Path("/") // public class TestProxyResource { // // @Path("proxied/class") // public TestClassLevelResource proxiedResource() { // try { // final ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(TestClassLevelResource.class); // final Proxy proxy = (Proxy) factory.createClass().newInstance(); // proxy.setHandler((self, overridden, proceed, args) -> { // return proceed.invoke(self, args); // }); // // return (TestClassLevelResource) proxy; // } catch (InstantiationException | IllegalAccessException e) { // throw new AssertionError(e); // } // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestResource.java // @Path("/") // public class TestResource { // // private final Authorizer<CommonProfile> IS_AUTHENTICATED_AUTHORIZER = new IsAuthenticatedAuthorizer<>(); // // @GET // @Path("no") // public String get() { // return "ok"; // } // // @POST // @Path("direct") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String direct() { // return "ok"; // } // // @POST // @Path("defaultDirect") // @Pac4JSecurity(authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String defaultDirect() { // return "ok"; // } // // @POST // @Path("directInject") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directInject(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directContext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext(@Context SecurityContext context) { // if (context != null) { // if (context.getUserPrincipal() instanceof Pac4JPrincipal) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @GET // @Path("directInjectNoAuth") // public String directInjectNoAuth(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directInjectManager") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectManager(@Pac4JProfileManager ProfileManager<CommonProfile> pm) throws HttpAction { // if (pm != null) { // // pm.isAuthorized is relying on the session... // if (IS_AUTHENTICATED_AUTHORIZER.isAuthorized(null, pm.getAll(false))) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("directInjectSkip") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectSkip(@Pac4JProfile Optional<CommonProfile> profile) { // if (profile.isPresent()) { // return "ok"; // } else { // return "fail"; // } // } // // @POST // @Path("directResponseHeadersSet") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, matchers = DefaultMatchers.NOSNIFF) // public String directResponseHeadersSet() { // return "ok"; // } // }
import java.util.Set; import javax.ws.rs.client.WebTarget; import org.assertj.core.util.Sets; import org.junit.rules.TestRule; import org.pac4j.jax.rs.TestConfig; import org.pac4j.jax.rs.resources.TestClassLevelResource; import org.pac4j.jax.rs.resources.TestProxyResource; import org.pac4j.jax.rs.resources.TestResource;
package org.pac4j.jax.rs.rules; public interface ContainerRule extends TestRule, TestConfig { WebTarget getTarget(String url); String cookieName(); default Set<Class<?>> getResources() {
// Path: testing/src/main/java/org/pac4j/jax/rs/TestConfig.java // public interface TestConfig { // // String DEFAULT_CLIENT = "default-form"; // // default Config getConfig() { // // login not used because the ajax resolver always answer true // Authenticator<UsernamePasswordCredentials> auth = new SimpleTestUsernamePasswordAuthenticator(); // FormClient client = new FormClient("notUsedLoginUrl", auth); // DirectFormClient client2 = new DirectFormClient(auth); // DirectFormClient client3 = new DirectFormClient(auth); // client3.setName(DEFAULT_CLIENT); // // Clients clients = new Clients("notUsedCallbackUrl", client, client2, client3); // // in case of invalid credentials, we simply want the error, not a redirect to the login url // clients.setAjaxRequestResolver(new JaxRsAjaxRequestResolver()); // // // so that callback url have the correct prefix w.r.t. the container's context // clients.setUrlResolver(new JaxRsUrlResolver()); // // clients.setDefaultSecurityClients(DEFAULT_CLIENT); // // return new Config(clients); // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestClassLevelResource.java // @Path("/class") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public class TestClassLevelResource { // // @GET // @Path("no") // @Pac4JSecurity(ignore = true) // public String get() { // return "ok"; // } // // @POST // @Path("direct") // public String direct() { // return "ok"; // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestProxyResource.java // @Path("/") // public class TestProxyResource { // // @Path("proxied/class") // public TestClassLevelResource proxiedResource() { // try { // final ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(TestClassLevelResource.class); // final Proxy proxy = (Proxy) factory.createClass().newInstance(); // proxy.setHandler((self, overridden, proceed, args) -> { // return proceed.invoke(self, args); // }); // // return (TestClassLevelResource) proxy; // } catch (InstantiationException | IllegalAccessException e) { // throw new AssertionError(e); // } // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestResource.java // @Path("/") // public class TestResource { // // private final Authorizer<CommonProfile> IS_AUTHENTICATED_AUTHORIZER = new IsAuthenticatedAuthorizer<>(); // // @GET // @Path("no") // public String get() { // return "ok"; // } // // @POST // @Path("direct") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String direct() { // return "ok"; // } // // @POST // @Path("defaultDirect") // @Pac4JSecurity(authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String defaultDirect() { // return "ok"; // } // // @POST // @Path("directInject") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directInject(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directContext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext(@Context SecurityContext context) { // if (context != null) { // if (context.getUserPrincipal() instanceof Pac4JPrincipal) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @GET // @Path("directInjectNoAuth") // public String directInjectNoAuth(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directInjectManager") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectManager(@Pac4JProfileManager ProfileManager<CommonProfile> pm) throws HttpAction { // if (pm != null) { // // pm.isAuthorized is relying on the session... // if (IS_AUTHENTICATED_AUTHORIZER.isAuthorized(null, pm.getAll(false))) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("directInjectSkip") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectSkip(@Pac4JProfile Optional<CommonProfile> profile) { // if (profile.isPresent()) { // return "ok"; // } else { // return "fail"; // } // } // // @POST // @Path("directResponseHeadersSet") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, matchers = DefaultMatchers.NOSNIFF) // public String directResponseHeadersSet() { // return "ok"; // } // } // Path: testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java import java.util.Set; import javax.ws.rs.client.WebTarget; import org.assertj.core.util.Sets; import org.junit.rules.TestRule; import org.pac4j.jax.rs.TestConfig; import org.pac4j.jax.rs.resources.TestClassLevelResource; import org.pac4j.jax.rs.resources.TestProxyResource; import org.pac4j.jax.rs.resources.TestResource; package org.pac4j.jax.rs.rules; public interface ContainerRule extends TestRule, TestConfig { WebTarget getTarget(String url); String cookieName(); default Set<Class<?>> getResources() {
return Sets.newLinkedHashSet(TestResource.class, TestClassLevelResource.class, TestProxyResource.class);
pac4j/jax-rs-pac4j
testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java
// Path: testing/src/main/java/org/pac4j/jax/rs/TestConfig.java // public interface TestConfig { // // String DEFAULT_CLIENT = "default-form"; // // default Config getConfig() { // // login not used because the ajax resolver always answer true // Authenticator<UsernamePasswordCredentials> auth = new SimpleTestUsernamePasswordAuthenticator(); // FormClient client = new FormClient("notUsedLoginUrl", auth); // DirectFormClient client2 = new DirectFormClient(auth); // DirectFormClient client3 = new DirectFormClient(auth); // client3.setName(DEFAULT_CLIENT); // // Clients clients = new Clients("notUsedCallbackUrl", client, client2, client3); // // in case of invalid credentials, we simply want the error, not a redirect to the login url // clients.setAjaxRequestResolver(new JaxRsAjaxRequestResolver()); // // // so that callback url have the correct prefix w.r.t. the container's context // clients.setUrlResolver(new JaxRsUrlResolver()); // // clients.setDefaultSecurityClients(DEFAULT_CLIENT); // // return new Config(clients); // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestClassLevelResource.java // @Path("/class") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public class TestClassLevelResource { // // @GET // @Path("no") // @Pac4JSecurity(ignore = true) // public String get() { // return "ok"; // } // // @POST // @Path("direct") // public String direct() { // return "ok"; // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestProxyResource.java // @Path("/") // public class TestProxyResource { // // @Path("proxied/class") // public TestClassLevelResource proxiedResource() { // try { // final ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(TestClassLevelResource.class); // final Proxy proxy = (Proxy) factory.createClass().newInstance(); // proxy.setHandler((self, overridden, proceed, args) -> { // return proceed.invoke(self, args); // }); // // return (TestClassLevelResource) proxy; // } catch (InstantiationException | IllegalAccessException e) { // throw new AssertionError(e); // } // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestResource.java // @Path("/") // public class TestResource { // // private final Authorizer<CommonProfile> IS_AUTHENTICATED_AUTHORIZER = new IsAuthenticatedAuthorizer<>(); // // @GET // @Path("no") // public String get() { // return "ok"; // } // // @POST // @Path("direct") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String direct() { // return "ok"; // } // // @POST // @Path("defaultDirect") // @Pac4JSecurity(authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String defaultDirect() { // return "ok"; // } // // @POST // @Path("directInject") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directInject(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directContext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext(@Context SecurityContext context) { // if (context != null) { // if (context.getUserPrincipal() instanceof Pac4JPrincipal) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @GET // @Path("directInjectNoAuth") // public String directInjectNoAuth(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directInjectManager") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectManager(@Pac4JProfileManager ProfileManager<CommonProfile> pm) throws HttpAction { // if (pm != null) { // // pm.isAuthorized is relying on the session... // if (IS_AUTHENTICATED_AUTHORIZER.isAuthorized(null, pm.getAll(false))) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("directInjectSkip") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectSkip(@Pac4JProfile Optional<CommonProfile> profile) { // if (profile.isPresent()) { // return "ok"; // } else { // return "fail"; // } // } // // @POST // @Path("directResponseHeadersSet") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, matchers = DefaultMatchers.NOSNIFF) // public String directResponseHeadersSet() { // return "ok"; // } // }
import java.util.Set; import javax.ws.rs.client.WebTarget; import org.assertj.core.util.Sets; import org.junit.rules.TestRule; import org.pac4j.jax.rs.TestConfig; import org.pac4j.jax.rs.resources.TestClassLevelResource; import org.pac4j.jax.rs.resources.TestProxyResource; import org.pac4j.jax.rs.resources.TestResource;
package org.pac4j.jax.rs.rules; public interface ContainerRule extends TestRule, TestConfig { WebTarget getTarget(String url); String cookieName(); default Set<Class<?>> getResources() {
// Path: testing/src/main/java/org/pac4j/jax/rs/TestConfig.java // public interface TestConfig { // // String DEFAULT_CLIENT = "default-form"; // // default Config getConfig() { // // login not used because the ajax resolver always answer true // Authenticator<UsernamePasswordCredentials> auth = new SimpleTestUsernamePasswordAuthenticator(); // FormClient client = new FormClient("notUsedLoginUrl", auth); // DirectFormClient client2 = new DirectFormClient(auth); // DirectFormClient client3 = new DirectFormClient(auth); // client3.setName(DEFAULT_CLIENT); // // Clients clients = new Clients("notUsedCallbackUrl", client, client2, client3); // // in case of invalid credentials, we simply want the error, not a redirect to the login url // clients.setAjaxRequestResolver(new JaxRsAjaxRequestResolver()); // // // so that callback url have the correct prefix w.r.t. the container's context // clients.setUrlResolver(new JaxRsUrlResolver()); // // clients.setDefaultSecurityClients(DEFAULT_CLIENT); // // return new Config(clients); // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestClassLevelResource.java // @Path("/class") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public class TestClassLevelResource { // // @GET // @Path("no") // @Pac4JSecurity(ignore = true) // public String get() { // return "ok"; // } // // @POST // @Path("direct") // public String direct() { // return "ok"; // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestProxyResource.java // @Path("/") // public class TestProxyResource { // // @Path("proxied/class") // public TestClassLevelResource proxiedResource() { // try { // final ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(TestClassLevelResource.class); // final Proxy proxy = (Proxy) factory.createClass().newInstance(); // proxy.setHandler((self, overridden, proceed, args) -> { // return proceed.invoke(self, args); // }); // // return (TestClassLevelResource) proxy; // } catch (InstantiationException | IllegalAccessException e) { // throw new AssertionError(e); // } // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestResource.java // @Path("/") // public class TestResource { // // private final Authorizer<CommonProfile> IS_AUTHENTICATED_AUTHORIZER = new IsAuthenticatedAuthorizer<>(); // // @GET // @Path("no") // public String get() { // return "ok"; // } // // @POST // @Path("direct") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String direct() { // return "ok"; // } // // @POST // @Path("defaultDirect") // @Pac4JSecurity(authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String defaultDirect() { // return "ok"; // } // // @POST // @Path("directInject") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directInject(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directContext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext(@Context SecurityContext context) { // if (context != null) { // if (context.getUserPrincipal() instanceof Pac4JPrincipal) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @GET // @Path("directInjectNoAuth") // public String directInjectNoAuth(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directInjectManager") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectManager(@Pac4JProfileManager ProfileManager<CommonProfile> pm) throws HttpAction { // if (pm != null) { // // pm.isAuthorized is relying on the session... // if (IS_AUTHENTICATED_AUTHORIZER.isAuthorized(null, pm.getAll(false))) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("directInjectSkip") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectSkip(@Pac4JProfile Optional<CommonProfile> profile) { // if (profile.isPresent()) { // return "ok"; // } else { // return "fail"; // } // } // // @POST // @Path("directResponseHeadersSet") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, matchers = DefaultMatchers.NOSNIFF) // public String directResponseHeadersSet() { // return "ok"; // } // } // Path: testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java import java.util.Set; import javax.ws.rs.client.WebTarget; import org.assertj.core.util.Sets; import org.junit.rules.TestRule; import org.pac4j.jax.rs.TestConfig; import org.pac4j.jax.rs.resources.TestClassLevelResource; import org.pac4j.jax.rs.resources.TestProxyResource; import org.pac4j.jax.rs.resources.TestResource; package org.pac4j.jax.rs.rules; public interface ContainerRule extends TestRule, TestConfig { WebTarget getTarget(String url); String cookieName(); default Set<Class<?>> getResources() {
return Sets.newLinkedHashSet(TestResource.class, TestClassLevelResource.class, TestProxyResource.class);
pac4j/jax-rs-pac4j
testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java
// Path: testing/src/main/java/org/pac4j/jax/rs/TestConfig.java // public interface TestConfig { // // String DEFAULT_CLIENT = "default-form"; // // default Config getConfig() { // // login not used because the ajax resolver always answer true // Authenticator<UsernamePasswordCredentials> auth = new SimpleTestUsernamePasswordAuthenticator(); // FormClient client = new FormClient("notUsedLoginUrl", auth); // DirectFormClient client2 = new DirectFormClient(auth); // DirectFormClient client3 = new DirectFormClient(auth); // client3.setName(DEFAULT_CLIENT); // // Clients clients = new Clients("notUsedCallbackUrl", client, client2, client3); // // in case of invalid credentials, we simply want the error, not a redirect to the login url // clients.setAjaxRequestResolver(new JaxRsAjaxRequestResolver()); // // // so that callback url have the correct prefix w.r.t. the container's context // clients.setUrlResolver(new JaxRsUrlResolver()); // // clients.setDefaultSecurityClients(DEFAULT_CLIENT); // // return new Config(clients); // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestClassLevelResource.java // @Path("/class") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public class TestClassLevelResource { // // @GET // @Path("no") // @Pac4JSecurity(ignore = true) // public String get() { // return "ok"; // } // // @POST // @Path("direct") // public String direct() { // return "ok"; // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestProxyResource.java // @Path("/") // public class TestProxyResource { // // @Path("proxied/class") // public TestClassLevelResource proxiedResource() { // try { // final ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(TestClassLevelResource.class); // final Proxy proxy = (Proxy) factory.createClass().newInstance(); // proxy.setHandler((self, overridden, proceed, args) -> { // return proceed.invoke(self, args); // }); // // return (TestClassLevelResource) proxy; // } catch (InstantiationException | IllegalAccessException e) { // throw new AssertionError(e); // } // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestResource.java // @Path("/") // public class TestResource { // // private final Authorizer<CommonProfile> IS_AUTHENTICATED_AUTHORIZER = new IsAuthenticatedAuthorizer<>(); // // @GET // @Path("no") // public String get() { // return "ok"; // } // // @POST // @Path("direct") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String direct() { // return "ok"; // } // // @POST // @Path("defaultDirect") // @Pac4JSecurity(authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String defaultDirect() { // return "ok"; // } // // @POST // @Path("directInject") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directInject(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directContext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext(@Context SecurityContext context) { // if (context != null) { // if (context.getUserPrincipal() instanceof Pac4JPrincipal) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @GET // @Path("directInjectNoAuth") // public String directInjectNoAuth(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directInjectManager") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectManager(@Pac4JProfileManager ProfileManager<CommonProfile> pm) throws HttpAction { // if (pm != null) { // // pm.isAuthorized is relying on the session... // if (IS_AUTHENTICATED_AUTHORIZER.isAuthorized(null, pm.getAll(false))) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("directInjectSkip") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectSkip(@Pac4JProfile Optional<CommonProfile> profile) { // if (profile.isPresent()) { // return "ok"; // } else { // return "fail"; // } // } // // @POST // @Path("directResponseHeadersSet") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, matchers = DefaultMatchers.NOSNIFF) // public String directResponseHeadersSet() { // return "ok"; // } // }
import java.util.Set; import javax.ws.rs.client.WebTarget; import org.assertj.core.util.Sets; import org.junit.rules.TestRule; import org.pac4j.jax.rs.TestConfig; import org.pac4j.jax.rs.resources.TestClassLevelResource; import org.pac4j.jax.rs.resources.TestProxyResource; import org.pac4j.jax.rs.resources.TestResource;
package org.pac4j.jax.rs.rules; public interface ContainerRule extends TestRule, TestConfig { WebTarget getTarget(String url); String cookieName(); default Set<Class<?>> getResources() {
// Path: testing/src/main/java/org/pac4j/jax/rs/TestConfig.java // public interface TestConfig { // // String DEFAULT_CLIENT = "default-form"; // // default Config getConfig() { // // login not used because the ajax resolver always answer true // Authenticator<UsernamePasswordCredentials> auth = new SimpleTestUsernamePasswordAuthenticator(); // FormClient client = new FormClient("notUsedLoginUrl", auth); // DirectFormClient client2 = new DirectFormClient(auth); // DirectFormClient client3 = new DirectFormClient(auth); // client3.setName(DEFAULT_CLIENT); // // Clients clients = new Clients("notUsedCallbackUrl", client, client2, client3); // // in case of invalid credentials, we simply want the error, not a redirect to the login url // clients.setAjaxRequestResolver(new JaxRsAjaxRequestResolver()); // // // so that callback url have the correct prefix w.r.t. the container's context // clients.setUrlResolver(new JaxRsUrlResolver()); // // clients.setDefaultSecurityClients(DEFAULT_CLIENT); // // return new Config(clients); // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestClassLevelResource.java // @Path("/class") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public class TestClassLevelResource { // // @GET // @Path("no") // @Pac4JSecurity(ignore = true) // public String get() { // return "ok"; // } // // @POST // @Path("direct") // public String direct() { // return "ok"; // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestProxyResource.java // @Path("/") // public class TestProxyResource { // // @Path("proxied/class") // public TestClassLevelResource proxiedResource() { // try { // final ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(TestClassLevelResource.class); // final Proxy proxy = (Proxy) factory.createClass().newInstance(); // proxy.setHandler((self, overridden, proceed, args) -> { // return proceed.invoke(self, args); // }); // // return (TestClassLevelResource) proxy; // } catch (InstantiationException | IllegalAccessException e) { // throw new AssertionError(e); // } // } // } // // Path: testing/src/main/java/org/pac4j/jax/rs/resources/TestResource.java // @Path("/") // public class TestResource { // // private final Authorizer<CommonProfile> IS_AUTHENTICATED_AUTHORIZER = new IsAuthenticatedAuthorizer<>(); // // @GET // @Path("no") // public String get() { // return "ok"; // } // // @POST // @Path("direct") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String direct() { // return "ok"; // } // // @POST // @Path("defaultDirect") // @Pac4JSecurity(authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String defaultDirect() { // return "ok"; // } // // @POST // @Path("directInject") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directInject(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directContext") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED) // public String directContext(@Context SecurityContext context) { // if (context != null) { // if (context.getUserPrincipal() instanceof Pac4JPrincipal) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @GET // @Path("directInjectNoAuth") // public String directInjectNoAuth(@Pac4JProfile CommonProfile profile) { // if (profile != null) { // return "ok"; // } else { // return "error"; // } // } // // @POST // @Path("directInjectManager") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectManager(@Pac4JProfileManager ProfileManager<CommonProfile> pm) throws HttpAction { // if (pm != null) { // // pm.isAuthorized is relying on the session... // if (IS_AUTHENTICATED_AUTHORIZER.isAuthorized(null, pm.getAll(false))) { // return "ok"; // } else { // return "fail"; // } // } else { // return "error"; // } // } // // @POST // @Path("directInjectSkip") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, skipResponse = true) // public String directInjectSkip(@Pac4JProfile Optional<CommonProfile> profile) { // if (profile.isPresent()) { // return "ok"; // } else { // return "fail"; // } // } // // @POST // @Path("directResponseHeadersSet") // @Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED, matchers = DefaultMatchers.NOSNIFF) // public String directResponseHeadersSet() { // return "ok"; // } // } // Path: testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java import java.util.Set; import javax.ws.rs.client.WebTarget; import org.assertj.core.util.Sets; import org.junit.rules.TestRule; import org.pac4j.jax.rs.TestConfig; import org.pac4j.jax.rs.resources.TestClassLevelResource; import org.pac4j.jax.rs.resources.TestProxyResource; import org.pac4j.jax.rs.resources.TestResource; package org.pac4j.jax.rs.rules; public interface ContainerRule extends TestRule, TestConfig { WebTarget getTarget(String url); String cookieName(); default Set<Class<?>> getResources() {
return Sets.newLinkedHashSet(TestResource.class, TestClassLevelResource.class, TestProxyResource.class);
pac4j/jax-rs-pac4j
testing/src/main/java/org/pac4j/jax/rs/AbstractTest.java
// Path: testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java // public interface ContainerRule extends TestRule, TestConfig { // // WebTarget getTarget(String url); // // String cookieName(); // // default Set<Class<?>> getResources() { // return Sets.newLinkedHashSet(TestResource.class, TestClassLevelResource.class, TestProxyResource.class); // } // }
import static org.assertj.core.api.Assertions.assertThat; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.junit.Rule; import org.junit.Test; import org.pac4j.jax.rs.rules.ContainerRule; import org.slf4j.bridge.SLF4JBridgeHandler;
package org.pac4j.jax.rs; /** * * @author Victor Noel - Linagora * @since 1.0.0 * */ public abstract class AbstractTest { static { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); // Logger.getLogger("org.glassfish").setLevel(Level.FINEST); } @Rule
// Path: testing/src/main/java/org/pac4j/jax/rs/rules/ContainerRule.java // public interface ContainerRule extends TestRule, TestConfig { // // WebTarget getTarget(String url); // // String cookieName(); // // default Set<Class<?>> getResources() { // return Sets.newLinkedHashSet(TestResource.class, TestClassLevelResource.class, TestProxyResource.class); // } // } // Path: testing/src/main/java/org/pac4j/jax/rs/AbstractTest.java import static org.assertj.core.api.Assertions.assertThat; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.junit.Rule; import org.junit.Test; import org.pac4j.jax.rs.rules.ContainerRule; import org.slf4j.bridge.SLF4JBridgeHandler; package org.pac4j.jax.rs; /** * * @author Victor Noel - Linagora * @since 1.0.0 * */ public abstract class AbstractTest { static { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); // Logger.getLogger("org.glassfish").setLevel(Level.FINEST); } @Rule
public ContainerRule container = createContainer();
pac4j/jax-rs-pac4j
jersey/src/main/java/org/pac4j/jax/rs/jersey/features/Pac4JValueFactoryProvider.java
// Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestUserProfile.java // public class RequestUserProfile { // // private final RequestPac4JSecurityContext context; // // public RequestUserProfile(RequestPac4JSecurityContext context) { // this.context = context; // } // // public Optional<UserProfile> profile() { // return context.context() // .flatMap(Pac4JSecurityContext::getProfiles) // .flatMap(ps -> ProfileHelper.flatIntoOneProfile(ps)); // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestJaxRsContext.java // public class RequestJaxRsContext { // // private final ProvidersContext providers; // private final ContainerRequestContext context; // // public RequestJaxRsContext(Providers providers, ContainerRequestContext context) { // this.providers = new ProvidersContext(providers); // this.context = context; // } // // public Optional<JaxRsContext> context() { // return new RequestPac4JSecurityContext(context).context().map(Pac4JSecurityContext::getContext); // } // // public JaxRsContext contextOrNew() { // return context().orElse(providers.resolveNotNull(JaxRsContextFactory.class).provides(context)); // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestPac4JSecurityContext.java // public class RequestPac4JSecurityContext { // // private final SecurityContext securityContext; // // public RequestPac4JSecurityContext(JaxRsContext context) { // this(context.getRequestContext()); // } // // public RequestPac4JSecurityContext(ContainerRequestContext request) { // this(request.getSecurityContext()); // } // // public RequestPac4JSecurityContext(SecurityContext securityContext) { // this.securityContext = securityContext; // } // // public Optional<Pac4JSecurityContext> context() { // if (securityContext instanceof Pac4JSecurityContext) { // return Optional.of((Pac4JSecurityContext) securityContext); // } else { // return Optional.empty(); // } // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestProfileManager.java // public class RequestProfileManager { // // private final RequestJaxRsContext context; // // public RequestProfileManager(RequestJaxRsContext context) { // this.context = context; // } // // public JaxRsProfileManager profileManager() { // return new JaxRsProfileManager(context.contextOrNew()); // } // }
import org.glassfish.jersey.internal.inject.AbstractBinder; import org.glassfish.jersey.internal.inject.InjectionResolver; import org.glassfish.jersey.internal.util.ReflectionHelper; import org.glassfish.jersey.internal.util.collection.ClassTypePair; import org.glassfish.jersey.server.ContainerRequest; import org.glassfish.jersey.server.internal.inject.AbstractValueParamProvider; import org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider; import org.glassfish.jersey.server.internal.inject.ParamInjectionResolver; import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.spi.internal.ValueParamProvider; import org.pac4j.core.profile.CommonProfile; import org.pac4j.core.profile.ProfileManager; import org.pac4j.core.profile.UserProfile; import org.pac4j.jax.rs.annotations.Pac4JProfile; import org.pac4j.jax.rs.annotations.Pac4JProfileManager; import org.pac4j.jax.rs.helpers.RequestUserProfile; import org.pac4j.jax.rs.helpers.RequestJaxRsContext; import org.pac4j.jax.rs.helpers.RequestPac4JSecurityContext; import org.pac4j.jax.rs.helpers.RequestProfileManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericType; import javax.ws.rs.ext.Providers; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier;
if(manager == null){ bind(DefaultProfileManagerFactoryBuilder.class) .to(ProfileManagerFactoryBuilder.class).in(Singleton.class); } else { bind(manager).to(ProfileManagerFactoryBuilder.class); } bindAsContract(Pac4JProfileValueFactoryProvider.class).to(ValueParamProvider.class).in(Singleton.class); bindAsContract(ProfileInjectionResolver.class) .to(new GenericType<InjectionResolver<Pac4JProfile>>(){}) .in(Singleton.class); bindAsContract(ProfileManagerInjectionResolver.class) .to(new GenericType<InjectionResolver<Pac4JProfileManager>>(){}) .in(Singleton.class); } } static class ProfileManagerValueFactory implements ProfileManagerFactory{ @Context private final Providers providers; ProfileManagerValueFactory(Providers providers) { this.providers = providers; } @Override public ProfileManager<CommonProfile> apply(ContainerRequest containerRequest) {
// Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestUserProfile.java // public class RequestUserProfile { // // private final RequestPac4JSecurityContext context; // // public RequestUserProfile(RequestPac4JSecurityContext context) { // this.context = context; // } // // public Optional<UserProfile> profile() { // return context.context() // .flatMap(Pac4JSecurityContext::getProfiles) // .flatMap(ps -> ProfileHelper.flatIntoOneProfile(ps)); // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestJaxRsContext.java // public class RequestJaxRsContext { // // private final ProvidersContext providers; // private final ContainerRequestContext context; // // public RequestJaxRsContext(Providers providers, ContainerRequestContext context) { // this.providers = new ProvidersContext(providers); // this.context = context; // } // // public Optional<JaxRsContext> context() { // return new RequestPac4JSecurityContext(context).context().map(Pac4JSecurityContext::getContext); // } // // public JaxRsContext contextOrNew() { // return context().orElse(providers.resolveNotNull(JaxRsContextFactory.class).provides(context)); // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestPac4JSecurityContext.java // public class RequestPac4JSecurityContext { // // private final SecurityContext securityContext; // // public RequestPac4JSecurityContext(JaxRsContext context) { // this(context.getRequestContext()); // } // // public RequestPac4JSecurityContext(ContainerRequestContext request) { // this(request.getSecurityContext()); // } // // public RequestPac4JSecurityContext(SecurityContext securityContext) { // this.securityContext = securityContext; // } // // public Optional<Pac4JSecurityContext> context() { // if (securityContext instanceof Pac4JSecurityContext) { // return Optional.of((Pac4JSecurityContext) securityContext); // } else { // return Optional.empty(); // } // } // } // // Path: core/src/main/java/org/pac4j/jax/rs/helpers/RequestProfileManager.java // public class RequestProfileManager { // // private final RequestJaxRsContext context; // // public RequestProfileManager(RequestJaxRsContext context) { // this.context = context; // } // // public JaxRsProfileManager profileManager() { // return new JaxRsProfileManager(context.contextOrNew()); // } // } // Path: jersey/src/main/java/org/pac4j/jax/rs/jersey/features/Pac4JValueFactoryProvider.java import org.glassfish.jersey.internal.inject.AbstractBinder; import org.glassfish.jersey.internal.inject.InjectionResolver; import org.glassfish.jersey.internal.util.ReflectionHelper; import org.glassfish.jersey.internal.util.collection.ClassTypePair; import org.glassfish.jersey.server.ContainerRequest; import org.glassfish.jersey.server.internal.inject.AbstractValueParamProvider; import org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider; import org.glassfish.jersey.server.internal.inject.ParamInjectionResolver; import org.glassfish.jersey.server.model.Parameter; import org.glassfish.jersey.server.spi.internal.ValueParamProvider; import org.pac4j.core.profile.CommonProfile; import org.pac4j.core.profile.ProfileManager; import org.pac4j.core.profile.UserProfile; import org.pac4j.jax.rs.annotations.Pac4JProfile; import org.pac4j.jax.rs.annotations.Pac4JProfileManager; import org.pac4j.jax.rs.helpers.RequestUserProfile; import org.pac4j.jax.rs.helpers.RequestJaxRsContext; import org.pac4j.jax.rs.helpers.RequestPac4JSecurityContext; import org.pac4j.jax.rs.helpers.RequestProfileManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericType; import javax.ws.rs.ext.Providers; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; if(manager == null){ bind(DefaultProfileManagerFactoryBuilder.class) .to(ProfileManagerFactoryBuilder.class).in(Singleton.class); } else { bind(manager).to(ProfileManagerFactoryBuilder.class); } bindAsContract(Pac4JProfileValueFactoryProvider.class).to(ValueParamProvider.class).in(Singleton.class); bindAsContract(ProfileInjectionResolver.class) .to(new GenericType<InjectionResolver<Pac4JProfile>>(){}) .in(Singleton.class); bindAsContract(ProfileManagerInjectionResolver.class) .to(new GenericType<InjectionResolver<Pac4JProfileManager>>(){}) .in(Singleton.class); } } static class ProfileManagerValueFactory implements ProfileManagerFactory{ @Context private final Providers providers; ProfileManagerValueFactory(Providers providers) { this.providers = providers; } @Override public ProfileManager<CommonProfile> apply(ContainerRequest containerRequest) {
return new RequestProfileManager(new RequestJaxRsContext(providers, containerRequest))