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
salk31/RedQueryBuilder
redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/ConditionAndOr.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // }
import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Widget; import com.redspr.redquerybuilder.core.client.BaseSqlWidget; import com.redspr.redquerybuilder.core.client.Visitor; import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.util.XWidget;
package com.redspr.redquerybuilder.core.client.expression; /** * An 'and' or 'or' condition as in WHERE ID=1 AND NAME=? */ public class ConditionAndOr extends Condition { interface MyUiBinder extends UiBinder<Widget, ConditionAndOr> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField XWidget<Expression> left; @UiField XWidget<Expression> right; @UiField ListBox op; /** * The AND condition type as in ID=1 AND NAME='Hello'. */ public static final int AND = 0; /** * The OR condition type as in ID=1 OR NAME='Hello'. */ public static final int OR = 1; private int andOrType;
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // } // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/ConditionAndOr.java import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Widget; import com.redspr.redquerybuilder.core.client.BaseSqlWidget; import com.redspr.redquerybuilder.core.client.Visitor; import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.util.XWidget; package com.redspr.redquerybuilder.core.client.expression; /** * An 'and' or 'or' condition as in WHERE ID=1 AND NAME=? */ public class ConditionAndOr extends Condition { interface MyUiBinder extends UiBinder<Widget, ConditionAndOr> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); @UiField XWidget<Expression> left; @UiField XWidget<Expression> right; @UiField ListBox op; /** * The AND condition type as in ID=1 AND NAME='Hello'. */ public static final int AND = 0; /** * The OR condition type as in ID=1 OR NAME='Hello'. */ public static final int OR = 1; private int andOrType;
public ConditionAndOr(Session session, int andOrType2, Expression left2, Expression right2) {
salk31/RedQueryBuilder
redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // } // // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java // public class Expression extends BaseSqlWidget { // // public Expression(Session session) { // super(session); // // initWidget(new Label("E" + getClass().getName())); // } // // public String getSQL(List<Object> args) { // return "blah"; // } // // }
import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.expression.Expression; import com.redspr.redquerybuilder.core.client.util.ObjectArray;
/* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group * * Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888 * Support for the operator "&&" as an alias for SPATIAL_INTERSECTS */ package com.redspr.redquerybuilder.core.client.command.dml; /** * Represents a union SELECT statement. */ public class SelectUnion extends Query { /** * The type of a UNION statement. */ public static final int UNION = 0; /** * The type of a UNION ALL statement. */ public static final int UNION_ALL = 1; /** * The type of an EXCEPT statement. */ public static final int EXCEPT = 2; /** * The type of an INTERSECT statement. */ public static final int INTERSECT = 3; private int unionType; private final Query left; private Query right;
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // } // // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java // public class Expression extends BaseSqlWidget { // // public Expression(Session session) { // super(session); // // initWidget(new Label("E" + getClass().getName())); // } // // public String getSQL(List<Object> args) { // return "blah"; // } // // } // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.expression.Expression; import com.redspr.redquerybuilder.core.client.util.ObjectArray; /* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group * * Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888 * Support for the operator "&&" as an alias for SPATIAL_INTERSECTS */ package com.redspr.redquerybuilder.core.client.command.dml; /** * Represents a union SELECT statement. */ public class SelectUnion extends Query { /** * The type of a UNION statement. */ public static final int UNION = 0; /** * The type of a UNION ALL statement. */ public static final int UNION_ALL = 1; /** * The type of an EXCEPT statement. */ public static final int EXCEPT = 2; /** * The type of an INTERSECT statement. */ public static final int INTERSECT = 3; private int unionType; private final Query left; private Query right;
private ObjectArray<Expression> expressions;
salk31/RedQueryBuilder
redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // } // // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java // public class Expression extends BaseSqlWidget { // // public Expression(Session session) { // super(session); // // initWidget(new Label("E" + getClass().getName())); // } // // public String getSQL(List<Object> args) { // return "blah"; // } // // }
import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.expression.Expression; import com.redspr.redquerybuilder.core.client.util.ObjectArray;
/* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group * * Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888 * Support for the operator "&&" as an alias for SPATIAL_INTERSECTS */ package com.redspr.redquerybuilder.core.client.command.dml; /** * Represents a union SELECT statement. */ public class SelectUnion extends Query { /** * The type of a UNION statement. */ public static final int UNION = 0; /** * The type of a UNION ALL statement. */ public static final int UNION_ALL = 1; /** * The type of an EXCEPT statement. */ public static final int EXCEPT = 2; /** * The type of an INTERSECT statement. */ public static final int INTERSECT = 3; private int unionType; private final Query left; private Query right; private ObjectArray<Expression> expressions; // private ObjectArray<SelectOrderBy> orderList; // SortOrder sort; private boolean distinct; private boolean isPrepared, checkInit; private boolean isForUpdate;
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // } // // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java // public class Expression extends BaseSqlWidget { // // public Expression(Session session) { // super(session); // // initWidget(new Label("E" + getClass().getName())); // } // // public String getSQL(List<Object> args) { // return "blah"; // } // // } // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java import com.redspr.redquerybuilder.core.client.engine.Session; import com.redspr.redquerybuilder.core.client.expression.Expression; import com.redspr.redquerybuilder.core.client.util.ObjectArray; /* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group * * Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888 * Support for the operator "&&" as an alias for SPATIAL_INTERSECTS */ package com.redspr.redquerybuilder.core.client.command.dml; /** * Represents a union SELECT statement. */ public class SelectUnion extends Query { /** * The type of a UNION statement. */ public static final int UNION = 0; /** * The type of a UNION ALL statement. */ public static final int UNION_ALL = 1; /** * The type of an EXCEPT statement. */ public static final int EXCEPT = 2; /** * The type of an INTERSECT statement. */ public static final int INTERSECT = 3; private int unionType; private final Query left; private Query right; private ObjectArray<Expression> expressions; // private ObjectArray<SelectOrderBy> orderList; // SortOrder sort; private boolean distinct; private boolean isPrepared, checkInit; private boolean isForUpdate;
public SelectUnion(Session session, Query query) {
salk31/RedQueryBuilder
redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/CapturingConfiguration.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/Configuration.java // public class Configuration { // private Database database = new Database(); // // private final From from = new From(); // // public void fireEnumerate(EnumerateRequest request, AsyncCallback<Response> callback) { // } // // // XXX not called by CommandBuilder. GWT users meant to use RedQueryBuilder? // public void fireOnSqlChange(String sql, List<Object> args) { // } // // public void fireOnTableChange(ObjectArray<TableFilter> filters) { // } // // public void fireDefaultSuggest(SuggestRequest request, AsyncCallback<Response> callback) { // } // // public void fireSuggest(SuggestRequest request, AsyncCallback<Response> callback) { // } // // public Database getDatabase() { // return database; // } // // public void setDatabase(Database p) { // this.database = p; // } // // public From getFrom() { // return from; // } // } // // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/EnumerateRequest.java // public class EnumerateRequest { // private String tableName; // // private String columnName; // // private String columnType; // // public String getTableName() { // return tableName; // } // // public void setTableName(String p) { // this.tableName = p; // } // // public String getColumnName() { // return columnName; // } // // public void setColumnName(String p) { // this.columnName = p; // } // // public String getColumnTypeName() { // return columnType; // } // // public void setColumnTypeName(String p) { // this.columnType = p; // } // // }
import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.SuggestOracle.Response; import com.redspr.redquerybuilder.core.client.Configuration; import com.redspr.redquerybuilder.core.shared.meta.EnumerateRequest;
package com.redspr.redquerybuilder.core.client; public class CapturingConfiguration extends Configuration { private AsyncCallback<Response> enumerateCallback; public AsyncCallback<Response> getEnumerateCallback() { return enumerateCallback; } @Override
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/Configuration.java // public class Configuration { // private Database database = new Database(); // // private final From from = new From(); // // public void fireEnumerate(EnumerateRequest request, AsyncCallback<Response> callback) { // } // // // XXX not called by CommandBuilder. GWT users meant to use RedQueryBuilder? // public void fireOnSqlChange(String sql, List<Object> args) { // } // // public void fireOnTableChange(ObjectArray<TableFilter> filters) { // } // // public void fireDefaultSuggest(SuggestRequest request, AsyncCallback<Response> callback) { // } // // public void fireSuggest(SuggestRequest request, AsyncCallback<Response> callback) { // } // // public Database getDatabase() { // return database; // } // // public void setDatabase(Database p) { // this.database = p; // } // // public From getFrom() { // return from; // } // } // // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/EnumerateRequest.java // public class EnumerateRequest { // private String tableName; // // private String columnName; // // private String columnType; // // public String getTableName() { // return tableName; // } // // public void setTableName(String p) { // this.tableName = p; // } // // public String getColumnName() { // return columnName; // } // // public void setColumnName(String p) { // this.columnName = p; // } // // public String getColumnTypeName() { // return columnType; // } // // public void setColumnTypeName(String p) { // this.columnType = p; // } // // } // Path: redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/CapturingConfiguration.java import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.SuggestOracle.Response; import com.redspr.redquerybuilder.core.client.Configuration; import com.redspr.redquerybuilder.core.shared.meta.EnumerateRequest; package com.redspr.redquerybuilder.core.client; public class CapturingConfiguration extends Configuration { private AsyncCallback<Response> enumerateCallback; public AsyncCallback<Response> getEnumerateCallback() { return enumerateCallback; } @Override
public void fireEnumerate(EnumerateRequest request, AsyncCallback<Response> callback) {
salk31/RedQueryBuilder
redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/DbObjectBase.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // }
import com.redspr.redquerybuilder.core.client.engine.Session;
package com.redspr.redquerybuilder.core.shared.meta; /** * The base class for all database objects. */ public abstract class DbObjectBase implements DbObject, HasLabel { private String objectName; private String label; protected void setObjectName(String name) { objectName = name; } public void setLabel(String p) { this.label = p; } @Override public String getSQL() {
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java // public class Session { // // private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() { // @Override // public String quote(String id) { // return "\"" + id + "\""; // } // }; // // public void setIdentifierEscaper(IdentifierEscaper p) { // identifierEscaper = p; // } // // /** // * Add double quotes around an identifier if required. // * // * @param s the identifier // * @return the quoted identifier // */ // public static String quoteIdentifier(String s) { // return identifierEscaper.quote(s); // } // // // XXX need commandBuilder and select? // private CommandBuilder commandBuilder; // // private Select select; // // private Configuration config; // // private final ValueRegistry valueRegistry = new ValueRegistry(); // // private final Database database; // // private final HandlerManager msgbus; // // // // XXX 00 remove one of these constructors // public Session(Configuration config2) { // this(config2.getDatabase()); // this.config = config2; // } // // @Deprecated // public Session(Database database2) { // database = database2; // msgbus = new HandlerManager(this); // } // // public Configuration getConfig() { // return config; // } // // public CommandBuilder getCommandBuilder() { // return commandBuilder; // } // // public void setCommandBuilder(CommandBuilder p) { // commandBuilder = p; // } // // public Database getDatabase() { // return database; // } // // // public HandlerManager getMsgBus() { // return msgbus; // } // // // // public void setSelect(Select p) { // select = p; // } // // public Column resolveColumn(String alias, String columnName) { // return select.resolveColumn(alias, columnName); // } // // public ObjectArray<TableFilter> getFilters() { // return select.getFilters(); // } // // public TableFilter getTableFilter(Table t) { // for (TableFilter tf : select.getFilters()) { // if (tf.getTable().equals(t)) { // return tf; // } // } // return null; // } // // public TableFilter createTableFilter(Table t) { // TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select); // select.addTableFilter(tf, true); // XXX really is true? // return tf; // } // // public TableFilter getOrCreateTableFilter(Table t) { // TableFilter tf = getTableFilter(t); // if (tf == null) { // tf = createTableFilter(t); // } // return tf; // } // // //public Table getTable(String alias) { // // return select.getTable(alias); // //} // // public Table getRootTable() { // // XXX maybe if no table then grab default? // // or should select always have one table? // // or ui shouldn't offer condition button till table? // return select.getFilters().get(0).getTable(); // } // // public ValueRegistry getValueRegistry() { // return valueRegistry; // } // } // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/DbObjectBase.java import com.redspr.redquerybuilder.core.client.engine.Session; package com.redspr.redquerybuilder.core.shared.meta; /** * The base class for all database objects. */ public abstract class DbObjectBase implements DbObject, HasLabel { private String objectName; private String label; protected void setObjectName(String name) { objectName = name; } public void setLabel(String p) { this.label = p; } @Override public String getSQL() {
return Session.quoteIdentifier(objectName);
salk31/RedQueryBuilder
redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/JsVisitor.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/VisitorContext.java // @JsType // public interface VisitorContext<T> { // interface NodeType { // String PARAMETER = "PARAMETER"; // String COLUMN = "COLUMN"; // String COMPARISON = "COMPARISON"; // String LOGIC = "LOGIC"; // XXX not sure about this // String SELECT = "SELECT"; // }; // // String getNodeType(); // TODO __ enum and JS? // String getNodeName(); // // HasMessages asHasMessages(); // // HasValue<T> asHasValue(); // }
import com.google.gwt.core.client.js.JsExport; import com.redspr.redquerybuilder.core.client.BaseSqlWidget; import com.redspr.redquerybuilder.core.client.Visitor; import com.redspr.redquerybuilder.core.client.VisitorContext;
package com.redspr.redquerybuilder.js.client; // XXX move into core as DefaultVisitor? //@JsNamespace("$wnd.rqb") @com.google.gwt.core.client.js.JsType public class JsVisitor implements Visitor { @JsExport("$wnd.rqb.Visitor") public JsVisitor() { } @Override public void handle(BaseSqlWidget w) { } @Override
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/VisitorContext.java // @JsType // public interface VisitorContext<T> { // interface NodeType { // String PARAMETER = "PARAMETER"; // String COLUMN = "COLUMN"; // String COMPARISON = "COMPARISON"; // String LOGIC = "LOGIC"; // XXX not sure about this // String SELECT = "SELECT"; // }; // // String getNodeType(); // TODO __ enum and JS? // String getNodeName(); // // HasMessages asHasMessages(); // // HasValue<T> asHasValue(); // } // Path: redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/JsVisitor.java import com.google.gwt.core.client.js.JsExport; import com.redspr.redquerybuilder.core.client.BaseSqlWidget; import com.redspr.redquerybuilder.core.client.Visitor; import com.redspr.redquerybuilder.core.client.VisitorContext; package com.redspr.redquerybuilder.js.client; // XXX move into core as DefaultVisitor? //@JsNamespace("$wnd.rqb") @com.google.gwt.core.client.js.JsType public class JsVisitor implements Visitor { @JsExport("$wnd.rqb.Visitor") public JsVisitor() { } @Override public void handle(BaseSqlWidget w) { } @Override
public void visit(VisitorContext<?> context) {
salk31/RedQueryBuilder
redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestTextEditor.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java // public class Editor implements HasStyleName, Serializable, IsSerializable { // public static class TextEditor extends Editor { // @Override // public Object getDefault() { // return ""; // } // } // // public static class DateEditor extends Editor { // public static final String FORMAT = "format"; // } // // public static class BooleanEditor extends Editor { // @Override // public Object getDefault() { // return Boolean.FALSE; // } // } // // public static class SelectEditor extends Editor { // // } // // public static class NumberEditor extends Editor { // } // // // // XXX - rubbish, only used by JSON? // private static final Map<String, Editor> editorByName = new HashMap<String, Editor>(); // // private static Editor valueOf2(String name) { // if ("STRING".equals(name) || "TEXT".equals(name)) { // return new TextEditor(); // } else if ("DATE".equals(name)) { // return new DateEditor(); // } else if ("SUGGEST".equals(name)) { // return new SuggestEditor(); // } else if ("SELECT".equals(name)) { // return new SelectEditor(); // } else if ("NUMBER".equals(name)) { // return new NumberEditor(); // } else { // throw new RuntimeException("No editor for " + name); // } // } // // public static Editor valueOf(String name) { // Editor e = editorByName.get(name); // if (e == null) { // e = valueOf2(name); // editorByName.put(name, e); // } // return e; // } // // // XXX map mush // private final Map<String, Object> attributes = new HashMap<String, Object>(); // // private String styleName; // // public Object getDefault() { // return null; // } // // public void setAttribute(String name, Object value) { // attributes.put(name, value); // } // // public Object getAttribute(String name) { // return attributes.get(name); // } // // public String getStyleName() { // return styleName; // } // // @Override // public void setStyleName(String p) { // this.styleName = p; // } // }
import com.redspr.redquerybuilder.core.shared.meta.Editor;
package com.redspr.redquerybuilder.core.client.expression; public class GwtTestTextEditor extends AbstractEditorTest<String> { @Override
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java // public class Editor implements HasStyleName, Serializable, IsSerializable { // public static class TextEditor extends Editor { // @Override // public Object getDefault() { // return ""; // } // } // // public static class DateEditor extends Editor { // public static final String FORMAT = "format"; // } // // public static class BooleanEditor extends Editor { // @Override // public Object getDefault() { // return Boolean.FALSE; // } // } // // public static class SelectEditor extends Editor { // // } // // public static class NumberEditor extends Editor { // } // // // // XXX - rubbish, only used by JSON? // private static final Map<String, Editor> editorByName = new HashMap<String, Editor>(); // // private static Editor valueOf2(String name) { // if ("STRING".equals(name) || "TEXT".equals(name)) { // return new TextEditor(); // } else if ("DATE".equals(name)) { // return new DateEditor(); // } else if ("SUGGEST".equals(name)) { // return new SuggestEditor(); // } else if ("SELECT".equals(name)) { // return new SelectEditor(); // } else if ("NUMBER".equals(name)) { // return new NumberEditor(); // } else { // throw new RuntimeException("No editor for " + name); // } // } // // public static Editor valueOf(String name) { // Editor e = editorByName.get(name); // if (e == null) { // e = valueOf2(name); // editorByName.put(name, e); // } // return e; // } // // // XXX map mush // private final Map<String, Object> attributes = new HashMap<String, Object>(); // // private String styleName; // // public Object getDefault() { // return null; // } // // public void setAttribute(String name, Object value) { // attributes.put(name, value); // } // // public Object getAttribute(String name) { // return attributes.get(name); // } // // public String getStyleName() { // return styleName; // } // // @Override // public void setStyleName(String p) { // this.styleName = p; // } // } // Path: redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestTextEditor.java import com.redspr.redquerybuilder.core.shared.meta.Editor; package com.redspr.redquerybuilder.core.client.expression; public class GwtTestTextEditor extends AbstractEditorTest<String> { @Override
protected Editor getEditor() {
salk31/RedQueryBuilder
redquerybuilder-jdbcsample/src/main/java/com/redspr/redquerybuilder/sample/MetaServlet.java
// Path: redquerybuilder-core/src/main/java/java/sql/SQLException.java // public class SQLException extends Exception { // public SQLException(String m) { // super(m); // } // // public SQLException(String m, Throwable t) { // super(m, t); // } // // // public int getErrorCode() { // return 0; // } // }
import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
int keySeq = rs2.getInt("KEY_SEQ"); if (keySeq == 1) { fk = new ForeignKey(); String name = rs2.getString("FK_NAME"); fk.name = name; fksx.add(fk); String key = "fk." + name; fk.label = getLocal(key); fk.reverseLabel = getLocal(key + ".reverse"); fk.fkTableName = rs2.getString("FKTABLE_NAME"); } fk.fkColumnNames.add(rs2 .getString("FKCOLUMN_NAME")); fk.pkColumnNames.add(rs2 .getString("PKCOLUMN_NAME")); } for (ForeignKey foo2 : fksx) { fks.put(foo2.toJson()); } } } } res.setContentType("application/json"); root.write(res.getWriter());
// Path: redquerybuilder-core/src/main/java/java/sql/SQLException.java // public class SQLException extends Exception { // public SQLException(String m) { // super(m); // } // // public SQLException(String m, Throwable t) { // super(m, t); // } // // // public int getErrorCode() { // return 0; // } // } // Path: redquerybuilder-jdbcsample/src/main/java/com/redspr/redquerybuilder/sample/MetaServlet.java import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; int keySeq = rs2.getInt("KEY_SEQ"); if (keySeq == 1) { fk = new ForeignKey(); String name = rs2.getString("FK_NAME"); fk.name = name; fksx.add(fk); String key = "fk." + name; fk.label = getLocal(key); fk.reverseLabel = getLocal(key + ".reverse"); fk.fkTableName = rs2.getString("FKTABLE_NAME"); } fk.fkColumnNames.add(rs2 .getString("FKCOLUMN_NAME")); fk.pkColumnNames.add(rs2 .getString("PKCOLUMN_NAME")); } for (ForeignKey foo2 : fksx) { fks.put(foo2.toJson()); } } } } res.setContentType("application/json"); root.write(res.getWriter());
} catch (SQLException ex) {
salk31/RedQueryBuilder
redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestNumberEditor.java
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java // public class Editor implements HasStyleName, Serializable, IsSerializable { // public static class TextEditor extends Editor { // @Override // public Object getDefault() { // return ""; // } // } // // public static class DateEditor extends Editor { // public static final String FORMAT = "format"; // } // // public static class BooleanEditor extends Editor { // @Override // public Object getDefault() { // return Boolean.FALSE; // } // } // // public static class SelectEditor extends Editor { // // } // // public static class NumberEditor extends Editor { // } // // // // XXX - rubbish, only used by JSON? // private static final Map<String, Editor> editorByName = new HashMap<String, Editor>(); // // private static Editor valueOf2(String name) { // if ("STRING".equals(name) || "TEXT".equals(name)) { // return new TextEditor(); // } else if ("DATE".equals(name)) { // return new DateEditor(); // } else if ("SUGGEST".equals(name)) { // return new SuggestEditor(); // } else if ("SELECT".equals(name)) { // return new SelectEditor(); // } else if ("NUMBER".equals(name)) { // return new NumberEditor(); // } else { // throw new RuntimeException("No editor for " + name); // } // } // // public static Editor valueOf(String name) { // Editor e = editorByName.get(name); // if (e == null) { // e = valueOf2(name); // editorByName.put(name, e); // } // return e; // } // // // XXX map mush // private final Map<String, Object> attributes = new HashMap<String, Object>(); // // private String styleName; // // public Object getDefault() { // return null; // } // // public void setAttribute(String name, Object value) { // attributes.put(name, value); // } // // public Object getAttribute(String name) { // return attributes.get(name); // } // // public String getStyleName() { // return styleName; // } // // @Override // public void setStyleName(String p) { // this.styleName = p; // } // }
import com.redspr.redquerybuilder.core.shared.meta.Editor;
package com.redspr.redquerybuilder.core.client.expression; public class GwtTestNumberEditor extends AbstractEditorTest<Double> { @Override
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java // public class Editor implements HasStyleName, Serializable, IsSerializable { // public static class TextEditor extends Editor { // @Override // public Object getDefault() { // return ""; // } // } // // public static class DateEditor extends Editor { // public static final String FORMAT = "format"; // } // // public static class BooleanEditor extends Editor { // @Override // public Object getDefault() { // return Boolean.FALSE; // } // } // // public static class SelectEditor extends Editor { // // } // // public static class NumberEditor extends Editor { // } // // // // XXX - rubbish, only used by JSON? // private static final Map<String, Editor> editorByName = new HashMap<String, Editor>(); // // private static Editor valueOf2(String name) { // if ("STRING".equals(name) || "TEXT".equals(name)) { // return new TextEditor(); // } else if ("DATE".equals(name)) { // return new DateEditor(); // } else if ("SUGGEST".equals(name)) { // return new SuggestEditor(); // } else if ("SELECT".equals(name)) { // return new SelectEditor(); // } else if ("NUMBER".equals(name)) { // return new NumberEditor(); // } else { // throw new RuntimeException("No editor for " + name); // } // } // // public static Editor valueOf(String name) { // Editor e = editorByName.get(name); // if (e == null) { // e = valueOf2(name); // editorByName.put(name, e); // } // return e; // } // // // XXX map mush // private final Map<String, Object> attributes = new HashMap<String, Object>(); // // private String styleName; // // public Object getDefault() { // return null; // } // // public void setAttribute(String name, Object value) { // attributes.put(name, value); // } // // public Object getAttribute(String name) { // return attributes.get(name); // } // // public String getStyleName() { // return styleName; // } // // @Override // public void setStyleName(String p) { // this.styleName = p; // } // } // Path: redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestNumberEditor.java import com.redspr.redquerybuilder.core.shared.meta.Editor; package com.redspr.redquerybuilder.core.client.expression; public class GwtTestNumberEditor extends AbstractEditorTest<Double> { @Override
protected Editor getEditor() {
bart-kneepkens/OpenHeosControl
src/main/java/Connection/ChangeListenerRunnable.java
// Path: src/main/java/Constants/Events.java // public class Events { // public static final String PLAYER_VOLUME_CHANGED = "event/player_volume_changed"; // public static final String PLAYER_STATE_CHANGED = "event/player_state_changed"; // public static final String PLAYER_NOW_PLAYING_CHANGED = "event/player_now_playing_changed"; // public static final String PLAYER_NOW_PLAYING_PROGRESS = "event/player_now_playing_progress"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // }
import Constants.Events; import Constants.PlayStates; import Constants.Results; import com.google.gson.Gson; import java.util.Map; import java.util.Scanner;
/* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * * @author bartkneepkens */ public class ChangeListenerRunnable implements Runnable { Scanner in; Gson gson; IChangeListener listener; @Override public void run() { while (true) { Response read = gson.fromJson(in.next(), Response.class); switch (read.getCommand()) {
// Path: src/main/java/Constants/Events.java // public class Events { // public static final String PLAYER_VOLUME_CHANGED = "event/player_volume_changed"; // public static final String PLAYER_STATE_CHANGED = "event/player_state_changed"; // public static final String PLAYER_NOW_PLAYING_CHANGED = "event/player_now_playing_changed"; // public static final String PLAYER_NOW_PLAYING_PROGRESS = "event/player_now_playing_progress"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // Path: src/main/java/Connection/ChangeListenerRunnable.java import Constants.Events; import Constants.PlayStates; import Constants.Results; import com.google.gson.Gson; import java.util.Map; import java.util.Scanner; /* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * * @author bartkneepkens */ public class ChangeListenerRunnable implements Runnable { Scanner in; Gson gson; IChangeListener listener; @Override public void run() { while (true) { Response read = gson.fromJson(in.next(), Response.class); switch (read.getCommand()) {
case Events.PLAYER_STATE_CHANGED:
bart-kneepkens/OpenHeosControl
src/main/java/Connection/ChangeListenerRunnable.java
// Path: src/main/java/Constants/Events.java // public class Events { // public static final String PLAYER_VOLUME_CHANGED = "event/player_volume_changed"; // public static final String PLAYER_STATE_CHANGED = "event/player_state_changed"; // public static final String PLAYER_NOW_PLAYING_CHANGED = "event/player_now_playing_changed"; // public static final String PLAYER_NOW_PLAYING_PROGRESS = "event/player_now_playing_progress"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // }
import Constants.Events; import Constants.PlayStates; import Constants.Results; import com.google.gson.Gson; import java.util.Map; import java.util.Scanner;
/* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * * @author bartkneepkens */ public class ChangeListenerRunnable implements Runnable { Scanner in; Gson gson; IChangeListener listener; @Override public void run() { while (true) { Response read = gson.fromJson(in.next(), Response.class); switch (read.getCommand()) { case Events.PLAYER_STATE_CHANGED: if (read.getMessage().contains("state=")) { String state = read.getMessage().substring(read.getMessage().indexOf("state=") + 6); String pid = read.getMessage().substring(read.getMessage().indexOf("pid=") + 4, read.getMessage().indexOf("state=")); listener.playerStateChanged(pid, state); } case Events.PLAYER_VOLUME_CHANGED: if (read.getMessage().contains("level=")) { int level = Integer.parseInt(read.getMessage().substring(read.getMessage().indexOf("level=") + 6, read.getMessage().indexOf("&mute="))); String pid = read.getMessage().substring(read.getMessage().indexOf("pid=") + 4, read.getMessage().indexOf("level=")); listener.playerVolumeChanged(pid, level); } case Events.PLAYER_NOW_PLAYING_CHANGED: if (read.getMessage().contains("state")) { String pid = read.getMessage().substring(read.getMessage().indexOf("pid=") + 4); // Event does not hold any info about the song. Response r = TelnetConnection.write(PlayerCommands.PlayerCommands.GET_NOW_PLAYING_MEDIA(pid)); // Code repetition, fix this.
// Path: src/main/java/Constants/Events.java // public class Events { // public static final String PLAYER_VOLUME_CHANGED = "event/player_volume_changed"; // public static final String PLAYER_STATE_CHANGED = "event/player_state_changed"; // public static final String PLAYER_NOW_PLAYING_CHANGED = "event/player_now_playing_changed"; // public static final String PLAYER_NOW_PLAYING_PROGRESS = "event/player_now_playing_progress"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // Path: src/main/java/Connection/ChangeListenerRunnable.java import Constants.Events; import Constants.PlayStates; import Constants.Results; import com.google.gson.Gson; import java.util.Map; import java.util.Scanner; /* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * * @author bartkneepkens */ public class ChangeListenerRunnable implements Runnable { Scanner in; Gson gson; IChangeListener listener; @Override public void run() { while (true) { Response read = gson.fromJson(in.next(), Response.class); switch (read.getCommand()) { case Events.PLAYER_STATE_CHANGED: if (read.getMessage().contains("state=")) { String state = read.getMessage().substring(read.getMessage().indexOf("state=") + 6); String pid = read.getMessage().substring(read.getMessage().indexOf("pid=") + 4, read.getMessage().indexOf("state=")); listener.playerStateChanged(pid, state); } case Events.PLAYER_VOLUME_CHANGED: if (read.getMessage().contains("level=")) { int level = Integer.parseInt(read.getMessage().substring(read.getMessage().indexOf("level=") + 6, read.getMessage().indexOf("&mute="))); String pid = read.getMessage().substring(read.getMessage().indexOf("pid=") + 4, read.getMessage().indexOf("level=")); listener.playerVolumeChanged(pid, level); } case Events.PLAYER_NOW_PLAYING_CHANGED: if (read.getMessage().contains("state")) { String pid = read.getMessage().substring(read.getMessage().indexOf("pid=") + 4); // Event does not hold any info about the song. Response r = TelnetConnection.write(PlayerCommands.PlayerCommands.GET_NOW_PLAYING_MEDIA(pid)); // Code repetition, fix this.
if (r.getResult().equals(Results.SUCCESS)) {
bart-kneepkens/OpenHeosControl
src/main/java/PlayerCommands/Player.java
// Path: src/main/java/Connection/TelnetConnection.java // public class TelnetConnection { // // /* Networking */ // private static Socket socket; // private static PrintWriter out; // private static Scanner in; // // private static Gson gson; // // /** // * Connect to a Heos System that is located at a certain ip. // * @param ipAddress a valid IP address. // */ // public static void connect(final String ipAddress) { // try { // socket = new Socket(ipAddress, 1255); // out = new PrintWriter(socket.getOutputStream(), true); // in = new Scanner(socket.getInputStream()); // in.useDelimiter("\r\n"); // gson = new GsonBuilder().create(); // } catch (IOException ex) { // Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * Write a certain command to the Heos System. // * @param command a String describing the command (see Constants package) // * @return a Response // */ // public static Response write(final String command) { // if (socket == null || out == null || in == null || gson == null) { // return null; // } // // new Thread(new Runnable() { // @Override // public void run() { // out.println(command); // out.flush(); // } // }).start(); // // return gson.fromJson(in.next(), Response.class); // } // // } // // Path: src/main/java/Connection/Response.java // public class Response { // // private Map<String, String> heos; // // /** // * Can be either null, a Map or an array of maps. // */ // private Object payload; // // public String getCommand() { // return heos.get("command"); // } // // public String getResult() { // return heos.get("result"); // } // // public String getMessage() { // return heos.get("message"); // } // // public Object getPayload(){ // return payload; // } // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // }
import Connection.TelnetConnection; import Connection.Response; import Constants.Results; import java.util.Map;
this.model = ""; this.version = ""; this.gid = 0.0; } public String getName(){ return name; } public String getPid() { return pid; } public String getModel() { return model; } public String getVersion() { return version; } public Double getGid() { return gid; } /** * Get this player's current state. * @return a String that is either "start", "stop", or "pause". */ public String getPlayState(){
// Path: src/main/java/Connection/TelnetConnection.java // public class TelnetConnection { // // /* Networking */ // private static Socket socket; // private static PrintWriter out; // private static Scanner in; // // private static Gson gson; // // /** // * Connect to a Heos System that is located at a certain ip. // * @param ipAddress a valid IP address. // */ // public static void connect(final String ipAddress) { // try { // socket = new Socket(ipAddress, 1255); // out = new PrintWriter(socket.getOutputStream(), true); // in = new Scanner(socket.getInputStream()); // in.useDelimiter("\r\n"); // gson = new GsonBuilder().create(); // } catch (IOException ex) { // Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * Write a certain command to the Heos System. // * @param command a String describing the command (see Constants package) // * @return a Response // */ // public static Response write(final String command) { // if (socket == null || out == null || in == null || gson == null) { // return null; // } // // new Thread(new Runnable() { // @Override // public void run() { // out.println(command); // out.flush(); // } // }).start(); // // return gson.fromJson(in.next(), Response.class); // } // // } // // Path: src/main/java/Connection/Response.java // public class Response { // // private Map<String, String> heos; // // /** // * Can be either null, a Map or an array of maps. // */ // private Object payload; // // public String getCommand() { // return heos.get("command"); // } // // public String getResult() { // return heos.get("result"); // } // // public String getMessage() { // return heos.get("message"); // } // // public Object getPayload(){ // return payload; // } // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // Path: src/main/java/PlayerCommands/Player.java import Connection.TelnetConnection; import Connection.Response; import Constants.Results; import java.util.Map; this.model = ""; this.version = ""; this.gid = 0.0; } public String getName(){ return name; } public String getPid() { return pid; } public String getModel() { return model; } public String getVersion() { return version; } public Double getGid() { return gid; } /** * Get this player's current state. * @return a String that is either "start", "stop", or "pause". */ public String getPlayState(){
Response response = TelnetConnection.write(PlayerCommands.GET_PLAY_STATE(this.pid));
bart-kneepkens/OpenHeosControl
src/main/java/PlayerCommands/Player.java
// Path: src/main/java/Connection/TelnetConnection.java // public class TelnetConnection { // // /* Networking */ // private static Socket socket; // private static PrintWriter out; // private static Scanner in; // // private static Gson gson; // // /** // * Connect to a Heos System that is located at a certain ip. // * @param ipAddress a valid IP address. // */ // public static void connect(final String ipAddress) { // try { // socket = new Socket(ipAddress, 1255); // out = new PrintWriter(socket.getOutputStream(), true); // in = new Scanner(socket.getInputStream()); // in.useDelimiter("\r\n"); // gson = new GsonBuilder().create(); // } catch (IOException ex) { // Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * Write a certain command to the Heos System. // * @param command a String describing the command (see Constants package) // * @return a Response // */ // public static Response write(final String command) { // if (socket == null || out == null || in == null || gson == null) { // return null; // } // // new Thread(new Runnable() { // @Override // public void run() { // out.println(command); // out.flush(); // } // }).start(); // // return gson.fromJson(in.next(), Response.class); // } // // } // // Path: src/main/java/Connection/Response.java // public class Response { // // private Map<String, String> heos; // // /** // * Can be either null, a Map or an array of maps. // */ // private Object payload; // // public String getCommand() { // return heos.get("command"); // } // // public String getResult() { // return heos.get("result"); // } // // public String getMessage() { // return heos.get("message"); // } // // public Object getPayload(){ // return payload; // } // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // }
import Connection.TelnetConnection; import Connection.Response; import Constants.Results; import java.util.Map;
this.model = ""; this.version = ""; this.gid = 0.0; } public String getName(){ return name; } public String getPid() { return pid; } public String getModel() { return model; } public String getVersion() { return version; } public Double getGid() { return gid; } /** * Get this player's current state. * @return a String that is either "start", "stop", or "pause". */ public String getPlayState(){
// Path: src/main/java/Connection/TelnetConnection.java // public class TelnetConnection { // // /* Networking */ // private static Socket socket; // private static PrintWriter out; // private static Scanner in; // // private static Gson gson; // // /** // * Connect to a Heos System that is located at a certain ip. // * @param ipAddress a valid IP address. // */ // public static void connect(final String ipAddress) { // try { // socket = new Socket(ipAddress, 1255); // out = new PrintWriter(socket.getOutputStream(), true); // in = new Scanner(socket.getInputStream()); // in.useDelimiter("\r\n"); // gson = new GsonBuilder().create(); // } catch (IOException ex) { // Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * Write a certain command to the Heos System. // * @param command a String describing the command (see Constants package) // * @return a Response // */ // public static Response write(final String command) { // if (socket == null || out == null || in == null || gson == null) { // return null; // } // // new Thread(new Runnable() { // @Override // public void run() { // out.println(command); // out.flush(); // } // }).start(); // // return gson.fromJson(in.next(), Response.class); // } // // } // // Path: src/main/java/Connection/Response.java // public class Response { // // private Map<String, String> heos; // // /** // * Can be either null, a Map or an array of maps. // */ // private Object payload; // // public String getCommand() { // return heos.get("command"); // } // // public String getResult() { // return heos.get("result"); // } // // public String getMessage() { // return heos.get("message"); // } // // public Object getPayload(){ // return payload; // } // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // Path: src/main/java/PlayerCommands/Player.java import Connection.TelnetConnection; import Connection.Response; import Constants.Results; import java.util.Map; this.model = ""; this.version = ""; this.gid = 0.0; } public String getName(){ return name; } public String getPid() { return pid; } public String getModel() { return model; } public String getVersion() { return version; } public Double getGid() { return gid; } /** * Get this player's current state. * @return a String that is either "start", "stop", or "pause". */ public String getPlayState(){
Response response = TelnetConnection.write(PlayerCommands.GET_PLAY_STATE(this.pid));
bart-kneepkens/OpenHeosControl
src/main/java/PlayerCommands/Player.java
// Path: src/main/java/Connection/TelnetConnection.java // public class TelnetConnection { // // /* Networking */ // private static Socket socket; // private static PrintWriter out; // private static Scanner in; // // private static Gson gson; // // /** // * Connect to a Heos System that is located at a certain ip. // * @param ipAddress a valid IP address. // */ // public static void connect(final String ipAddress) { // try { // socket = new Socket(ipAddress, 1255); // out = new PrintWriter(socket.getOutputStream(), true); // in = new Scanner(socket.getInputStream()); // in.useDelimiter("\r\n"); // gson = new GsonBuilder().create(); // } catch (IOException ex) { // Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * Write a certain command to the Heos System. // * @param command a String describing the command (see Constants package) // * @return a Response // */ // public static Response write(final String command) { // if (socket == null || out == null || in == null || gson == null) { // return null; // } // // new Thread(new Runnable() { // @Override // public void run() { // out.println(command); // out.flush(); // } // }).start(); // // return gson.fromJson(in.next(), Response.class); // } // // } // // Path: src/main/java/Connection/Response.java // public class Response { // // private Map<String, String> heos; // // /** // * Can be either null, a Map or an array of maps. // */ // private Object payload; // // public String getCommand() { // return heos.get("command"); // } // // public String getResult() { // return heos.get("result"); // } // // public String getMessage() { // return heos.get("message"); // } // // public Object getPayload(){ // return payload; // } // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // }
import Connection.TelnetConnection; import Connection.Response; import Constants.Results; import java.util.Map;
this.gid = 0.0; } public String getName(){ return name; } public String getPid() { return pid; } public String getModel() { return model; } public String getVersion() { return version; } public Double getGid() { return gid; } /** * Get this player's current state. * @return a String that is either "start", "stop", or "pause". */ public String getPlayState(){ Response response = TelnetConnection.write(PlayerCommands.GET_PLAY_STATE(this.pid));
// Path: src/main/java/Connection/TelnetConnection.java // public class TelnetConnection { // // /* Networking */ // private static Socket socket; // private static PrintWriter out; // private static Scanner in; // // private static Gson gson; // // /** // * Connect to a Heos System that is located at a certain ip. // * @param ipAddress a valid IP address. // */ // public static void connect(final String ipAddress) { // try { // socket = new Socket(ipAddress, 1255); // out = new PrintWriter(socket.getOutputStream(), true); // in = new Scanner(socket.getInputStream()); // in.useDelimiter("\r\n"); // gson = new GsonBuilder().create(); // } catch (IOException ex) { // Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * Write a certain command to the Heos System. // * @param command a String describing the command (see Constants package) // * @return a Response // */ // public static Response write(final String command) { // if (socket == null || out == null || in == null || gson == null) { // return null; // } // // new Thread(new Runnable() { // @Override // public void run() { // out.println(command); // out.flush(); // } // }).start(); // // return gson.fromJson(in.next(), Response.class); // } // // } // // Path: src/main/java/Connection/Response.java // public class Response { // // private Map<String, String> heos; // // /** // * Can be either null, a Map or an array of maps. // */ // private Object payload; // // public String getCommand() { // return heos.get("command"); // } // // public String getResult() { // return heos.get("result"); // } // // public String getMessage() { // return heos.get("message"); // } // // public Object getPayload(){ // return payload; // } // } // // Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // Path: src/main/java/PlayerCommands/Player.java import Connection.TelnetConnection; import Connection.Response; import Constants.Results; import java.util.Map; this.gid = 0.0; } public String getName(){ return name; } public String getPid() { return pid; } public String getModel() { return model; } public String getVersion() { return version; } public Double getGid() { return gid; } /** * Get this player's current state. * @return a String that is either "start", "stop", or "pause". */ public String getPlayState(){ Response response = TelnetConnection.write(PlayerCommands.GET_PLAY_STATE(this.pid));
if(response.getResult().equals(Results.SUCCESS)){
bart-kneepkens/OpenHeosControl
src/main/java/Gui/Observers/MediaObserver.java
// Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // }
import SystemCommands.Song; import java.awt.Image; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel;
/* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Gui.Observers; /** * * @author bartkneepkens */ public class MediaObserver implements PropertyChangeListener { private final JLabel imageLabel; private final JLabel songNameLabel; private final JLabel artistNameLabel; private final JLabel albumNameLabel; public MediaObserver(JLabel imageLabel, JLabel songNameLabel, JLabel artistNameLabel, JLabel albumNameLabel) { this.imageLabel = imageLabel; this.songNameLabel = songNameLabel; this.artistNameLabel = artistNameLabel; this.albumNameLabel = albumNameLabel; } @Override public void propertyChange(PropertyChangeEvent evt) {
// Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // } // Path: src/main/java/Gui/Observers/MediaObserver.java import SystemCommands.Song; import java.awt.Image; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; /* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Gui.Observers; /** * * @author bartkneepkens */ public class MediaObserver implements PropertyChangeListener { private final JLabel imageLabel; private final JLabel songNameLabel; private final JLabel artistNameLabel; private final JLabel albumNameLabel; public MediaObserver(JLabel imageLabel, JLabel songNameLabel, JLabel artistNameLabel, JLabel albumNameLabel) { this.imageLabel = imageLabel; this.songNameLabel = songNameLabel; this.artistNameLabel = artistNameLabel; this.albumNameLabel = albumNameLabel; } @Override public void propertyChange(PropertyChangeEvent evt) {
Song newValue = (Song) evt.getNewValue();
bart-kneepkens/OpenHeosControl
src/main/java/Gui/Observers/QueueObserver.java
// Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // }
import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractListModel; import javax.swing.JList;
/* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Gui.Observers; /** * * @author bartkneepkens */ public class QueueObserver implements PropertyChangeListener { private final JList queueList; public QueueObserver(JList queueList) { this.queueList = queueList; } @Override public void propertyChange(PropertyChangeEvent evt) {
// Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // } // Path: src/main/java/Gui/Observers/QueueObserver.java import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractListModel; import javax.swing.JList; /* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Gui.Observers; /** * * @author bartkneepkens */ public class QueueObserver implements PropertyChangeListener { private final JList queueList; public QueueObserver(JList queueList) { this.queueList = queueList; } @Override public void propertyChange(PropertyChangeEvent evt) {
final Song[] newQueue = (Song[]) evt.getNewValue();
bart-kneepkens/OpenHeosControl
src/main/java/Gui/Observers/ControlsObserver.java
// Path: src/main/java/Constants/Assets.java // public class Assets { // public static final String PLAY = "/media-play-6x.png"; // public static final String PAUSE = "/media-pause-6x.png"; // public static final String STOP = "/media-stop-6x.png"; // public static final String PLAY_PRESSED = "/pressed/media-play-6x.png"; // public static final String PAUSE_PRESSED = "/pressed/media-pause-6x.png"; // public static final String STOP_PRESSED = "/pressed/media-stop-6x.png"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // }
import Constants.Assets; import Constants.PlayStates; import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JProgressBar;
private final JButton playPauseStopButton; private final JProgressBar songProgressBar; private final JLabel timePassedLabel; private final JLabel songDurationLabel; public ControlsObserver(JButton playPauseStopButton, JProgressBar songProgressBar, JLabel timePassedLabel, JLabel songDurationLabel) { this.playPauseStopButton = playPauseStopButton; this.songProgressBar = songProgressBar; this.timePassedLabel = timePassedLabel; this.songDurationLabel = songDurationLabel; this.loadAssets(); } @Override public void propertyChange(PropertyChangeEvent evt) { String changedPropertyName = evt.getPropertyName(); switch (changedPropertyName) { case ObservablePropertyNames.PLAYSTATE: String newState = (String) evt.getNewValue(); this.setPlayButtonState(newState); break; case ObservablePropertyNames.SONGPROGRESS: int newProgress = (int) evt.getNewValue(); this.songProgressBar.setValue(newProgress); String formattedProgress = this.formattedTime(newProgress); this.timePassedLabel.setText(formattedProgress); break; case ObservablePropertyNames.NOWPLAYING:
// Path: src/main/java/Constants/Assets.java // public class Assets { // public static final String PLAY = "/media-play-6x.png"; // public static final String PAUSE = "/media-pause-6x.png"; // public static final String STOP = "/media-stop-6x.png"; // public static final String PLAY_PRESSED = "/pressed/media-play-6x.png"; // public static final String PAUSE_PRESSED = "/pressed/media-pause-6x.png"; // public static final String STOP_PRESSED = "/pressed/media-stop-6x.png"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // } // Path: src/main/java/Gui/Observers/ControlsObserver.java import Constants.Assets; import Constants.PlayStates; import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JProgressBar; private final JButton playPauseStopButton; private final JProgressBar songProgressBar; private final JLabel timePassedLabel; private final JLabel songDurationLabel; public ControlsObserver(JButton playPauseStopButton, JProgressBar songProgressBar, JLabel timePassedLabel, JLabel songDurationLabel) { this.playPauseStopButton = playPauseStopButton; this.songProgressBar = songProgressBar; this.timePassedLabel = timePassedLabel; this.songDurationLabel = songDurationLabel; this.loadAssets(); } @Override public void propertyChange(PropertyChangeEvent evt) { String changedPropertyName = evt.getPropertyName(); switch (changedPropertyName) { case ObservablePropertyNames.PLAYSTATE: String newState = (String) evt.getNewValue(); this.setPlayButtonState(newState); break; case ObservablePropertyNames.SONGPROGRESS: int newProgress = (int) evt.getNewValue(); this.songProgressBar.setValue(newProgress); String formattedProgress = this.formattedTime(newProgress); this.timePassedLabel.setText(formattedProgress); break; case ObservablePropertyNames.NOWPLAYING:
int newDuration = ((Song) evt.getNewValue()).getDuration();
bart-kneepkens/OpenHeosControl
src/main/java/Gui/Observers/ControlsObserver.java
// Path: src/main/java/Constants/Assets.java // public class Assets { // public static final String PLAY = "/media-play-6x.png"; // public static final String PAUSE = "/media-pause-6x.png"; // public static final String STOP = "/media-stop-6x.png"; // public static final String PLAY_PRESSED = "/pressed/media-play-6x.png"; // public static final String PAUSE_PRESSED = "/pressed/media-pause-6x.png"; // public static final String STOP_PRESSED = "/pressed/media-stop-6x.png"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // }
import Constants.Assets; import Constants.PlayStates; import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JProgressBar;
this.loadAssets(); } @Override public void propertyChange(PropertyChangeEvent evt) { String changedPropertyName = evt.getPropertyName(); switch (changedPropertyName) { case ObservablePropertyNames.PLAYSTATE: String newState = (String) evt.getNewValue(); this.setPlayButtonState(newState); break; case ObservablePropertyNames.SONGPROGRESS: int newProgress = (int) evt.getNewValue(); this.songProgressBar.setValue(newProgress); String formattedProgress = this.formattedTime(newProgress); this.timePassedLabel.setText(formattedProgress); break; case ObservablePropertyNames.NOWPLAYING: int newDuration = ((Song) evt.getNewValue()).getDuration(); this.songProgressBar.setMaximum(newDuration); String formattedDuration = this.formattedTime(newDuration); this.songDurationLabel.setText(formattedDuration); default: break; } } public void setPlayButtonState(String state) { switch (state) {
// Path: src/main/java/Constants/Assets.java // public class Assets { // public static final String PLAY = "/media-play-6x.png"; // public static final String PAUSE = "/media-pause-6x.png"; // public static final String STOP = "/media-stop-6x.png"; // public static final String PLAY_PRESSED = "/pressed/media-play-6x.png"; // public static final String PAUSE_PRESSED = "/pressed/media-pause-6x.png"; // public static final String STOP_PRESSED = "/pressed/media-stop-6x.png"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // } // Path: src/main/java/Gui/Observers/ControlsObserver.java import Constants.Assets; import Constants.PlayStates; import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JProgressBar; this.loadAssets(); } @Override public void propertyChange(PropertyChangeEvent evt) { String changedPropertyName = evt.getPropertyName(); switch (changedPropertyName) { case ObservablePropertyNames.PLAYSTATE: String newState = (String) evt.getNewValue(); this.setPlayButtonState(newState); break; case ObservablePropertyNames.SONGPROGRESS: int newProgress = (int) evt.getNewValue(); this.songProgressBar.setValue(newProgress); String formattedProgress = this.formattedTime(newProgress); this.timePassedLabel.setText(formattedProgress); break; case ObservablePropertyNames.NOWPLAYING: int newDuration = ((Song) evt.getNewValue()).getDuration(); this.songProgressBar.setMaximum(newDuration); String formattedDuration = this.formattedTime(newDuration); this.songDurationLabel.setText(formattedDuration); default: break; } } public void setPlayButtonState(String state) { switch (state) {
case PlayStates.PLAY:
bart-kneepkens/OpenHeosControl
src/main/java/Gui/Observers/ControlsObserver.java
// Path: src/main/java/Constants/Assets.java // public class Assets { // public static final String PLAY = "/media-play-6x.png"; // public static final String PAUSE = "/media-pause-6x.png"; // public static final String STOP = "/media-stop-6x.png"; // public static final String PLAY_PRESSED = "/pressed/media-play-6x.png"; // public static final String PAUSE_PRESSED = "/pressed/media-pause-6x.png"; // public static final String STOP_PRESSED = "/pressed/media-stop-6x.png"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // }
import Constants.Assets; import Constants.PlayStates; import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JProgressBar;
case ObservablePropertyNames.NOWPLAYING: int newDuration = ((Song) evt.getNewValue()).getDuration(); this.songProgressBar.setMaximum(newDuration); String formattedDuration = this.formattedTime(newDuration); this.songDurationLabel.setText(formattedDuration); default: break; } } public void setPlayButtonState(String state) { switch (state) { case PlayStates.PLAY: this.playPauseStopButton.setIcon(playIcon); this.playPauseStopButton.setPressedIcon(playIconPressed); break; case PlayStates.PAUSE: this.playPauseStopButton.setIcon(pauseIcon); this.playPauseStopButton.setPressedIcon(pauseIconPressed); break; case PlayStates.STOP: this.playPauseStopButton.setIcon(stopIcon); this.playPauseStopButton.setPressedIcon(stopIconPressed); break; default: break; } } private void loadAssets() {
// Path: src/main/java/Constants/Assets.java // public class Assets { // public static final String PLAY = "/media-play-6x.png"; // public static final String PAUSE = "/media-pause-6x.png"; // public static final String STOP = "/media-stop-6x.png"; // public static final String PLAY_PRESSED = "/pressed/media-play-6x.png"; // public static final String PAUSE_PRESSED = "/pressed/media-pause-6x.png"; // public static final String STOP_PRESSED = "/pressed/media-stop-6x.png"; // } // // Path: src/main/java/Constants/PlayStates.java // public class PlayStates { // public static final String PLAY = "play"; // public static final String PAUSE = "pause"; // public static final String STOP = "stop"; // } // // Path: src/main/java/SystemCommands/Song.java // public class Song { // private final String title; // private final String artist; // private final String album; // private final String url; // private final String imageURL; // private final int duration; // // public Song(String title, String artist, String album, String url, String imageURL, int duration) { // this.title = title; // this.artist = artist; // this.album = album; // this.url = url; // this.imageURL = imageURL; // this.duration = duration; // } // // public Song(String title){ // this.title = title; // this.artist = ""; // this.album = ""; // this.url = ""; // this.imageURL = ""; // this.duration = 0; // } // // public String getTitle(){ // return this.title; // } // // public String getArtist() { // return this.artist; // } // // public String getAlbum() { // return this.album; // } // // public String getUrl() { // return this.url; // } // // public String getMediaURL() { // return this.imageURL; // } // // public int getDuration() { // return this.duration; // } // } // Path: src/main/java/Gui/Observers/ControlsObserver.java import Constants.Assets; import Constants.PlayStates; import SystemCommands.Song; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JProgressBar; case ObservablePropertyNames.NOWPLAYING: int newDuration = ((Song) evt.getNewValue()).getDuration(); this.songProgressBar.setMaximum(newDuration); String formattedDuration = this.formattedTime(newDuration); this.songDurationLabel.setText(formattedDuration); default: break; } } public void setPlayButtonState(String state) { switch (state) { case PlayStates.PLAY: this.playPauseStopButton.setIcon(playIcon); this.playPauseStopButton.setPressedIcon(playIconPressed); break; case PlayStates.PAUSE: this.playPauseStopButton.setIcon(pauseIcon); this.playPauseStopButton.setPressedIcon(pauseIconPressed); break; case PlayStates.STOP: this.playPauseStopButton.setIcon(stopIcon); this.playPauseStopButton.setPressedIcon(stopIconPressed); break; default: break; } } private void loadAssets() {
this.playIcon = new ImageIcon(getClass().getResource(Assets.PLAY));
bart-kneepkens/OpenHeosControl
src/test/java/MainViewModelTests.java
// Path: src/main/java/Gui/Observers/ObservablePropertyNames.java // public class ObservablePropertyNames { // public static final String VOLUME = "volume"; // // public static final String PLAYSTATE = "playstate"; // public static final String SONGPROGRESS = "songprogress"; // // public static final String NOWPLAYING = "nowplaying"; // // public static final String PLAYERS = "players"; // // public static final String QUEUE = "queue"; // } // // Path: src/main/java/ViewModel/MainViewModel.java // public class MainViewModel implements Connection.IChangeListener { // private PropertyChangeSupport changes = new PropertyChangeSupport(this); // // private int volume; // // private int songProgress; // // private Player[] players; // private Player currentPlayer; // // private Song nowPlaying; // private Song[] queue; // // public MainViewModel() { // // } // // public void postInit() { // final SsdpClient cl = new SsdpClient(); // try { // String ip = cl.getHeosIp(); // // HeosSystem sys = new HeosSystem(ip); // // System.out.println(sys.systemHeartBeat()); // // this.setPlayers(sys.getPlayers().toArray(new Player[sys.getPlayers().size()])); // // System.out.println(sys.getPlayers()); // // } catch (InterruptedException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } catch (ExecutionException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } // // // TelnetListener.registerForChanges(this); // } // // public void addObserverForProperty(String propertyName, PropertyChangeListener listener) { // changes.addPropertyChangeListener(propertyName, listener); // } // // // MAKE these setters private. // // Public for now, for testing purposes. // private void setVolume(int volume) { // int oldVolume = this.currentPlayer.getVolume(); // this.currentPlayer.setVolume(volume); // changes.firePropertyChange(ObservablePropertyNames.VOLUME, oldVolume, volume); // } // // private void setPlayState(String state) { // String oldState = this.currentPlayer.getPlayState(); // this.currentPlayer.setPlayState(state); // changes.firePropertyChange(ObservablePropertyNames.PLAYSTATE, oldState, state); // } // // private void setSongProgress(int progress) { // int oldProgress = this.songProgress; // this.songProgress = progress; // changes.firePropertyChange(ObservablePropertyNames.SONGPROGRESS, oldProgress, progress); // } // // private void setPlayers(Player[] players) { // Player[] oldPlayers = this.players; // this.players = players; // changes.firePropertyChange(ObservablePropertyNames.PLAYERS, oldPlayers, players); // } // // private void setQueue(Song[] queue) { // Song[] oldQueue = this.queue; // this.queue = queue; // changes.firePropertyChange(ObservablePropertyNames.QUEUE, oldQueue, queue); // } // // private void setNowPlaying(Song song) { // Song oldSong = this.nowPlaying; // this.nowPlaying = song; // changes.firePropertyChange(ObservablePropertyNames.NOWPLAYING, oldSong, song); // } // // public void volumeUpdated(int newValue) { // this.setVolume(newValue); // } // // public void changePlayer(int index) { // this.currentPlayer = this.players[index]; // } // // @Override // public void playerStateChanged(String pid, String state) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerVolumeChanged(String pid, int level) { // this.setVolume(level); // } // // @Override // public void playerNowPlayingChanged(String pid, String nowPlaying) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerNowPlayingProgress(String pid, int current, int duration) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // }
import Gui.Observers.ObservablePropertyNames; import ViewModel.MainViewModel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.junit.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * * @author bartkneepkens */ class MockObserver implements PropertyChangeListener { Object object; @Override public void propertyChange(PropertyChangeEvent evt) { this.object = evt.getNewValue(); } } public class MainViewModelTests {
// Path: src/main/java/Gui/Observers/ObservablePropertyNames.java // public class ObservablePropertyNames { // public static final String VOLUME = "volume"; // // public static final String PLAYSTATE = "playstate"; // public static final String SONGPROGRESS = "songprogress"; // // public static final String NOWPLAYING = "nowplaying"; // // public static final String PLAYERS = "players"; // // public static final String QUEUE = "queue"; // } // // Path: src/main/java/ViewModel/MainViewModel.java // public class MainViewModel implements Connection.IChangeListener { // private PropertyChangeSupport changes = new PropertyChangeSupport(this); // // private int volume; // // private int songProgress; // // private Player[] players; // private Player currentPlayer; // // private Song nowPlaying; // private Song[] queue; // // public MainViewModel() { // // } // // public void postInit() { // final SsdpClient cl = new SsdpClient(); // try { // String ip = cl.getHeosIp(); // // HeosSystem sys = new HeosSystem(ip); // // System.out.println(sys.systemHeartBeat()); // // this.setPlayers(sys.getPlayers().toArray(new Player[sys.getPlayers().size()])); // // System.out.println(sys.getPlayers()); // // } catch (InterruptedException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } catch (ExecutionException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } // // // TelnetListener.registerForChanges(this); // } // // public void addObserverForProperty(String propertyName, PropertyChangeListener listener) { // changes.addPropertyChangeListener(propertyName, listener); // } // // // MAKE these setters private. // // Public for now, for testing purposes. // private void setVolume(int volume) { // int oldVolume = this.currentPlayer.getVolume(); // this.currentPlayer.setVolume(volume); // changes.firePropertyChange(ObservablePropertyNames.VOLUME, oldVolume, volume); // } // // private void setPlayState(String state) { // String oldState = this.currentPlayer.getPlayState(); // this.currentPlayer.setPlayState(state); // changes.firePropertyChange(ObservablePropertyNames.PLAYSTATE, oldState, state); // } // // private void setSongProgress(int progress) { // int oldProgress = this.songProgress; // this.songProgress = progress; // changes.firePropertyChange(ObservablePropertyNames.SONGPROGRESS, oldProgress, progress); // } // // private void setPlayers(Player[] players) { // Player[] oldPlayers = this.players; // this.players = players; // changes.firePropertyChange(ObservablePropertyNames.PLAYERS, oldPlayers, players); // } // // private void setQueue(Song[] queue) { // Song[] oldQueue = this.queue; // this.queue = queue; // changes.firePropertyChange(ObservablePropertyNames.QUEUE, oldQueue, queue); // } // // private void setNowPlaying(Song song) { // Song oldSong = this.nowPlaying; // this.nowPlaying = song; // changes.firePropertyChange(ObservablePropertyNames.NOWPLAYING, oldSong, song); // } // // public void volumeUpdated(int newValue) { // this.setVolume(newValue); // } // // public void changePlayer(int index) { // this.currentPlayer = this.players[index]; // } // // @Override // public void playerStateChanged(String pid, String state) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerVolumeChanged(String pid, int level) { // this.setVolume(level); // } // // @Override // public void playerNowPlayingChanged(String pid, String nowPlaying) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerNowPlayingProgress(String pid, int current, int duration) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // } // Path: src/test/java/MainViewModelTests.java import Gui.Observers.ObservablePropertyNames; import ViewModel.MainViewModel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.junit.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * * @author bartkneepkens */ class MockObserver implements PropertyChangeListener { Object object; @Override public void propertyChange(PropertyChangeEvent evt) { this.object = evt.getNewValue(); } } public class MainViewModelTests {
MainViewModel viewModel;
bart-kneepkens/OpenHeosControl
src/test/java/MainViewModelTests.java
// Path: src/main/java/Gui/Observers/ObservablePropertyNames.java // public class ObservablePropertyNames { // public static final String VOLUME = "volume"; // // public static final String PLAYSTATE = "playstate"; // public static final String SONGPROGRESS = "songprogress"; // // public static final String NOWPLAYING = "nowplaying"; // // public static final String PLAYERS = "players"; // // public static final String QUEUE = "queue"; // } // // Path: src/main/java/ViewModel/MainViewModel.java // public class MainViewModel implements Connection.IChangeListener { // private PropertyChangeSupport changes = new PropertyChangeSupport(this); // // private int volume; // // private int songProgress; // // private Player[] players; // private Player currentPlayer; // // private Song nowPlaying; // private Song[] queue; // // public MainViewModel() { // // } // // public void postInit() { // final SsdpClient cl = new SsdpClient(); // try { // String ip = cl.getHeosIp(); // // HeosSystem sys = new HeosSystem(ip); // // System.out.println(sys.systemHeartBeat()); // // this.setPlayers(sys.getPlayers().toArray(new Player[sys.getPlayers().size()])); // // System.out.println(sys.getPlayers()); // // } catch (InterruptedException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } catch (ExecutionException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } // // // TelnetListener.registerForChanges(this); // } // // public void addObserverForProperty(String propertyName, PropertyChangeListener listener) { // changes.addPropertyChangeListener(propertyName, listener); // } // // // MAKE these setters private. // // Public for now, for testing purposes. // private void setVolume(int volume) { // int oldVolume = this.currentPlayer.getVolume(); // this.currentPlayer.setVolume(volume); // changes.firePropertyChange(ObservablePropertyNames.VOLUME, oldVolume, volume); // } // // private void setPlayState(String state) { // String oldState = this.currentPlayer.getPlayState(); // this.currentPlayer.setPlayState(state); // changes.firePropertyChange(ObservablePropertyNames.PLAYSTATE, oldState, state); // } // // private void setSongProgress(int progress) { // int oldProgress = this.songProgress; // this.songProgress = progress; // changes.firePropertyChange(ObservablePropertyNames.SONGPROGRESS, oldProgress, progress); // } // // private void setPlayers(Player[] players) { // Player[] oldPlayers = this.players; // this.players = players; // changes.firePropertyChange(ObservablePropertyNames.PLAYERS, oldPlayers, players); // } // // private void setQueue(Song[] queue) { // Song[] oldQueue = this.queue; // this.queue = queue; // changes.firePropertyChange(ObservablePropertyNames.QUEUE, oldQueue, queue); // } // // private void setNowPlaying(Song song) { // Song oldSong = this.nowPlaying; // this.nowPlaying = song; // changes.firePropertyChange(ObservablePropertyNames.NOWPLAYING, oldSong, song); // } // // public void volumeUpdated(int newValue) { // this.setVolume(newValue); // } // // public void changePlayer(int index) { // this.currentPlayer = this.players[index]; // } // // @Override // public void playerStateChanged(String pid, String state) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerVolumeChanged(String pid, int level) { // this.setVolume(level); // } // // @Override // public void playerNowPlayingChanged(String pid, String nowPlaying) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerNowPlayingProgress(String pid, int current, int duration) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // }
import Gui.Observers.ObservablePropertyNames; import ViewModel.MainViewModel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.junit.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * * @author bartkneepkens */ class MockObserver implements PropertyChangeListener { Object object; @Override public void propertyChange(PropertyChangeEvent evt) { this.object = evt.getNewValue(); } } public class MainViewModelTests { MainViewModel viewModel; public MainViewModelTests() { viewModel = new MainViewModel(); } @Test public void testChangeVolume() { MockObserver obs = new MockObserver();
// Path: src/main/java/Gui/Observers/ObservablePropertyNames.java // public class ObservablePropertyNames { // public static final String VOLUME = "volume"; // // public static final String PLAYSTATE = "playstate"; // public static final String SONGPROGRESS = "songprogress"; // // public static final String NOWPLAYING = "nowplaying"; // // public static final String PLAYERS = "players"; // // public static final String QUEUE = "queue"; // } // // Path: src/main/java/ViewModel/MainViewModel.java // public class MainViewModel implements Connection.IChangeListener { // private PropertyChangeSupport changes = new PropertyChangeSupport(this); // // private int volume; // // private int songProgress; // // private Player[] players; // private Player currentPlayer; // // private Song nowPlaying; // private Song[] queue; // // public MainViewModel() { // // } // // public void postInit() { // final SsdpClient cl = new SsdpClient(); // try { // String ip = cl.getHeosIp(); // // HeosSystem sys = new HeosSystem(ip); // // System.out.println(sys.systemHeartBeat()); // // this.setPlayers(sys.getPlayers().toArray(new Player[sys.getPlayers().size()])); // // System.out.println(sys.getPlayers()); // // } catch (InterruptedException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } catch (ExecutionException ex) { // Logger.getLogger(MainViewModel.class.getName()).log(Level.SEVERE, null, ex); // } // // // TelnetListener.registerForChanges(this); // } // // public void addObserverForProperty(String propertyName, PropertyChangeListener listener) { // changes.addPropertyChangeListener(propertyName, listener); // } // // // MAKE these setters private. // // Public for now, for testing purposes. // private void setVolume(int volume) { // int oldVolume = this.currentPlayer.getVolume(); // this.currentPlayer.setVolume(volume); // changes.firePropertyChange(ObservablePropertyNames.VOLUME, oldVolume, volume); // } // // private void setPlayState(String state) { // String oldState = this.currentPlayer.getPlayState(); // this.currentPlayer.setPlayState(state); // changes.firePropertyChange(ObservablePropertyNames.PLAYSTATE, oldState, state); // } // // private void setSongProgress(int progress) { // int oldProgress = this.songProgress; // this.songProgress = progress; // changes.firePropertyChange(ObservablePropertyNames.SONGPROGRESS, oldProgress, progress); // } // // private void setPlayers(Player[] players) { // Player[] oldPlayers = this.players; // this.players = players; // changes.firePropertyChange(ObservablePropertyNames.PLAYERS, oldPlayers, players); // } // // private void setQueue(Song[] queue) { // Song[] oldQueue = this.queue; // this.queue = queue; // changes.firePropertyChange(ObservablePropertyNames.QUEUE, oldQueue, queue); // } // // private void setNowPlaying(Song song) { // Song oldSong = this.nowPlaying; // this.nowPlaying = song; // changes.firePropertyChange(ObservablePropertyNames.NOWPLAYING, oldSong, song); // } // // public void volumeUpdated(int newValue) { // this.setVolume(newValue); // } // // public void changePlayer(int index) { // this.currentPlayer = this.players[index]; // } // // @Override // public void playerStateChanged(String pid, String state) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerVolumeChanged(String pid, int level) { // this.setVolume(level); // } // // @Override // public void playerNowPlayingChanged(String pid, String nowPlaying) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // @Override // public void playerNowPlayingProgress(String pid, int current, int duration) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. // } // // } // Path: src/test/java/MainViewModelTests.java import Gui.Observers.ObservablePropertyNames; import ViewModel.MainViewModel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.junit.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * * @author bartkneepkens */ class MockObserver implements PropertyChangeListener { Object object; @Override public void propertyChange(PropertyChangeEvent evt) { this.object = evt.getNewValue(); } } public class MainViewModelTests { MainViewModel viewModel; public MainViewModelTests() { viewModel = new MainViewModel(); } @Test public void testChangeVolume() { MockObserver obs = new MockObserver();
viewModel.addObserverForProperty(ObservablePropertyNames.VOLUME, obs);
bart-kneepkens/OpenHeosControl
src/main/java/Connection/TelnetListener.java
// Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // // Path: src/main/java/SystemCommands/HeosSystem.java // public class HeosSystem { // // public HeosSystem(String ipAddress){ // TelnetConnection.connect(ipAddress); // TelnetListener.connect(ipAddress); // } // // /** // * Checks whether or not the user is signed in to its HEOS system. // * @return The signed in account; if not signed in, null. // */ // public Account accountCheck(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_CHECK); // // if(response.getResult().equals(Results.SUCCESS)){ // if(response.getMessage().contains("signed_in")){ // String username = response.getMessage().substring(response.getMessage().indexOf("un=") + 3); // return new Account(username); // } // } // return null; // } // // /** // * Sign in to the HEOS system with specified HEOS account. // * @param username // * @param password // * @return The signed in account; if not signed in, null. // */ // public Account accountSignIn(String username, String password){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_IN(username, password)); // // if(response.getResult().equals(Results.SUCCESS) && !response.getMessage().contains("command under process")){ // return new Account(username, password); // } // // return null; // } // // /** // * Sign out of the HEOS system. // * @return boolean indicating a successful operation. // */ // public boolean accountSignOut(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_OUT); // return response.getResult().equals(Results.SUCCESS) && response.getMessage().equals("signed_out"); // } // // /** // * Gets the HEOS System state // * @return boolean indicating if the system is alive. // */ // public boolean systemHeartBeat(){ // Response response = TelnetConnection.write(SystemCommands.HEARTBEAT); // return response.getResult().equals(Results.SUCCESS); // } // // /** // * Gets the HEOS players that are connected to this system. // * @return Players. If none, null. // */ // public List<Player> getPlayers(){ // Response response = TelnetConnection.write(SystemCommands.GET_PLAYERS); // // if(response.getResult().equals(Results.SUCCESS)){ // List<Player> toBeReturned = new ArrayList<>(); // for (Map<String, Object> map : (List<Map<String, Object>>) response.getPayload() ) { // toBeReturned.add(new Player(map)); // } // return toBeReturned; // } // return null; // } // // } // // Path: src/main/java/SystemCommands/SystemCommands.java // public class SystemCommands { // public static final String HEARTBEAT = "heos://system/heart_beat"; // public static final String GET_PLAYERS = "heos://player/get_players"; // public static final String ACCOUNT_CHECK = "heos://system/check_account"; // public static final String ACCOUNT_SIGN_OUT = "heos://system/sign_out"; // // public static final String ACCOUNT_SIGN_IN(String username, String password){ // return "heos://system/sign_in?un=" + username + "&pw=" + password; // } // // public static final String REGISTER_FOR_CHANGE_EVENTS(boolean enabled){ // if(enabled){ // return "heos://system/register_for_change_events?enable=on"; // } // return "heos://system/register_for_change_events?enable=off"; // } // }
import Constants.Results; import SystemCommands.HeosSystem; import SystemCommands.SystemCommands; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * A class with static methods that is responsible for listening to change events on the Heos System side. * Opens a separate socket connection, to be used in parallel with TelnetConnection, since it should be polling for any information. * @author bartkneepkens */ public class TelnetListener { /* Networking */ private static Socket socket; private static PrintWriter out; private static Scanner in; private static Gson gson; /** * Connect to a Heos System that is located at a certain ip. * @param ipAddress a valid IP address. */ public static void connect(final String ipAddress) { try { socket = new Socket(ipAddress, 1255); out = new PrintWriter(socket.getOutputStream(), true); in = new Scanner(socket.getInputStream()); in.useDelimiter("\r\n"); gson = new GsonBuilder().create(); } catch (IOException ex) {
// Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // // Path: src/main/java/SystemCommands/HeosSystem.java // public class HeosSystem { // // public HeosSystem(String ipAddress){ // TelnetConnection.connect(ipAddress); // TelnetListener.connect(ipAddress); // } // // /** // * Checks whether or not the user is signed in to its HEOS system. // * @return The signed in account; if not signed in, null. // */ // public Account accountCheck(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_CHECK); // // if(response.getResult().equals(Results.SUCCESS)){ // if(response.getMessage().contains("signed_in")){ // String username = response.getMessage().substring(response.getMessage().indexOf("un=") + 3); // return new Account(username); // } // } // return null; // } // // /** // * Sign in to the HEOS system with specified HEOS account. // * @param username // * @param password // * @return The signed in account; if not signed in, null. // */ // public Account accountSignIn(String username, String password){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_IN(username, password)); // // if(response.getResult().equals(Results.SUCCESS) && !response.getMessage().contains("command under process")){ // return new Account(username, password); // } // // return null; // } // // /** // * Sign out of the HEOS system. // * @return boolean indicating a successful operation. // */ // public boolean accountSignOut(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_OUT); // return response.getResult().equals(Results.SUCCESS) && response.getMessage().equals("signed_out"); // } // // /** // * Gets the HEOS System state // * @return boolean indicating if the system is alive. // */ // public boolean systemHeartBeat(){ // Response response = TelnetConnection.write(SystemCommands.HEARTBEAT); // return response.getResult().equals(Results.SUCCESS); // } // // /** // * Gets the HEOS players that are connected to this system. // * @return Players. If none, null. // */ // public List<Player> getPlayers(){ // Response response = TelnetConnection.write(SystemCommands.GET_PLAYERS); // // if(response.getResult().equals(Results.SUCCESS)){ // List<Player> toBeReturned = new ArrayList<>(); // for (Map<String, Object> map : (List<Map<String, Object>>) response.getPayload() ) { // toBeReturned.add(new Player(map)); // } // return toBeReturned; // } // return null; // } // // } // // Path: src/main/java/SystemCommands/SystemCommands.java // public class SystemCommands { // public static final String HEARTBEAT = "heos://system/heart_beat"; // public static final String GET_PLAYERS = "heos://player/get_players"; // public static final String ACCOUNT_CHECK = "heos://system/check_account"; // public static final String ACCOUNT_SIGN_OUT = "heos://system/sign_out"; // // public static final String ACCOUNT_SIGN_IN(String username, String password){ // return "heos://system/sign_in?un=" + username + "&pw=" + password; // } // // public static final String REGISTER_FOR_CHANGE_EVENTS(boolean enabled){ // if(enabled){ // return "heos://system/register_for_change_events?enable=on"; // } // return "heos://system/register_for_change_events?enable=off"; // } // } // Path: src/main/java/Connection/TelnetListener.java import Constants.Results; import SystemCommands.HeosSystem; import SystemCommands.SystemCommands; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (C) 2017 bartkneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * A class with static methods that is responsible for listening to change events on the Heos System side. * Opens a separate socket connection, to be used in parallel with TelnetConnection, since it should be polling for any information. * @author bartkneepkens */ public class TelnetListener { /* Networking */ private static Socket socket; private static PrintWriter out; private static Scanner in; private static Gson gson; /** * Connect to a Heos System that is located at a certain ip. * @param ipAddress a valid IP address. */ public static void connect(final String ipAddress) { try { socket = new Socket(ipAddress, 1255); out = new PrintWriter(socket.getOutputStream(), true); in = new Scanner(socket.getInputStream()); in.useDelimiter("\r\n"); gson = new GsonBuilder().create(); } catch (IOException ex) {
Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex);
bart-kneepkens/OpenHeosControl
src/main/java/Connection/TelnetListener.java
// Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // // Path: src/main/java/SystemCommands/HeosSystem.java // public class HeosSystem { // // public HeosSystem(String ipAddress){ // TelnetConnection.connect(ipAddress); // TelnetListener.connect(ipAddress); // } // // /** // * Checks whether or not the user is signed in to its HEOS system. // * @return The signed in account; if not signed in, null. // */ // public Account accountCheck(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_CHECK); // // if(response.getResult().equals(Results.SUCCESS)){ // if(response.getMessage().contains("signed_in")){ // String username = response.getMessage().substring(response.getMessage().indexOf("un=") + 3); // return new Account(username); // } // } // return null; // } // // /** // * Sign in to the HEOS system with specified HEOS account. // * @param username // * @param password // * @return The signed in account; if not signed in, null. // */ // public Account accountSignIn(String username, String password){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_IN(username, password)); // // if(response.getResult().equals(Results.SUCCESS) && !response.getMessage().contains("command under process")){ // return new Account(username, password); // } // // return null; // } // // /** // * Sign out of the HEOS system. // * @return boolean indicating a successful operation. // */ // public boolean accountSignOut(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_OUT); // return response.getResult().equals(Results.SUCCESS) && response.getMessage().equals("signed_out"); // } // // /** // * Gets the HEOS System state // * @return boolean indicating if the system is alive. // */ // public boolean systemHeartBeat(){ // Response response = TelnetConnection.write(SystemCommands.HEARTBEAT); // return response.getResult().equals(Results.SUCCESS); // } // // /** // * Gets the HEOS players that are connected to this system. // * @return Players. If none, null. // */ // public List<Player> getPlayers(){ // Response response = TelnetConnection.write(SystemCommands.GET_PLAYERS); // // if(response.getResult().equals(Results.SUCCESS)){ // List<Player> toBeReturned = new ArrayList<>(); // for (Map<String, Object> map : (List<Map<String, Object>>) response.getPayload() ) { // toBeReturned.add(new Player(map)); // } // return toBeReturned; // } // return null; // } // // } // // Path: src/main/java/SystemCommands/SystemCommands.java // public class SystemCommands { // public static final String HEARTBEAT = "heos://system/heart_beat"; // public static final String GET_PLAYERS = "heos://player/get_players"; // public static final String ACCOUNT_CHECK = "heos://system/check_account"; // public static final String ACCOUNT_SIGN_OUT = "heos://system/sign_out"; // // public static final String ACCOUNT_SIGN_IN(String username, String password){ // return "heos://system/sign_in?un=" + username + "&pw=" + password; // } // // public static final String REGISTER_FOR_CHANGE_EVENTS(boolean enabled){ // if(enabled){ // return "heos://system/register_for_change_events?enable=on"; // } // return "heos://system/register_for_change_events?enable=off"; // } // }
import Constants.Results; import SystemCommands.HeosSystem; import SystemCommands.SystemCommands; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger;
* Write a certain command to the Heos System. * @param command a String describing the command (see Constants package) * @return a Response */ public static Response write(final String command) { if (socket == null || out == null || in == null || gson == null) { return null; } new Thread(new Runnable() { @Override public void run() { out.println(command); out.flush(); } }).start(); return gson.fromJson(in.next(), Response.class); } /** * Register a certain listener for change events. For now, the runnable is implemented inside this code block. * @param listener any class that implements IChangeListener */ public static void registerForChanges(final IChangeListener listener) { if (socket == null || in == null || listener == null) { return; } Response r = TelnetListener.write(SystemCommands.REGISTER_FOR_CHANGE_EVENTS(true));
// Path: src/main/java/Constants/Results.java // public class Results { // public static String SUCCESS = "success"; // public static String FAIL = "fail"; // } // // Path: src/main/java/SystemCommands/HeosSystem.java // public class HeosSystem { // // public HeosSystem(String ipAddress){ // TelnetConnection.connect(ipAddress); // TelnetListener.connect(ipAddress); // } // // /** // * Checks whether or not the user is signed in to its HEOS system. // * @return The signed in account; if not signed in, null. // */ // public Account accountCheck(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_CHECK); // // if(response.getResult().equals(Results.SUCCESS)){ // if(response.getMessage().contains("signed_in")){ // String username = response.getMessage().substring(response.getMessage().indexOf("un=") + 3); // return new Account(username); // } // } // return null; // } // // /** // * Sign in to the HEOS system with specified HEOS account. // * @param username // * @param password // * @return The signed in account; if not signed in, null. // */ // public Account accountSignIn(String username, String password){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_IN(username, password)); // // if(response.getResult().equals(Results.SUCCESS) && !response.getMessage().contains("command under process")){ // return new Account(username, password); // } // // return null; // } // // /** // * Sign out of the HEOS system. // * @return boolean indicating a successful operation. // */ // public boolean accountSignOut(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_OUT); // return response.getResult().equals(Results.SUCCESS) && response.getMessage().equals("signed_out"); // } // // /** // * Gets the HEOS System state // * @return boolean indicating if the system is alive. // */ // public boolean systemHeartBeat(){ // Response response = TelnetConnection.write(SystemCommands.HEARTBEAT); // return response.getResult().equals(Results.SUCCESS); // } // // /** // * Gets the HEOS players that are connected to this system. // * @return Players. If none, null. // */ // public List<Player> getPlayers(){ // Response response = TelnetConnection.write(SystemCommands.GET_PLAYERS); // // if(response.getResult().equals(Results.SUCCESS)){ // List<Player> toBeReturned = new ArrayList<>(); // for (Map<String, Object> map : (List<Map<String, Object>>) response.getPayload() ) { // toBeReturned.add(new Player(map)); // } // return toBeReturned; // } // return null; // } // // } // // Path: src/main/java/SystemCommands/SystemCommands.java // public class SystemCommands { // public static final String HEARTBEAT = "heos://system/heart_beat"; // public static final String GET_PLAYERS = "heos://player/get_players"; // public static final String ACCOUNT_CHECK = "heos://system/check_account"; // public static final String ACCOUNT_SIGN_OUT = "heos://system/sign_out"; // // public static final String ACCOUNT_SIGN_IN(String username, String password){ // return "heos://system/sign_in?un=" + username + "&pw=" + password; // } // // public static final String REGISTER_FOR_CHANGE_EVENTS(boolean enabled){ // if(enabled){ // return "heos://system/register_for_change_events?enable=on"; // } // return "heos://system/register_for_change_events?enable=off"; // } // } // Path: src/main/java/Connection/TelnetListener.java import Constants.Results; import SystemCommands.HeosSystem; import SystemCommands.SystemCommands; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; * Write a certain command to the Heos System. * @param command a String describing the command (see Constants package) * @return a Response */ public static Response write(final String command) { if (socket == null || out == null || in == null || gson == null) { return null; } new Thread(new Runnable() { @Override public void run() { out.println(command); out.flush(); } }).start(); return gson.fromJson(in.next(), Response.class); } /** * Register a certain listener for change events. For now, the runnable is implemented inside this code block. * @param listener any class that implements IChangeListener */ public static void registerForChanges(final IChangeListener listener) { if (socket == null || in == null || listener == null) { return; } Response r = TelnetListener.write(SystemCommands.REGISTER_FOR_CHANGE_EVENTS(true));
if (r.getResult().equals(Results.SUCCESS)) {
bart-kneepkens/OpenHeosControl
src/main/java/Connection/TelnetConnection.java
// Path: src/main/java/SystemCommands/HeosSystem.java // public class HeosSystem { // // public HeosSystem(String ipAddress){ // TelnetConnection.connect(ipAddress); // TelnetListener.connect(ipAddress); // } // // /** // * Checks whether or not the user is signed in to its HEOS system. // * @return The signed in account; if not signed in, null. // */ // public Account accountCheck(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_CHECK); // // if(response.getResult().equals(Results.SUCCESS)){ // if(response.getMessage().contains("signed_in")){ // String username = response.getMessage().substring(response.getMessage().indexOf("un=") + 3); // return new Account(username); // } // } // return null; // } // // /** // * Sign in to the HEOS system with specified HEOS account. // * @param username // * @param password // * @return The signed in account; if not signed in, null. // */ // public Account accountSignIn(String username, String password){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_IN(username, password)); // // if(response.getResult().equals(Results.SUCCESS) && !response.getMessage().contains("command under process")){ // return new Account(username, password); // } // // return null; // } // // /** // * Sign out of the HEOS system. // * @return boolean indicating a successful operation. // */ // public boolean accountSignOut(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_OUT); // return response.getResult().equals(Results.SUCCESS) && response.getMessage().equals("signed_out"); // } // // /** // * Gets the HEOS System state // * @return boolean indicating if the system is alive. // */ // public boolean systemHeartBeat(){ // Response response = TelnetConnection.write(SystemCommands.HEARTBEAT); // return response.getResult().equals(Results.SUCCESS); // } // // /** // * Gets the HEOS players that are connected to this system. // * @return Players. If none, null. // */ // public List<Player> getPlayers(){ // Response response = TelnetConnection.write(SystemCommands.GET_PLAYERS); // // if(response.getResult().equals(Results.SUCCESS)){ // List<Player> toBeReturned = new ArrayList<>(); // for (Map<String, Object> map : (List<Map<String, Object>>) response.getPayload() ) { // toBeReturned.add(new Player(map)); // } // return toBeReturned; // } // return null; // } // // }
import SystemCommands.HeosSystem; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2016 bart-kneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * Class with static methods that handle the Telnet connection to the Heos system. * @author bart-kneepkens */ public class TelnetConnection { /* Networking */ private static Socket socket; private static PrintWriter out; private static Scanner in; private static Gson gson; /** * Connect to a Heos System that is located at a certain ip. * @param ipAddress a valid IP address. */ public static void connect(final String ipAddress) { try { socket = new Socket(ipAddress, 1255); out = new PrintWriter(socket.getOutputStream(), true); in = new Scanner(socket.getInputStream()); in.useDelimiter("\r\n"); gson = new GsonBuilder().create(); } catch (IOException ex) {
// Path: src/main/java/SystemCommands/HeosSystem.java // public class HeosSystem { // // public HeosSystem(String ipAddress){ // TelnetConnection.connect(ipAddress); // TelnetListener.connect(ipAddress); // } // // /** // * Checks whether or not the user is signed in to its HEOS system. // * @return The signed in account; if not signed in, null. // */ // public Account accountCheck(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_CHECK); // // if(response.getResult().equals(Results.SUCCESS)){ // if(response.getMessage().contains("signed_in")){ // String username = response.getMessage().substring(response.getMessage().indexOf("un=") + 3); // return new Account(username); // } // } // return null; // } // // /** // * Sign in to the HEOS system with specified HEOS account. // * @param username // * @param password // * @return The signed in account; if not signed in, null. // */ // public Account accountSignIn(String username, String password){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_IN(username, password)); // // if(response.getResult().equals(Results.SUCCESS) && !response.getMessage().contains("command under process")){ // return new Account(username, password); // } // // return null; // } // // /** // * Sign out of the HEOS system. // * @return boolean indicating a successful operation. // */ // public boolean accountSignOut(){ // Response response = TelnetConnection.write(SystemCommands.ACCOUNT_SIGN_OUT); // return response.getResult().equals(Results.SUCCESS) && response.getMessage().equals("signed_out"); // } // // /** // * Gets the HEOS System state // * @return boolean indicating if the system is alive. // */ // public boolean systemHeartBeat(){ // Response response = TelnetConnection.write(SystemCommands.HEARTBEAT); // return response.getResult().equals(Results.SUCCESS); // } // // /** // * Gets the HEOS players that are connected to this system. // * @return Players. If none, null. // */ // public List<Player> getPlayers(){ // Response response = TelnetConnection.write(SystemCommands.GET_PLAYERS); // // if(response.getResult().equals(Results.SUCCESS)){ // List<Player> toBeReturned = new ArrayList<>(); // for (Map<String, Object> map : (List<Map<String, Object>>) response.getPayload() ) { // toBeReturned.add(new Player(map)); // } // return toBeReturned; // } // return null; // } // // } // Path: src/main/java/Connection/TelnetConnection.java import SystemCommands.HeosSystem; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (C) 2016 bart-kneepkens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Connection; /** * Class with static methods that handle the Telnet connection to the Heos system. * @author bart-kneepkens */ public class TelnetConnection { /* Networking */ private static Socket socket; private static PrintWriter out; private static Scanner in; private static Gson gson; /** * Connect to a Heos System that is located at a certain ip. * @param ipAddress a valid IP address. */ public static void connect(final String ipAddress) { try { socket = new Socket(ipAddress, 1255); out = new PrintWriter(socket.getOutputStream(), true); in = new Scanner(socket.getInputStream()); in.useDelimiter("\r\n"); gson = new GsonBuilder().create(); } catch (IOException ex) {
Logger.getLogger(HeosSystem.class.getName()).log(Level.SEVERE, null, ex);
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerConfig.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerAckType.java // public enum ConsumerAckType{ // AUTO_CLIENT_ACK, // CLIENT_ACK; // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/DestinationType.java // public enum DestinationType{ // QUEUE, // TOPIC // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // }
import java.util.Set; import com.groupon.messagebus.api.ConsumerAckType; import com.groupon.messagebus.api.DestinationType; import com.groupon.messagebus.api.HostParams;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ConsumerConfig { // Set of servers to consume from. private Set<HostParams> hostParamsSet = null; // Consumer destination information. private String destinationName;
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerAckType.java // public enum ConsumerAckType{ // AUTO_CLIENT_ACK, // CLIENT_ACK; // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/DestinationType.java // public enum DestinationType{ // QUEUE, // TOPIC // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerConfig.java import java.util.Set; import com.groupon.messagebus.api.ConsumerAckType; import com.groupon.messagebus.api.DestinationType; import com.groupon.messagebus.api.HostParams; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ConsumerConfig { // Set of servers to consume from. private Set<HostParams> hostParamsSet = null; // Consumer destination information. private String destinationName;
private DestinationType destinationType = DestinationType.QUEUE;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerConfig.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerAckType.java // public enum ConsumerAckType{ // AUTO_CLIENT_ACK, // CLIENT_ACK; // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/DestinationType.java // public enum DestinationType{ // QUEUE, // TOPIC // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // }
import java.util.Set; import com.groupon.messagebus.api.ConsumerAckType; import com.groupon.messagebus.api.DestinationType; import com.groupon.messagebus.api.HostParams;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ConsumerConfig { // Set of servers to consume from. private Set<HostParams> hostParamsSet = null; // Consumer destination information. private String destinationName; private DestinationType destinationType = DestinationType.QUEUE;
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerAckType.java // public enum ConsumerAckType{ // AUTO_CLIENT_ACK, // CLIENT_ACK; // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/DestinationType.java // public enum DestinationType{ // QUEUE, // TOPIC // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/ConsumerConfig.java import java.util.Set; import com.groupon.messagebus.api.ConsumerAckType; import com.groupon.messagebus.api.DestinationType; import com.groupon.messagebus.api.HostParams; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ConsumerConfig { // Set of servers to consume from. private Set<HostParams> hostParamsSet = null; // Consumer destination information. private String destinationName; private DestinationType destinationType = DestinationType.QUEUE;
private ConsumerAckType ackType = ConsumerAckType.CLIENT_ACK;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/util/DynamicServerListGetter.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // }
import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.client.utils.URIBuilder; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import com.groupon.messagebus.api.HostParams;
package com.groupon.messagebus.util; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class DynamicServerListGetter { private static Logger log = Logger.getLogger(DynamicServerListGetter.class); private static final int MAX_READ_TIMEOUT = 5000; private static final int MAX_CONNECT_TIMEOUT = 1000; public static String buildDynamicServersURL(String hostname, int port) throws URISyntaxException{ URIBuilder builder = new URIBuilder(); builder.setHost(hostname); builder.setPort(port); builder.setPath("/jmx"); builder.addParameter("command", "get_attribute"); builder.addParameter("args", "org.hornetq:module=Core,type=Server ListOfBrokers"); builder.setScheme("http"); return builder.build().toASCIIString(); } protected static String fetch(String aURL) throws MalformedURLException, IOException { String content = null; URLConnection connection = null; connection = new URL(aURL).openConnection(); connection.setConnectTimeout(MAX_CONNECT_TIMEOUT); connection.setReadTimeout(MAX_READ_TIMEOUT); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); return content; }
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // } // Path: mbus-java/src/main/java/com/groupon/messagebus/util/DynamicServerListGetter.java import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.client.utils.URIBuilder; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import com.groupon.messagebus.api.HostParams; package com.groupon.messagebus.util; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class DynamicServerListGetter { private static Logger log = Logger.getLogger(DynamicServerListGetter.class); private static final int MAX_READ_TIMEOUT = 5000; private static final int MAX_CONNECT_TIMEOUT = 1000; public static String buildDynamicServersURL(String hostname, int port) throws URISyntaxException{ URIBuilder builder = new URIBuilder(); builder.setHost(hostname); builder.setPort(port); builder.setPath("/jmx"); builder.addParameter("command", "get_attribute"); builder.addParameter("args", "org.hornetq:module=Core,type=Server ListOfBrokers"); builder.setScheme("http"); return builder.build().toASCIIString(); } protected static String fetch(String aURL) throws MalformedURLException, IOException { String content = null; URLConnection connection = null; connection = new URL(aURL).openConnection(); connection.setConnectTimeout(MAX_CONNECT_TIMEOUT); connection.setReadTimeout(MAX_READ_TIMEOUT); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); return content; }
public static Set<HostParams> parseAndReturnHosts(String content) {
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // }
import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */
public void start(ProducerConfig config) throws InvalidConfigException, TooManyConnectionRetryAttemptsException, InvalidStatusException;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // }
import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */
public void start(ProducerConfig config) throws InvalidConfigException, TooManyConnectionRetryAttemptsException, InvalidStatusException;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // }
import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */
public void start(ProducerConfig config) throws InvalidConfigException, TooManyConnectionRetryAttemptsException, InvalidStatusException;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // }
import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */ public void start(ProducerConfig config) throws InvalidConfigException, TooManyConnectionRetryAttemptsException, InvalidStatusException; /** * Provides convenient API to refresh connection, in case connection with * the broker breaks during send or any other operation. * * @throws TooManyConnectionRetryAttemptsException * */ public void refreshConnection() throws TooManyConnectionRetryAttemptsException; /** * Stop producer, throws exception */
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */ public void start(ProducerConfig config) throws InvalidConfigException, TooManyConnectionRetryAttemptsException, InvalidStatusException; /** * Provides convenient API to refresh connection, in case connection with * the broker breaks during send or any other operation. * * @throws TooManyConnectionRetryAttemptsException * */ public void refreshConnection() throws TooManyConnectionRetryAttemptsException; /** * Stop producer, throws exception */
public void stop() throws BrokerConnectionCloseFailedException, InvalidStatusException;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // }
import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */ public void start(ProducerConfig config) throws InvalidConfigException, TooManyConnectionRetryAttemptsException, InvalidStatusException; /** * Provides convenient API to refresh connection, in case connection with * the broker breaks during send or any other operation. * * @throws TooManyConnectionRetryAttemptsException * */ public void refreshConnection() throws TooManyConnectionRetryAttemptsException; /** * Stop producer, throws exception */ public void stop() throws BrokerConnectionCloseFailedException, InvalidStatusException; /** * Fire and forget send. Fast (1500+ QPS) but less reliable way of sending * data to the broker. * <p/> * The Producer thread sends data on the server connection and returns * instantly The Message server might not have persisted this message to any * durable format On server restarts/failure the user will lose messages. * This should be used when you have very high load and losing few messages * will not cause much harm. * * @param message : A {@link Message} to send. */
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/BrokerConnectionCloseFailedException.java // @SuppressWarnings("serial") // public class BrokerConnectionCloseFailedException extends MessageBusException { // public BrokerConnectionCloseFailedException(Exception e){ // super(e); // } // // public BrokerConnectionCloseFailedException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidConfigException.java // @SuppressWarnings("serial") // public class InvalidConfigException extends MessageBusException{ // public InvalidConfigException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidStatusException.java // @SuppressWarnings("serial") // public class InvalidStatusException extends RuntimeException { // // public InvalidStatusException(String message) { // super(message); // } // // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/TooManyConnectionRetryAttemptsException.java // @SuppressWarnings("serial") // public class TooManyConnectionRetryAttemptsException extends BrokerConnectionFailedException { // // public TooManyConnectionRetryAttemptsException(String message) { // super(message); // } // // public TooManyConnectionRetryAttemptsException(Exception e) { // super(e); // } // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/Producer.java import java.util.Map; import com.groupon.messagebus.api.exceptions.BrokerConnectionCloseFailedException; import com.groupon.messagebus.api.exceptions.InvalidConfigException; import com.groupon.messagebus.api.exceptions.InvalidStatusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.api.exceptions.TooManyConnectionRetryAttemptsException; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface Producer { public enum Status{ INITIALIZED, RUNNING, STOPPED } public Status getStatus(); /** * Start producer, this opens threads */ public void start(ProducerConfig config) throws InvalidConfigException, TooManyConnectionRetryAttemptsException, InvalidStatusException; /** * Provides convenient API to refresh connection, in case connection with * the broker breaks during send or any other operation. * * @throws TooManyConnectionRetryAttemptsException * */ public void refreshConnection() throws TooManyConnectionRetryAttemptsException; /** * Stop producer, throws exception */ public void stop() throws BrokerConnectionCloseFailedException, InvalidStatusException; /** * Fire and forget send. Fast (1500+ QPS) but less reliable way of sending * data to the broker. * <p/> * The Producer thread sends data on the server connection and returns * instantly The Message server might not have persisted this message to any * durable format On server restarts/failure the user will lose messages. * This should be used when you have very high load and losing few messages * will not cause much harm. * * @param message : A {@link Message} to send. */
public void send(Message message) throws TooManyConnectionRetryAttemptsException, SendFailedException;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/messagebus/api/ProducerConfig.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/DestinationType.java // public enum DestinationType{ // QUEUE, // TOPIC // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // }
import com.groupon.messagebus.api.DestinationType; import com.groupon.messagebus.api.HostParams;
package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ProducerConfig { private HostParams broker; private long connectionLifetime = 300000; private String destinationName;
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/DestinationType.java // public enum DestinationType{ // QUEUE, // TOPIC // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/HostParams.java // public class HostParams { // private String host; // private int port; // // public HostParams(String aHost, int aPort) { // host = aHost; // port = aPort; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String toString() { // return host + ":" + port; // } // // @Override // public int hashCode() { // String hostName = host + ":" + port; // return hostName.hashCode(); // } // // @Override // public boolean equals(Object o) { // // if (o instanceof HostParams) { // HostParams other = (HostParams) o; // // return ((host + ":" + port).equalsIgnoreCase((other.getHost() + ":" + other.getPort()))); // } // // return false; // } // // } // Path: mbus-java/src/main/java/com/groupon/messagebus/api/ProducerConfig.java import com.groupon.messagebus.api.DestinationType; import com.groupon.messagebus.api.HostParams; package com.groupon.messagebus.api; /* * Copyright (c) 2013, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ProducerConfig { private HostParams broker; private long connectionLifetime = 300000; private String destinationName;
private DestinationType destinationType = DestinationType.QUEUE;
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/stomp/StompConnection.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidDestinationException.java // @SuppressWarnings("serial") // public class InvalidDestinationException extends RuntimeException{ // public InvalidDestinationException(Exception e){ // super(e); // } // // public InvalidDestinationException(String msg) { // super(msg); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/MessageBusException.java // @SuppressWarnings("serial") // public class MessageBusException extends Exception { // public MessageBusException(Exception e){ // super(e); // } // // public MessageBusException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/client/Utils.java // public class Utils{ // // private static int MESSAGE_LOG_MAX_LENGTH = 100; // private static TDeserializer deserializer = new TDeserializer(); // private static TSerializer serializer = new TSerializer(); // private static Logger log = Logger.getLogger(Utils.class); // private final static String charset = "US-ASCII"; // // public static final String NULL_STRING = "null"; // // // static String encode( String clearText){ // String ret = ""; // try { // byte[] bytes = clearText.getBytes(charset); // ret = new String(Base64.encodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = clearText; // } // // return ret; // } // // static String decode( String codedText){ // String ret = ""; // try { // byte[] bytes = codedText.getBytes(charset); // // ret = new String(Base64.decodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = codedText; // } // // return ret; // } // public static Message getMessageFromBytes(byte[] bytes) { // try { // MessageInternal messageInternal = new MessageInternal(); // bytes = Base64.decodeBase64(bytes); // synchronized(deserializer){ // deserializer.deserialize(messageInternal, bytes); // } // return new Message(messageInternal); // } catch (Exception e) { // throw new RuntimeException("Failed to read thrift message correctly.", e); // } // } // // // public static byte[] getThriftDataAsBytes(Message message) throws TException, UnsupportedEncodingException { // byte[] bytes = null; // synchronized(serializer){ // bytes = serializer.serialize(message.getMessageInternal()); // } // // bytes = Base64.encodeBase64(bytes); // return bytes; // // } // // // public static String getMessageInternalForLogging(MessageInternal messageInternal) { // String str = messageInternal.toString(); // if (str.length() > MESSAGE_LOG_MAX_LENGTH) // str = str.substring(0, MESSAGE_LOG_MAX_LENGTH -1); // // return str; // } // // public static void sleep(long millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException ie) { // log.error("Error occurred while resting...", ie); // } // } // // }
import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.groupon.messagebus.api.exceptions.InvalidDestinationException; import com.groupon.messagebus.api.exceptions.MessageBusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.client.Utils;
} else { inputBuffer.write(c); } } } public boolean isConnected() { if (stompSocket == null || !stompSocket.isConnected()) { connected = false; } return connected; } private String stringFromBuffer(ByteArrayOutputStream inputBuffer) throws IOException { byte[] ba = inputBuffer.toByteArray(); inputBuffer.reset(); return new String(ba, "UTF-8"); } public Socket getStompSocket() { return stompSocket; } public void setStompSocket(Socket stompSocket) { this.stompSocket = stompSocket; } public void connect(String username, String password) throws IOException,
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidDestinationException.java // @SuppressWarnings("serial") // public class InvalidDestinationException extends RuntimeException{ // public InvalidDestinationException(Exception e){ // super(e); // } // // public InvalidDestinationException(String msg) { // super(msg); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/MessageBusException.java // @SuppressWarnings("serial") // public class MessageBusException extends Exception { // public MessageBusException(Exception e){ // super(e); // } // // public MessageBusException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/client/Utils.java // public class Utils{ // // private static int MESSAGE_LOG_MAX_LENGTH = 100; // private static TDeserializer deserializer = new TDeserializer(); // private static TSerializer serializer = new TSerializer(); // private static Logger log = Logger.getLogger(Utils.class); // private final static String charset = "US-ASCII"; // // public static final String NULL_STRING = "null"; // // // static String encode( String clearText){ // String ret = ""; // try { // byte[] bytes = clearText.getBytes(charset); // ret = new String(Base64.encodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = clearText; // } // // return ret; // } // // static String decode( String codedText){ // String ret = ""; // try { // byte[] bytes = codedText.getBytes(charset); // // ret = new String(Base64.decodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = codedText; // } // // return ret; // } // public static Message getMessageFromBytes(byte[] bytes) { // try { // MessageInternal messageInternal = new MessageInternal(); // bytes = Base64.decodeBase64(bytes); // synchronized(deserializer){ // deserializer.deserialize(messageInternal, bytes); // } // return new Message(messageInternal); // } catch (Exception e) { // throw new RuntimeException("Failed to read thrift message correctly.", e); // } // } // // // public static byte[] getThriftDataAsBytes(Message message) throws TException, UnsupportedEncodingException { // byte[] bytes = null; // synchronized(serializer){ // bytes = serializer.serialize(message.getMessageInternal()); // } // // bytes = Base64.encodeBase64(bytes); // return bytes; // // } // // // public static String getMessageInternalForLogging(MessageInternal messageInternal) { // String str = messageInternal.toString(); // if (str.length() > MESSAGE_LOG_MAX_LENGTH) // str = str.substring(0, MESSAGE_LOG_MAX_LENGTH -1); // // return str; // } // // public static void sleep(long millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException ie) { // log.error("Error occurred while resting...", ie); // } // } // // } // Path: mbus-java/src/main/java/com/groupon/stomp/StompConnection.java import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.groupon.messagebus.api.exceptions.InvalidDestinationException; import com.groupon.messagebus.api.exceptions.MessageBusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.client.Utils; } else { inputBuffer.write(c); } } } public boolean isConnected() { if (stompSocket == null || !stompSocket.isConnected()) { connected = false; } return connected; } private String stringFromBuffer(ByteArrayOutputStream inputBuffer) throws IOException { byte[] ba = inputBuffer.toByteArray(); inputBuffer.reset(); return new String(ba, "UTF-8"); } public Socket getStompSocket() { return stompSocket; } public void setStompSocket(Socket stompSocket) { this.stompSocket = stompSocket; } public void connect(String username, String password) throws IOException,
MessageBusException {
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/stomp/StompConnection.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidDestinationException.java // @SuppressWarnings("serial") // public class InvalidDestinationException extends RuntimeException{ // public InvalidDestinationException(Exception e){ // super(e); // } // // public InvalidDestinationException(String msg) { // super(msg); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/MessageBusException.java // @SuppressWarnings("serial") // public class MessageBusException extends Exception { // public MessageBusException(Exception e){ // super(e); // } // // public MessageBusException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/client/Utils.java // public class Utils{ // // private static int MESSAGE_LOG_MAX_LENGTH = 100; // private static TDeserializer deserializer = new TDeserializer(); // private static TSerializer serializer = new TSerializer(); // private static Logger log = Logger.getLogger(Utils.class); // private final static String charset = "US-ASCII"; // // public static final String NULL_STRING = "null"; // // // static String encode( String clearText){ // String ret = ""; // try { // byte[] bytes = clearText.getBytes(charset); // ret = new String(Base64.encodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = clearText; // } // // return ret; // } // // static String decode( String codedText){ // String ret = ""; // try { // byte[] bytes = codedText.getBytes(charset); // // ret = new String(Base64.decodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = codedText; // } // // return ret; // } // public static Message getMessageFromBytes(byte[] bytes) { // try { // MessageInternal messageInternal = new MessageInternal(); // bytes = Base64.decodeBase64(bytes); // synchronized(deserializer){ // deserializer.deserialize(messageInternal, bytes); // } // return new Message(messageInternal); // } catch (Exception e) { // throw new RuntimeException("Failed to read thrift message correctly.", e); // } // } // // // public static byte[] getThriftDataAsBytes(Message message) throws TException, UnsupportedEncodingException { // byte[] bytes = null; // synchronized(serializer){ // bytes = serializer.serialize(message.getMessageInternal()); // } // // bytes = Base64.encodeBase64(bytes); // return bytes; // // } // // // public static String getMessageInternalForLogging(MessageInternal messageInternal) { // String str = messageInternal.toString(); // if (str.length() > MESSAGE_LOG_MAX_LENGTH) // str = str.substring(0, MESSAGE_LOG_MAX_LENGTH -1); // // return str; // } // // public static void sleep(long millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException ie) { // log.error("Error occurred while resting...", ie); // } // } // // }
import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.groupon.messagebus.api.exceptions.InvalidDestinationException; import com.groupon.messagebus.api.exceptions.MessageBusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.client.Utils;
MessageBusException { connect(username, password, null); } public void connect(String username, String password, String client) throws IOException, MessageBusException { Map<String, String> headers = new HashMap(); headers.put("login", username); headers.put("passcode", password); if (client != null) { headers.put("client-id", client); } StompFrame frame = new StompFrame("CONNECT", headers); sendFrame(frame.format()); StompFrame connect = receive(); if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) { throw new MessageBusException("Not connected to server: " + connect.getBody()); } } public void disconnect() throws IOException { StompFrame frame = new StompFrame("DISCONNECT"); sendFrame(frame.format()); } public void sendSafe(String destination, String message, Map<String, String> headers) throws IOException,
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidDestinationException.java // @SuppressWarnings("serial") // public class InvalidDestinationException extends RuntimeException{ // public InvalidDestinationException(Exception e){ // super(e); // } // // public InvalidDestinationException(String msg) { // super(msg); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/MessageBusException.java // @SuppressWarnings("serial") // public class MessageBusException extends Exception { // public MessageBusException(Exception e){ // super(e); // } // // public MessageBusException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/client/Utils.java // public class Utils{ // // private static int MESSAGE_LOG_MAX_LENGTH = 100; // private static TDeserializer deserializer = new TDeserializer(); // private static TSerializer serializer = new TSerializer(); // private static Logger log = Logger.getLogger(Utils.class); // private final static String charset = "US-ASCII"; // // public static final String NULL_STRING = "null"; // // // static String encode( String clearText){ // String ret = ""; // try { // byte[] bytes = clearText.getBytes(charset); // ret = new String(Base64.encodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = clearText; // } // // return ret; // } // // static String decode( String codedText){ // String ret = ""; // try { // byte[] bytes = codedText.getBytes(charset); // // ret = new String(Base64.decodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = codedText; // } // // return ret; // } // public static Message getMessageFromBytes(byte[] bytes) { // try { // MessageInternal messageInternal = new MessageInternal(); // bytes = Base64.decodeBase64(bytes); // synchronized(deserializer){ // deserializer.deserialize(messageInternal, bytes); // } // return new Message(messageInternal); // } catch (Exception e) { // throw new RuntimeException("Failed to read thrift message correctly.", e); // } // } // // // public static byte[] getThriftDataAsBytes(Message message) throws TException, UnsupportedEncodingException { // byte[] bytes = null; // synchronized(serializer){ // bytes = serializer.serialize(message.getMessageInternal()); // } // // bytes = Base64.encodeBase64(bytes); // return bytes; // // } // // // public static String getMessageInternalForLogging(MessageInternal messageInternal) { // String str = messageInternal.toString(); // if (str.length() > MESSAGE_LOG_MAX_LENGTH) // str = str.substring(0, MESSAGE_LOG_MAX_LENGTH -1); // // return str; // } // // public static void sleep(long millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException ie) { // log.error("Error occurred while resting...", ie); // } // } // // } // Path: mbus-java/src/main/java/com/groupon/stomp/StompConnection.java import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.groupon.messagebus.api.exceptions.InvalidDestinationException; import com.groupon.messagebus.api.exceptions.MessageBusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.client.Utils; MessageBusException { connect(username, password, null); } public void connect(String username, String password, String client) throws IOException, MessageBusException { Map<String, String> headers = new HashMap(); headers.put("login", username); headers.put("passcode", password); if (client != null) { headers.put("client-id", client); } StompFrame frame = new StompFrame("CONNECT", headers); sendFrame(frame.format()); StompFrame connect = receive(); if (!connect.getAction().equals(Stomp.Responses.CONNECTED)) { throw new MessageBusException("Not connected to server: " + connect.getBody()); } } public void disconnect() throws IOException { StompFrame frame = new StompFrame("DISCONNECT"); sendFrame(frame.format()); } public void sendSafe(String destination, String message, Map<String, String> headers) throws IOException,
SendFailedException {
groupon/Message-Bus
mbus-java/src/main/java/com/groupon/stomp/StompConnection.java
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidDestinationException.java // @SuppressWarnings("serial") // public class InvalidDestinationException extends RuntimeException{ // public InvalidDestinationException(Exception e){ // super(e); // } // // public InvalidDestinationException(String msg) { // super(msg); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/MessageBusException.java // @SuppressWarnings("serial") // public class MessageBusException extends Exception { // public MessageBusException(Exception e){ // super(e); // } // // public MessageBusException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/client/Utils.java // public class Utils{ // // private static int MESSAGE_LOG_MAX_LENGTH = 100; // private static TDeserializer deserializer = new TDeserializer(); // private static TSerializer serializer = new TSerializer(); // private static Logger log = Logger.getLogger(Utils.class); // private final static String charset = "US-ASCII"; // // public static final String NULL_STRING = "null"; // // // static String encode( String clearText){ // String ret = ""; // try { // byte[] bytes = clearText.getBytes(charset); // ret = new String(Base64.encodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = clearText; // } // // return ret; // } // // static String decode( String codedText){ // String ret = ""; // try { // byte[] bytes = codedText.getBytes(charset); // // ret = new String(Base64.decodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = codedText; // } // // return ret; // } // public static Message getMessageFromBytes(byte[] bytes) { // try { // MessageInternal messageInternal = new MessageInternal(); // bytes = Base64.decodeBase64(bytes); // synchronized(deserializer){ // deserializer.deserialize(messageInternal, bytes); // } // return new Message(messageInternal); // } catch (Exception e) { // throw new RuntimeException("Failed to read thrift message correctly.", e); // } // } // // // public static byte[] getThriftDataAsBytes(Message message) throws TException, UnsupportedEncodingException { // byte[] bytes = null; // synchronized(serializer){ // bytes = serializer.serialize(message.getMessageInternal()); // } // // bytes = Base64.encodeBase64(bytes); // return bytes; // // } // // // public static String getMessageInternalForLogging(MessageInternal messageInternal) { // String str = messageInternal.toString(); // if (str.length() > MESSAGE_LOG_MAX_LENGTH) // str = str.substring(0, MESSAGE_LOG_MAX_LENGTH -1); // // return str; // } // // public static void sleep(long millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException ie) { // log.error("Error occurred while resting...", ie); // } // } // // }
import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.groupon.messagebus.api.exceptions.InvalidDestinationException; import com.groupon.messagebus.api.exceptions.MessageBusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.client.Utils;
StompFrame frame = new StompFrame("ABORT", headers); sendFrame(frame.format()); } public void commit(String transaction) throws IOException { Map<String, String> headers = new HashMap<String, String>(); headers.put("transaction", transaction); StompFrame frame = new StompFrame("COMMIT", headers); sendFrame(frame.format()); } public void ack(String messageId) throws IOException { ack(messageId, null, null, null, null); } public void ack(String messageId, String receiptId) throws IOException { ack(messageId, null, null, null, receiptId); } public void ack(String messageId, String transaction, String subscriptionId, String connectionId, String receiptId) throws IOException { Map<String, String> headers = new HashMap<String, String>(); headers.put("message-id", messageId); log.debug("acking message-id: " + messageId); if (transaction != null) headers.put("transaction", transaction); if (subscriptionId != null && !subscriptionId.equals("")) headers.put("subscription", subscriptionId);
// Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/InvalidDestinationException.java // @SuppressWarnings("serial") // public class InvalidDestinationException extends RuntimeException{ // public InvalidDestinationException(Exception e){ // super(e); // } // // public InvalidDestinationException(String msg) { // super(msg); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/MessageBusException.java // @SuppressWarnings("serial") // public class MessageBusException extends Exception { // public MessageBusException(Exception e){ // super(e); // } // // public MessageBusException(String message){ // super(message); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/api/exceptions/SendFailedException.java // public class SendFailedException extends MessageBusException{ // public SendFailedException(String message) { // super(message); // } // // public SendFailedException(Exception e) { // super(e); // } // } // // Path: mbus-java/src/main/java/com/groupon/messagebus/client/Utils.java // public class Utils{ // // private static int MESSAGE_LOG_MAX_LENGTH = 100; // private static TDeserializer deserializer = new TDeserializer(); // private static TSerializer serializer = new TSerializer(); // private static Logger log = Logger.getLogger(Utils.class); // private final static String charset = "US-ASCII"; // // public static final String NULL_STRING = "null"; // // // static String encode( String clearText){ // String ret = ""; // try { // byte[] bytes = clearText.getBytes(charset); // ret = new String(Base64.encodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = clearText; // } // // return ret; // } // // static String decode( String codedText){ // String ret = ""; // try { // byte[] bytes = codedText.getBytes(charset); // // ret = new String(Base64.decodeBase64(bytes), charset); // } catch (UnsupportedEncodingException e) { // log.error("Failed to encode message. Non alphanumeric char?"); // ret = codedText; // } // // return ret; // } // public static Message getMessageFromBytes(byte[] bytes) { // try { // MessageInternal messageInternal = new MessageInternal(); // bytes = Base64.decodeBase64(bytes); // synchronized(deserializer){ // deserializer.deserialize(messageInternal, bytes); // } // return new Message(messageInternal); // } catch (Exception e) { // throw new RuntimeException("Failed to read thrift message correctly.", e); // } // } // // // public static byte[] getThriftDataAsBytes(Message message) throws TException, UnsupportedEncodingException { // byte[] bytes = null; // synchronized(serializer){ // bytes = serializer.serialize(message.getMessageInternal()); // } // // bytes = Base64.encodeBase64(bytes); // return bytes; // // } // // // public static String getMessageInternalForLogging(MessageInternal messageInternal) { // String str = messageInternal.toString(); // if (str.length() > MESSAGE_LOG_MAX_LENGTH) // str = str.substring(0, MESSAGE_LOG_MAX_LENGTH -1); // // return str; // } // // public static void sleep(long millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException ie) { // log.error("Error occurred while resting...", ie); // } // } // // } // Path: mbus-java/src/main/java/com/groupon/stomp/StompConnection.java import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.groupon.messagebus.api.exceptions.InvalidDestinationException; import com.groupon.messagebus.api.exceptions.MessageBusException; import com.groupon.messagebus.api.exceptions.SendFailedException; import com.groupon.messagebus.client.Utils; StompFrame frame = new StompFrame("ABORT", headers); sendFrame(frame.format()); } public void commit(String transaction) throws IOException { Map<String, String> headers = new HashMap<String, String>(); headers.put("transaction", transaction); StompFrame frame = new StompFrame("COMMIT", headers); sendFrame(frame.format()); } public void ack(String messageId) throws IOException { ack(messageId, null, null, null, null); } public void ack(String messageId, String receiptId) throws IOException { ack(messageId, null, null, null, receiptId); } public void ack(String messageId, String transaction, String subscriptionId, String connectionId, String receiptId) throws IOException { Map<String, String> headers = new HashMap<String, String>(); headers.put("message-id", messageId); log.debug("acking message-id: " + messageId); if (transaction != null) headers.put("transaction", transaction); if (subscriptionId != null && !subscriptionId.equals("")) headers.put("subscription", subscriptionId);
if (connectionId != null && !connectionId.equals(Utils.NULL_STRING))
Progether/JAdventure
src/main/java/com/jadventure/game/JAdventure.java
// Path: src/main/java/com/jadventure/game/menus/MainMenu.java // public class MainMenu extends Menus implements Runnable { // // public MainMenu(Socket server, GameModeType mode){ // QueueProvider.startMessenger(mode, server); // } // // public MainMenu() { // start(); // } // // public void run() { // start(); // } // // public void start() { // menuItems.add(new MenuItem("Start", "Starts a new Game", "new")); // menuItems.add(new MenuItem("Load", "Loads an existing Game")); // menuItems.add(new MenuItem("Delete", "Deletes an existing Game")); // menuItems.add(new MenuItem("Exit", null, "quit")); // // boolean continuing = true; // do { // MenuItem selectedItem = displayMenu(menuItems); // try { // continuing = testOption(selectedItem); // } catch (DeathException e) { // if (e.getLocalisedMessage().equals("close")) { // continuing = false; // } // } // } while(continuing); // QueueProvider.offer("EXIT"); // } // // private static boolean testOption(MenuItem m) throws DeathException { // String key = m.getKey(); // switch (key){ // case "start": // new ChooseClassMenu(); // break; // case "load": // loadProfileFromMenu(); // break; // case "delete": // deleteProfileFromMenu(); // break; // case "exit": // QueueProvider.offer("Goodbye!"); // return false; // } // return true; // } // // private static void loadProfileFromMenu() throws DeathException { // String key; // if (isProfileDirEmpty()) { // QueueProvider.offer("\nThere are no profiles to load. Please start a new game instead."); // return; // } // Player player = null; // do { // listProfiles(); // QueueProvider.offer("\nSelect a profile to load. Type 'back' to go back."); // key = QueueProvider.take(); // if (key.equals("exit") || key.equals("back")) { // return; // } else if (Player.profileExists(key)) { // player = Player.load(key); // } else { // QueueProvider.offer("That user doesn't exist. Try again."); // } // } while (player == null); // new Game(player, "old"); // } // // private static void deleteProfileFromMenu() { // String key; // while (true) { // if (isProfileDirEmpty()) { // QueueProvider.offer("\nThere are no profiles to delete."); // return; // } // listProfiles(); // QueueProvider.offer("\nWhich profile do you want to delete? Type 'back' to go back."); // key = QueueProvider.take(); // if ((key.equals("exit") || key.equals("back"))) { // return; // } // if (Player.profileExists(key)) { // String profileName = key; // QueueProvider.offer("Are you sure you want to delete " + profileName + "? y/n"); // key = QueueProvider.take(); // if ((key.equals("exit") || key.equals("back"))) { // return; // } else if (key.equals("y")) { // File profile = new File("json/profiles/" + profileName); // deleteDirectory(profile); // QueueProvider.offer(profileName + " has been deleted."); // return; // } else { // QueueProvider.offer(profileName + " will NOT be deleted."); // } // } else { // QueueProvider.offer("That user doesn't exist. Try again."); // } // } // } // // private static boolean deleteDirectory(File directory) { // if(directory.exists()){ // File[] files = directory.listFiles(); // for (File file : files) { // if(file.isDirectory()) { // deleteDirectory(file); // } else { // file.delete(); // } // } // } // return directory.delete(); // } // // private static boolean isProfileDirEmpty() { // int numProfiles = new File("json/profiles").list().length; // return (numProfiles == 0); // } // // private static void listProfiles() { // if (isProfileDirEmpty()) { // QueueProvider.offer("No profiles found."); // return; // } // File file = new File("json/profiles"); // String[] profiles = file.list(); // QueueProvider.offer("Profiles:"); // for (String name : profiles) { // if (new File("json/profiles/" + name).isDirectory()) { // QueueProvider.offer(" " + name); // } // } // } // }
import com.jadventure.game.menus.MainMenu; import java.net.ServerSocket; import java.net.Socket; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.jadventure.game; /** * This is the starting point of the game. * This class doesn't do much more than create * a new MainMenu that will handle the rest of * the game. */ public class JAdventure { private static Logger logger = LoggerFactory.getLogger(JAdventure.class); public static void main(String[] args) { logger.info("Starting JAdventure " + toString(args)); GameModeType mode = getGameMode(args); logger.debug("Starting in mode " + mode.name()); String serverName = "localhost"; int port = 4044; if (mode == GameModeType.SERVER) { port = Integer.parseInt(args[1]); } else if (mode == GameModeType.CLIENT) { serverName = args[2]; port = Integer.parseInt(args[1]); } if (GameModeType.CLIENT == mode) { new Client(serverName, port); } else if (GameModeType.SERVER == mode) { while (true) { ServerSocket listener = null; try { listener = new ServerSocket(port); while (true) { Socket server = listener.accept();
// Path: src/main/java/com/jadventure/game/menus/MainMenu.java // public class MainMenu extends Menus implements Runnable { // // public MainMenu(Socket server, GameModeType mode){ // QueueProvider.startMessenger(mode, server); // } // // public MainMenu() { // start(); // } // // public void run() { // start(); // } // // public void start() { // menuItems.add(new MenuItem("Start", "Starts a new Game", "new")); // menuItems.add(new MenuItem("Load", "Loads an existing Game")); // menuItems.add(new MenuItem("Delete", "Deletes an existing Game")); // menuItems.add(new MenuItem("Exit", null, "quit")); // // boolean continuing = true; // do { // MenuItem selectedItem = displayMenu(menuItems); // try { // continuing = testOption(selectedItem); // } catch (DeathException e) { // if (e.getLocalisedMessage().equals("close")) { // continuing = false; // } // } // } while(continuing); // QueueProvider.offer("EXIT"); // } // // private static boolean testOption(MenuItem m) throws DeathException { // String key = m.getKey(); // switch (key){ // case "start": // new ChooseClassMenu(); // break; // case "load": // loadProfileFromMenu(); // break; // case "delete": // deleteProfileFromMenu(); // break; // case "exit": // QueueProvider.offer("Goodbye!"); // return false; // } // return true; // } // // private static void loadProfileFromMenu() throws DeathException { // String key; // if (isProfileDirEmpty()) { // QueueProvider.offer("\nThere are no profiles to load. Please start a new game instead."); // return; // } // Player player = null; // do { // listProfiles(); // QueueProvider.offer("\nSelect a profile to load. Type 'back' to go back."); // key = QueueProvider.take(); // if (key.equals("exit") || key.equals("back")) { // return; // } else if (Player.profileExists(key)) { // player = Player.load(key); // } else { // QueueProvider.offer("That user doesn't exist. Try again."); // } // } while (player == null); // new Game(player, "old"); // } // // private static void deleteProfileFromMenu() { // String key; // while (true) { // if (isProfileDirEmpty()) { // QueueProvider.offer("\nThere are no profiles to delete."); // return; // } // listProfiles(); // QueueProvider.offer("\nWhich profile do you want to delete? Type 'back' to go back."); // key = QueueProvider.take(); // if ((key.equals("exit") || key.equals("back"))) { // return; // } // if (Player.profileExists(key)) { // String profileName = key; // QueueProvider.offer("Are you sure you want to delete " + profileName + "? y/n"); // key = QueueProvider.take(); // if ((key.equals("exit") || key.equals("back"))) { // return; // } else if (key.equals("y")) { // File profile = new File("json/profiles/" + profileName); // deleteDirectory(profile); // QueueProvider.offer(profileName + " has been deleted."); // return; // } else { // QueueProvider.offer(profileName + " will NOT be deleted."); // } // } else { // QueueProvider.offer("That user doesn't exist. Try again."); // } // } // } // // private static boolean deleteDirectory(File directory) { // if(directory.exists()){ // File[] files = directory.listFiles(); // for (File file : files) { // if(file.isDirectory()) { // deleteDirectory(file); // } else { // file.delete(); // } // } // } // return directory.delete(); // } // // private static boolean isProfileDirEmpty() { // int numProfiles = new File("json/profiles").list().length; // return (numProfiles == 0); // } // // private static void listProfiles() { // if (isProfileDirEmpty()) { // QueueProvider.offer("No profiles found."); // return; // } // File file = new File("json/profiles"); // String[] profiles = file.list(); // QueueProvider.offer("Profiles:"); // for (String name : profiles) { // if (new File("json/profiles/" + name).isDirectory()) { // QueueProvider.offer(" " + name); // } // } // } // } // Path: src/main/java/com/jadventure/game/JAdventure.java import com.jadventure.game.menus.MainMenu; import java.net.ServerSocket; import java.net.Socket; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.jadventure.game; /** * This is the starting point of the game. * This class doesn't do much more than create * a new MainMenu that will handle the rest of * the game. */ public class JAdventure { private static Logger logger = LoggerFactory.getLogger(JAdventure.class); public static void main(String[] args) { logger.info("Starting JAdventure " + toString(args)); GameModeType mode = getGameMode(args); logger.debug("Starting in mode " + mode.name()); String serverName = "localhost"; int port = 4044; if (mode == GameModeType.SERVER) { port = Integer.parseInt(args[1]); } else if (mode == GameModeType.CLIENT) { serverName = args[2]; port = Integer.parseInt(args[1]); } if (GameModeType.CLIENT == mode) { new Client(serverName, port); } else if (GameModeType.SERVER == mode) { while (true) { ServerSocket listener = null; try { listener = new ServerSocket(port); while (true) { Socket server = listener.accept();
Runnable r = new MainMenu(server, mode);
Progether/JAdventure
src/main/java/com/jadventure/game/monsters/Monster.java
// Path: src/main/java/com/jadventure/game/entities/NPC.java // public class NPC extends Entity { // private int xpGain; // private String id; // private List<String> allies; // private List<String> enemies; // // public NPC() { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // } // // public NPC(String entityID) { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // this.id = entityID; // } // // public void setItems(JsonObject json, int itemLimit, int i) { // JsonArray items = json.get("items").getAsJsonArray(); // JsonArray itemTypes = json.get("tradingEmphasis").getAsJsonArray(); // boolean cont; // for (JsonElement item : items) { // if (i == itemLimit) { // break; // } // // cont = false; // char itemType = item.getAsString().charAt(0); // for (JsonElement type : itemTypes) { // if (itemType == type.getAsString().charAt(0)) { // cont = true; // } // } // // Random rand = new Random(); // int j = rand.nextInt(100) + 1; // if (cont) { // if ((j > 0) && (j <= 95)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } else { // if ((j > 95) && (j <= 100)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } // } // if (i != itemLimit) { // setItems(json, itemLimit, i); // } // } // // public List<String> getAllies() { // return allies; // } // // public List<String> getEnemies() { // return enemies; // } // // public void setAllies( List<String> allies ) { // this.allies = allies; // } // // public void setEnemies( List<String> enemies ) { // this.enemies = enemies; // } // // public int getXPGain() { // return xpGain; // } // // public void setXPGain(int xpGain) { // this.xpGain = xpGain; // } // // public String getId() { // return id; // } // // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj instanceof NPC) { // NPC npc = (NPC) obj; // return npc.getId().equals(id); // } // return false; // } // // // } // // Path: src/main/java/com/jadventure/game/GameBeans.java // public final class GameBeans { // // public static ItemRepository getItemRepository() { // return ItemRepository.createRepo(); // } // // public static LocationRepository getLocationRepository() { // return LocationRepository.createRepo(""); // } // // public static LocationRepository getLocationRepository(String profile) { // return LocationRepository.createRepo(profile); // } // // public static NpcRepository getNpcRepository() { // return EncounteredNpcRepository.createRepo(); // } // }
import com.jadventure.game.entities.NPC; import com.jadventure.game.items.Item; import com.jadventure.game.GameBeans; import com.jadventure.game.repository.ItemRepository; import java.util.List; import java.util.Arrays; import java.util.Random;
package com.jadventure.game.monsters; /* * This class just holds a type of monster that is * further outlined in its respective file. For now it * just holds the monster's name. */ public abstract class Monster extends NPC { public String monsterType;
// Path: src/main/java/com/jadventure/game/entities/NPC.java // public class NPC extends Entity { // private int xpGain; // private String id; // private List<String> allies; // private List<String> enemies; // // public NPC() { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // } // // public NPC(String entityID) { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // this.id = entityID; // } // // public void setItems(JsonObject json, int itemLimit, int i) { // JsonArray items = json.get("items").getAsJsonArray(); // JsonArray itemTypes = json.get("tradingEmphasis").getAsJsonArray(); // boolean cont; // for (JsonElement item : items) { // if (i == itemLimit) { // break; // } // // cont = false; // char itemType = item.getAsString().charAt(0); // for (JsonElement type : itemTypes) { // if (itemType == type.getAsString().charAt(0)) { // cont = true; // } // } // // Random rand = new Random(); // int j = rand.nextInt(100) + 1; // if (cont) { // if ((j > 0) && (j <= 95)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } else { // if ((j > 95) && (j <= 100)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } // } // if (i != itemLimit) { // setItems(json, itemLimit, i); // } // } // // public List<String> getAllies() { // return allies; // } // // public List<String> getEnemies() { // return enemies; // } // // public void setAllies( List<String> allies ) { // this.allies = allies; // } // // public void setEnemies( List<String> enemies ) { // this.enemies = enemies; // } // // public int getXPGain() { // return xpGain; // } // // public void setXPGain(int xpGain) { // this.xpGain = xpGain; // } // // public String getId() { // return id; // } // // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj instanceof NPC) { // NPC npc = (NPC) obj; // return npc.getId().equals(id); // } // return false; // } // // // } // // Path: src/main/java/com/jadventure/game/GameBeans.java // public final class GameBeans { // // public static ItemRepository getItemRepository() { // return ItemRepository.createRepo(); // } // // public static LocationRepository getLocationRepository() { // return LocationRepository.createRepo(""); // } // // public static LocationRepository getLocationRepository(String profile) { // return LocationRepository.createRepo(profile); // } // // public static NpcRepository getNpcRepository() { // return EncounteredNpcRepository.createRepo(); // } // } // Path: src/main/java/com/jadventure/game/monsters/Monster.java import com.jadventure.game.entities.NPC; import com.jadventure.game.items.Item; import com.jadventure.game.GameBeans; import com.jadventure.game.repository.ItemRepository; import java.util.List; import java.util.Arrays; import java.util.Random; package com.jadventure.game.monsters; /* * This class just holds a type of monster that is * further outlined in its respective file. For now it * just holds the monster's name. */ public abstract class Monster extends NPC { public String monsterType;
private ItemRepository itemRepo = GameBeans.getItemRepository();
Progether/JAdventure
src/test/java/com/jadventure/game/repository/EncounteredNpcRepositoryTest.java
// Path: src/main/java/com/jadventure/game/entities/NPC.java // public class NPC extends Entity { // private int xpGain; // private String id; // private List<String> allies; // private List<String> enemies; // // public NPC() { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // } // // public NPC(String entityID) { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // this.id = entityID; // } // // public void setItems(JsonObject json, int itemLimit, int i) { // JsonArray items = json.get("items").getAsJsonArray(); // JsonArray itemTypes = json.get("tradingEmphasis").getAsJsonArray(); // boolean cont; // for (JsonElement item : items) { // if (i == itemLimit) { // break; // } // // cont = false; // char itemType = item.getAsString().charAt(0); // for (JsonElement type : itemTypes) { // if (itemType == type.getAsString().charAt(0)) { // cont = true; // } // } // // Random rand = new Random(); // int j = rand.nextInt(100) + 1; // if (cont) { // if ((j > 0) && (j <= 95)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } else { // if ((j > 95) && (j <= 100)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } // } // if (i != itemLimit) { // setItems(json, itemLimit, i); // } // } // // public List<String> getAllies() { // return allies; // } // // public List<String> getEnemies() { // return enemies; // } // // public void setAllies( List<String> allies ) { // this.allies = allies; // } // // public void setEnemies( List<String> enemies ) { // this.enemies = enemies; // } // // public int getXPGain() { // return xpGain; // } // // public void setXPGain(int xpGain) { // this.xpGain = xpGain; // } // // public String getId() { // return id; // } // // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj instanceof NPC) { // NPC npc = (NPC) obj; // return npc.getId().equals(id); // } // return false; // } // // // }
import com.jadventure.game.entities.NPC; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package com.jadventure.game.repository; public class EncounteredNpcRepositoryTest { @Test public void createRepo() { NpcRepository npcRepo = EncounteredNpcRepository.createRepo(); assertNotNull(npcRepo); } @Test public void getNpc() { NpcRepository npcRepo = EncounteredNpcRepository.createRepo();
// Path: src/main/java/com/jadventure/game/entities/NPC.java // public class NPC extends Entity { // private int xpGain; // private String id; // private List<String> allies; // private List<String> enemies; // // public NPC() { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // } // // public NPC(String entityID) { // allies = new ArrayList<>(); // enemies = new ArrayList<>(); // this.id = entityID; // } // // public void setItems(JsonObject json, int itemLimit, int i) { // JsonArray items = json.get("items").getAsJsonArray(); // JsonArray itemTypes = json.get("tradingEmphasis").getAsJsonArray(); // boolean cont; // for (JsonElement item : items) { // if (i == itemLimit) { // break; // } // // cont = false; // char itemType = item.getAsString().charAt(0); // for (JsonElement type : itemTypes) { // if (itemType == type.getAsString().charAt(0)) { // cont = true; // } // } // // Random rand = new Random(); // int j = rand.nextInt(100) + 1; // if (cont) { // if ((j > 0) && (j <= 95)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } else { // if ((j > 95) && (j <= 100)) { // addItemToStorage(itemRepo.getItem(item.getAsString())); // i++; // } // } // } // if (i != itemLimit) { // setItems(json, itemLimit, i); // } // } // // public List<String> getAllies() { // return allies; // } // // public List<String> getEnemies() { // return enemies; // } // // public void setAllies( List<String> allies ) { // this.allies = allies; // } // // public void setEnemies( List<String> enemies ) { // this.enemies = enemies; // } // // public int getXPGain() { // return xpGain; // } // // public void setXPGain(int xpGain) { // this.xpGain = xpGain; // } // // public String getId() { // return id; // } // // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (obj instanceof NPC) { // NPC npc = (NPC) obj; // return npc.getId().equals(id); // } // return false; // } // // // } // Path: src/test/java/com/jadventure/game/repository/EncounteredNpcRepositoryTest.java import com.jadventure.game.entities.NPC; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package com.jadventure.game.repository; public class EncounteredNpcRepositoryTest { @Test public void createRepo() { NpcRepository npcRepo = EncounteredNpcRepository.createRepo(); assertNotNull(npcRepo); } @Test public void getNpc() { NpcRepository npcRepo = EncounteredNpcRepository.createRepo();
NPC guide = npcRepo.getNpc("guide");
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/func/WriteCoilFunction.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/UnexpectedResponseException.java // public class UnexpectedResponseException extends DecoderException { // // public UnexpectedResponseException() { // } // // public UnexpectedResponseException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedResponseException(String message) { // super(message); // } // // public UnexpectedResponseException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/WriteCoilResponse.java // public class WriteCoilResponse extends ModbusResponse { // // private boolean value; // private int address; // // public WriteCoilResponse(int transectionId, int unitId, int address, boolean value) { // super(transectionId, unitId); // this.address = address; // this.value = value; // } // // public WriteCoilResponse() { // } // // public boolean getValue() { // return value; // } // // public void setValue(boolean value) { // this.value = value; // } // // public int getAddress() { // return address; // } // // public void setAddress(int address) { // this.address = address; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeShort(address); // out.writeShort(value ? 0xFF00 : 0x0000); // // } // // @Override // public int getPduCoreLength() { // return 4; // } // // @Override // public int getFunctionCode() { // return 0x05; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + address; // result = prime * result + (value ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // WriteCoilResponse other = (WriteCoilResponse) obj; // if (address != other.address) // return false; // if (value != other.value) // return false; // return true; // } // // @Override // public String toString() { // return "WriteCoilResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", address=" + address // + ", value=" + value + "]"; // } // // }
import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.UnexpectedResponseException; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import net.epsilony.utils.codec.modbus.reqres.WriteCoilResponse;
public int getCode() { return 0x05; } public int getAddress() { return address; } public void setAddress(int address) { if (address < 0 || address > 0xffff) { throw new IllegalArgumentException(); } this.address = address; } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } @Override public void decodeRequestData(ByteBuf data) { setAddress(data.readUnsignedShort()); value = data.readUnsignedShort() == 0xFF00; } @Override
// Path: src/main/java/net/epsilony/utils/codec/modbus/UnexpectedResponseException.java // public class UnexpectedResponseException extends DecoderException { // // public UnexpectedResponseException() { // } // // public UnexpectedResponseException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedResponseException(String message) { // super(message); // } // // public UnexpectedResponseException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/WriteCoilResponse.java // public class WriteCoilResponse extends ModbusResponse { // // private boolean value; // private int address; // // public WriteCoilResponse(int transectionId, int unitId, int address, boolean value) { // super(transectionId, unitId); // this.address = address; // this.value = value; // } // // public WriteCoilResponse() { // } // // public boolean getValue() { // return value; // } // // public void setValue(boolean value) { // this.value = value; // } // // public int getAddress() { // return address; // } // // public void setAddress(int address) { // this.address = address; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeShort(address); // out.writeShort(value ? 0xFF00 : 0x0000); // // } // // @Override // public int getPduCoreLength() { // return 4; // } // // @Override // public int getFunctionCode() { // return 0x05; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + address; // result = prime * result + (value ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // WriteCoilResponse other = (WriteCoilResponse) obj; // if (address != other.address) // return false; // if (value != other.value) // return false; // return true; // } // // @Override // public String toString() { // return "WriteCoilResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", address=" + address // + ", value=" + value + "]"; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/func/WriteCoilFunction.java import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.UnexpectedResponseException; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import net.epsilony.utils.codec.modbus.reqres.WriteCoilResponse; public int getCode() { return 0x05; } public int getAddress() { return address; } public void setAddress(int address) { if (address < 0 || address > 0xffff) { throw new IllegalArgumentException(); } this.address = address; } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } @Override public void decodeRequestData(ByteBuf data) { setAddress(data.readUnsignedShort()); value = data.readUnsignedShort() == 0xFF00; } @Override
public void decodeResponseData(ByteBuf data, ModbusResponse response) {
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/func/WriteCoilFunction.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/UnexpectedResponseException.java // public class UnexpectedResponseException extends DecoderException { // // public UnexpectedResponseException() { // } // // public UnexpectedResponseException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedResponseException(String message) { // super(message); // } // // public UnexpectedResponseException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/WriteCoilResponse.java // public class WriteCoilResponse extends ModbusResponse { // // private boolean value; // private int address; // // public WriteCoilResponse(int transectionId, int unitId, int address, boolean value) { // super(transectionId, unitId); // this.address = address; // this.value = value; // } // // public WriteCoilResponse() { // } // // public boolean getValue() { // return value; // } // // public void setValue(boolean value) { // this.value = value; // } // // public int getAddress() { // return address; // } // // public void setAddress(int address) { // this.address = address; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeShort(address); // out.writeShort(value ? 0xFF00 : 0x0000); // // } // // @Override // public int getPduCoreLength() { // return 4; // } // // @Override // public int getFunctionCode() { // return 0x05; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + address; // result = prime * result + (value ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // WriteCoilResponse other = (WriteCoilResponse) obj; // if (address != other.address) // return false; // if (value != other.value) // return false; // return true; // } // // @Override // public String toString() { // return "WriteCoilResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", address=" + address // + ", value=" + value + "]"; // } // // }
import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.UnexpectedResponseException; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import net.epsilony.utils.codec.modbus.reqres.WriteCoilResponse;
return 0x05; } public int getAddress() { return address; } public void setAddress(int address) { if (address < 0 || address > 0xffff) { throw new IllegalArgumentException(); } this.address = address; } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } @Override public void decodeRequestData(ByteBuf data) { setAddress(data.readUnsignedShort()); value = data.readUnsignedShort() == 0xFF00; } @Override public void decodeResponseData(ByteBuf data, ModbusResponse response) {
// Path: src/main/java/net/epsilony/utils/codec/modbus/UnexpectedResponseException.java // public class UnexpectedResponseException extends DecoderException { // // public UnexpectedResponseException() { // } // // public UnexpectedResponseException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedResponseException(String message) { // super(message); // } // // public UnexpectedResponseException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/WriteCoilResponse.java // public class WriteCoilResponse extends ModbusResponse { // // private boolean value; // private int address; // // public WriteCoilResponse(int transectionId, int unitId, int address, boolean value) { // super(transectionId, unitId); // this.address = address; // this.value = value; // } // // public WriteCoilResponse() { // } // // public boolean getValue() { // return value; // } // // public void setValue(boolean value) { // this.value = value; // } // // public int getAddress() { // return address; // } // // public void setAddress(int address) { // this.address = address; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeShort(address); // out.writeShort(value ? 0xFF00 : 0x0000); // // } // // @Override // public int getPduCoreLength() { // return 4; // } // // @Override // public int getFunctionCode() { // return 0x05; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + address; // result = prime * result + (value ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // WriteCoilResponse other = (WriteCoilResponse) obj; // if (address != other.address) // return false; // if (value != other.value) // return false; // return true; // } // // @Override // public String toString() { // return "WriteCoilResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", address=" + address // + ", value=" + value + "]"; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/func/WriteCoilFunction.java import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.UnexpectedResponseException; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import net.epsilony.utils.codec.modbus.reqres.WriteCoilResponse; return 0x05; } public int getAddress() { return address; } public void setAddress(int address) { if (address < 0 || address > 0xffff) { throw new IllegalArgumentException(); } this.address = address; } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } @Override public void decodeRequestData(ByteBuf data) { setAddress(data.readUnsignedShort()); value = data.readUnsignedShort() == 0xFF00; } @Override public void decodeResponseData(ByteBuf data, ModbusResponse response) {
WriteCoilResponse rResponse = (WriteCoilResponse) response;
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/func/WriteCoilFunction.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/UnexpectedResponseException.java // public class UnexpectedResponseException extends DecoderException { // // public UnexpectedResponseException() { // } // // public UnexpectedResponseException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedResponseException(String message) { // super(message); // } // // public UnexpectedResponseException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/WriteCoilResponse.java // public class WriteCoilResponse extends ModbusResponse { // // private boolean value; // private int address; // // public WriteCoilResponse(int transectionId, int unitId, int address, boolean value) { // super(transectionId, unitId); // this.address = address; // this.value = value; // } // // public WriteCoilResponse() { // } // // public boolean getValue() { // return value; // } // // public void setValue(boolean value) { // this.value = value; // } // // public int getAddress() { // return address; // } // // public void setAddress(int address) { // this.address = address; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeShort(address); // out.writeShort(value ? 0xFF00 : 0x0000); // // } // // @Override // public int getPduCoreLength() { // return 4; // } // // @Override // public int getFunctionCode() { // return 0x05; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + address; // result = prime * result + (value ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // WriteCoilResponse other = (WriteCoilResponse) obj; // if (address != other.address) // return false; // if (value != other.value) // return false; // return true; // } // // @Override // public String toString() { // return "WriteCoilResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", address=" + address // + ", value=" + value + "]"; // } // // }
import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.UnexpectedResponseException; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import net.epsilony.utils.codec.modbus.reqres.WriteCoilResponse;
return address; } public void setAddress(int address) { if (address < 0 || address > 0xffff) { throw new IllegalArgumentException(); } this.address = address; } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } @Override public void decodeRequestData(ByteBuf data) { setAddress(data.readUnsignedShort()); value = data.readUnsignedShort() == 0xFF00; } @Override public void decodeResponseData(ByteBuf data, ModbusResponse response) { WriteCoilResponse rResponse = (WriteCoilResponse) response; rResponse.setAddress(data.readUnsignedShort()); rResponse.setValue(data.readUnsignedShort() == 0xFF00); if (rResponse.getAddress() != address || rResponse.getValue() != value) {
// Path: src/main/java/net/epsilony/utils/codec/modbus/UnexpectedResponseException.java // public class UnexpectedResponseException extends DecoderException { // // public UnexpectedResponseException() { // } // // public UnexpectedResponseException(String message, Throwable cause) { // super(message, cause); // } // // public UnexpectedResponseException(String message) { // super(message); // } // // public UnexpectedResponseException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/WriteCoilResponse.java // public class WriteCoilResponse extends ModbusResponse { // // private boolean value; // private int address; // // public WriteCoilResponse(int transectionId, int unitId, int address, boolean value) { // super(transectionId, unitId); // this.address = address; // this.value = value; // } // // public WriteCoilResponse() { // } // // public boolean getValue() { // return value; // } // // public void setValue(boolean value) { // this.value = value; // } // // public int getAddress() { // return address; // } // // public void setAddress(int address) { // this.address = address; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeShort(address); // out.writeShort(value ? 0xFF00 : 0x0000); // // } // // @Override // public int getPduCoreLength() { // return 4; // } // // @Override // public int getFunctionCode() { // return 0x05; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + address; // result = prime * result + (value ? 1231 : 1237); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // WriteCoilResponse other = (WriteCoilResponse) obj; // if (address != other.address) // return false; // if (value != other.value) // return false; // return true; // } // // @Override // public String toString() { // return "WriteCoilResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", address=" + address // + ", value=" + value + "]"; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/func/WriteCoilFunction.java import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.UnexpectedResponseException; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import net.epsilony.utils.codec.modbus.reqres.WriteCoilResponse; return address; } public void setAddress(int address) { if (address < 0 || address > 0xffff) { throw new IllegalArgumentException(); } this.address = address; } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } @Override public void decodeRequestData(ByteBuf data) { setAddress(data.readUnsignedShort()); value = data.readUnsignedShort() == 0xFF00; } @Override public void decodeResponseData(ByteBuf data, ModbusResponse response) { WriteCoilResponse rResponse = (WriteCoilResponse) response; rResponse.setAddress(data.readUnsignedShort()); rResponse.setValue(data.readUnsignedShort() == 0xFF00); if (rResponse.getAddress() != address || rResponse.getValue() != value) {
throw new UnexpectedResponseException();
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/func/ReadRegistersFunctionTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse;
package net.epsilony.utils.codec.modbus.func; public class ReadRegistersFunctionTest { public ReadRegistersFunction mockFunction() { return new ReadRegistersFunction() { @Override
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/func/ReadRegistersFunctionTest.java import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; package net.epsilony.utils.codec.modbus.func; public class ReadRegistersFunctionTest { public ReadRegistersFunction mockFunction() { return new ReadRegistersFunction() { @Override
public void decodeResponseData(ByteBuf data, ModbusResponse response) {
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/func/ReadRegistersFunctionTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse;
package net.epsilony.utils.codec.modbus.func; public class ReadRegistersFunctionTest { public ReadRegistersFunction mockFunction() { return new ReadRegistersFunction() { @Override public void decodeResponseData(ByteBuf data, ModbusResponse response) { throw new UnsupportedOperationException(); } @Override
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/func/ReadRegistersFunctionTest.java import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; package net.epsilony.utils.codec.modbus.func; public class ReadRegistersFunctionTest { public ReadRegistersFunction mockFunction() { return new ReadRegistersFunction() { @Override public void decodeResponseData(ByteBuf data, ModbusResponse response) { throw new UnsupportedOperationException(); } @Override
protected void checkRegisterType(ModbusRegisterType registerType) {
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/func/ReadBooleanRegistersFunctionTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadBooleanRegistersResponse.java // public class ReadBooleanRegistersResponse extends ReadRegistersResponse { // // private TByteArrayList values; // // public ReadBooleanRegistersResponse() { // } // // public ReadBooleanRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, boolean[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.values = new TByteArrayList(values.length); // quantity = values.length; // for (boolean v : values) { // this.values.add((byte) (v ? 1 : 0)); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // this.quantity = quantity; // if (values == null) { // values = new TByteArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // values.fill(0, quantity, (byte) 0); // } // // public boolean getValue(int index) { // return values.get(index) != 0; // } // // public void setValue(int index, boolean value) { // values.set(index, value ? (byte) 1 : (byte) 0); // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(getPduCoreLength() - 1); // int mask = 1; // int dataByte = 0; // for (int i = 0; i < quantity; i++) { // if (getValue(i)) { // dataByte |= mask; // } // mask <<= 1; // if (mask == 0x100) { // out.writeByte(dataByte); // mask = 1; // dataByte = 0; // } // } // if (mask != 1) { // out.writeByte(dataByte); // } // // } // // @Override // public int getPduCoreLength() { // return 1 + (7 + quantity) / 8; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadBooleanRegistersResponse other = (ReadBooleanRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.COIL && registerType != ModbusRegisterType.DISCRETE_INPUT) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadBooleanRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // }
import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadBooleanRegistersResponse;
package net.epsilony.utils.codec.modbus.func; public class ReadBooleanRegistersFunctionTest { static class SampleData {
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadBooleanRegistersResponse.java // public class ReadBooleanRegistersResponse extends ReadRegistersResponse { // // private TByteArrayList values; // // public ReadBooleanRegistersResponse() { // } // // public ReadBooleanRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, boolean[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.values = new TByteArrayList(values.length); // quantity = values.length; // for (boolean v : values) { // this.values.add((byte) (v ? 1 : 0)); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // this.quantity = quantity; // if (values == null) { // values = new TByteArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // values.fill(0, quantity, (byte) 0); // } // // public boolean getValue(int index) { // return values.get(index) != 0; // } // // public void setValue(int index, boolean value) { // values.set(index, value ? (byte) 1 : (byte) 0); // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(getPduCoreLength() - 1); // int mask = 1; // int dataByte = 0; // for (int i = 0; i < quantity; i++) { // if (getValue(i)) { // dataByte |= mask; // } // mask <<= 1; // if (mask == 0x100) { // out.writeByte(dataByte); // mask = 1; // dataByte = 0; // } // } // if (mask != 1) { // out.writeByte(dataByte); // } // // } // // @Override // public int getPduCoreLength() { // return 1 + (7 + quantity) / 8; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadBooleanRegistersResponse other = (ReadBooleanRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.COIL && registerType != ModbusRegisterType.DISCRETE_INPUT) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadBooleanRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/func/ReadBooleanRegistersFunctionTest.java import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadBooleanRegistersResponse; package net.epsilony.utils.codec.modbus.func; public class ReadBooleanRegistersFunctionTest { static class SampleData {
ModbusRegisterType registerType;
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/func/ReadBooleanRegistersFunctionTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadBooleanRegistersResponse.java // public class ReadBooleanRegistersResponse extends ReadRegistersResponse { // // private TByteArrayList values; // // public ReadBooleanRegistersResponse() { // } // // public ReadBooleanRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, boolean[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.values = new TByteArrayList(values.length); // quantity = values.length; // for (boolean v : values) { // this.values.add((byte) (v ? 1 : 0)); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // this.quantity = quantity; // if (values == null) { // values = new TByteArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // values.fill(0, quantity, (byte) 0); // } // // public boolean getValue(int index) { // return values.get(index) != 0; // } // // public void setValue(int index, boolean value) { // values.set(index, value ? (byte) 1 : (byte) 0); // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(getPduCoreLength() - 1); // int mask = 1; // int dataByte = 0; // for (int i = 0; i < quantity; i++) { // if (getValue(i)) { // dataByte |= mask; // } // mask <<= 1; // if (mask == 0x100) { // out.writeByte(dataByte); // mask = 1; // dataByte = 0; // } // } // if (mask != 1) { // out.writeByte(dataByte); // } // // } // // @Override // public int getPduCoreLength() { // return 1 + (7 + quantity) / 8; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadBooleanRegistersResponse other = (ReadBooleanRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.COIL && registerType != ModbusRegisterType.DISCRETE_INPUT) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadBooleanRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // }
import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadBooleanRegistersResponse;
package net.epsilony.utils.codec.modbus.func; public class ReadBooleanRegistersFunctionTest { static class SampleData { ModbusRegisterType registerType; int startingAddress; boolean values[]; int[] buffer; ReadBooleanRegistersFunction function() { ReadBooleanRegistersFunction func = new ReadBooleanRegistersFunction(); func.setRegisterType(registerType); func.setStartingAddress(startingAddress); func.setQuantity(values.length); return func; } void write(ByteBuf buf) { for (int byteData : buffer) { buf.writeByte(byteData); } }
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadBooleanRegistersResponse.java // public class ReadBooleanRegistersResponse extends ReadRegistersResponse { // // private TByteArrayList values; // // public ReadBooleanRegistersResponse() { // } // // public ReadBooleanRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, boolean[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.values = new TByteArrayList(values.length); // quantity = values.length; // for (boolean v : values) { // this.values.add((byte) (v ? 1 : 0)); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // this.quantity = quantity; // if (values == null) { // values = new TByteArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // values.fill(0, quantity, (byte) 0); // } // // public boolean getValue(int index) { // return values.get(index) != 0; // } // // public void setValue(int index, boolean value) { // values.set(index, value ? (byte) 1 : (byte) 0); // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(getPduCoreLength() - 1); // int mask = 1; // int dataByte = 0; // for (int i = 0; i < quantity; i++) { // if (getValue(i)) { // dataByte |= mask; // } // mask <<= 1; // if (mask == 0x100) { // out.writeByte(dataByte); // mask = 1; // dataByte = 0; // } // } // if (mask != 1) { // out.writeByte(dataByte); // } // // } // // @Override // public int getPduCoreLength() { // return 1 + (7 + quantity) / 8; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadBooleanRegistersResponse other = (ReadBooleanRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.COIL && registerType != ModbusRegisterType.DISCRETE_INPUT) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadBooleanRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/func/ReadBooleanRegistersFunctionTest.java import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadBooleanRegistersResponse; package net.epsilony.utils.codec.modbus.func; public class ReadBooleanRegistersFunctionTest { static class SampleData { ModbusRegisterType registerType; int startingAddress; boolean values[]; int[] buffer; ReadBooleanRegistersFunction function() { ReadBooleanRegistersFunction func = new ReadBooleanRegistersFunction(); func.setRegisterType(registerType); func.setStartingAddress(startingAddress); func.setQuantity(values.length); return func; } void write(ByteBuf buf) { for (int byteData : buffer) { buf.writeByte(byteData); } }
public void assertResponse(ReadBooleanRegistersResponse response) {
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/handler/ModbusSlaveResponseEncoderTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.util.ReferenceCountUtil; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import io.netty.buffer.ByteBuf;
/* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.handler; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ModbusSlaveResponseEncoderTest { @Test public void test() { ModbusSlaveResponseEncoder encoder = new ModbusSlaveResponseEncoder(); EmbeddedChannel channel = new EmbeddedChannel(encoder);
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/handler/ModbusSlaveResponseEncoderTest.java import io.netty.channel.embedded.EmbeddedChannel; import io.netty.util.ReferenceCountUtil; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import io.netty.buffer.ByteBuf; /* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.handler; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ModbusSlaveResponseEncoderTest { @Test public void test() { ModbusSlaveResponseEncoder encoder = new ModbusSlaveResponseEncoder(); EmbeddedChannel channel = new EmbeddedChannel(encoder);
ModbusResponse response = new ModbusResponse() {
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/handler/ModbusSlaveResponseEncoderTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import io.netty.channel.embedded.EmbeddedChannel; import io.netty.util.ReferenceCountUtil; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import io.netty.buffer.ByteBuf;
assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 3, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes()); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } encoder.setWithCheckSum(true); for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 6, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes() - 2); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); }
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/handler/ModbusSlaveResponseEncoderTest.java import io.netty.channel.embedded.EmbeddedChannel; import io.netty.util.ReferenceCountUtil; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import io.netty.buffer.ByteBuf; assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 3, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes()); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } encoder.setWithCheckSum(true); for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 6, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes() - 2); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); }
int calcCrc = Utils.crc(buf, buf.readerIndex() - buffer.length, buffer.length);
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadBooleanRegistersResponse.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // }
import gnu.trove.list.array.TByteArrayList; import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.ModbusRegisterType;
/* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.reqres; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ReadBooleanRegistersResponse extends ReadRegistersResponse { private TByteArrayList values; public ReadBooleanRegistersResponse() { }
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadBooleanRegistersResponse.java import gnu.trove.list.array.TByteArrayList; import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.ModbusRegisterType; /* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.reqres; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ReadBooleanRegistersResponse extends ReadRegistersResponse { private TByteArrayList values; public ReadBooleanRegistersResponse() { }
public ReadBooleanRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType,
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadWordRegistersResponse.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // }
import gnu.trove.list.array.TShortArrayList; import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.ModbusRegisterType;
/* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.reqres; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ReadWordRegistersResponse extends ReadRegistersResponse { private TShortArrayList values; public ReadWordRegistersResponse() { }
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadWordRegistersResponse.java import gnu.trove.list.array.TShortArrayList; import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.ModbusRegisterType; /* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.reqres; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ReadWordRegistersResponse extends ReadRegistersResponse { private TShortArrayList values; public ReadWordRegistersResponse() { }
public ReadWordRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType,
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/ModbusClientMaster.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusRequest.java // public class ModbusRequest { // private ModbusFunction function; // private int transectionId; // private int unitId; // // public ModbusFunction getFunction() { // return function; // } // // public void setFunction(ModbusFunction function) { // this.function = function; // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public ModbusRequest(int transectionId, int unitId, ModbusFunction function) { // this.transectionId = transectionId; // this.unitId = unitId; // this.function = function; // } // // public ModbusRequest() { // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((function == null) ? 0 : function.hashCode()); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusRequest other = (ModbusRequest) obj; // if (function == null) { // if (other.function != null) // return false; // } else if (!function.equals(other.function)) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // @Override // public String toString() { // return "ModbusRequest [transectionId=" + transectionId + ", unitId=" + unitId + ", function=" + function + "]"; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import net.epsilony.utils.codec.modbus.reqres.ModbusRequest; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import java.rmi.ConnectException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantLock; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ChannelFactory;
private TransectionIdDispatcher transectionIdDispatcher = new SimpTransectionIdDispatcher(); private EventLoopGroup group; private int inetPort; private String innetAddress; private boolean keepAlive = true; private int socketTimeout = 5000; private int connectTimeout = 5000; private long requestLifeTime = 5000; private boolean tcpNoDelay = true; private ChannelFactory<Channel> channelFactory = new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new NioSocketChannel(); } }; protected ChannelFuture genConnectFuture() { initializer = new SimpModbusMasterChannelInitializer(); initializer.setRequestLifeTime(requestLifeTime); bootstrap = new Bootstrap(); bootstrap.group(group).channelFactory(channelFactory).handler(initializer) .option(ChannelOption.TCP_NODELAY, tcpNoDelay).option(ChannelOption.SO_KEEPALIVE, keepAlive) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout) .option(ChannelOption.SO_TIMEOUT, socketTimeout); return bootstrap.connect(innetAddress, inetPort); }
// Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusRequest.java // public class ModbusRequest { // private ModbusFunction function; // private int transectionId; // private int unitId; // // public ModbusFunction getFunction() { // return function; // } // // public void setFunction(ModbusFunction function) { // this.function = function; // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public ModbusRequest(int transectionId, int unitId, ModbusFunction function) { // this.transectionId = transectionId; // this.unitId = unitId; // this.function = function; // } // // public ModbusRequest() { // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((function == null) ? 0 : function.hashCode()); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusRequest other = (ModbusRequest) obj; // if (function == null) { // if (other.function != null) // return false; // } else if (!function.equals(other.function)) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // @Override // public String toString() { // return "ModbusRequest [transectionId=" + transectionId + ", unitId=" + unitId + ", function=" + function + "]"; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusClientMaster.java import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import net.epsilony.utils.codec.modbus.reqres.ModbusRequest; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import java.rmi.ConnectException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantLock; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ChannelFactory; private TransectionIdDispatcher transectionIdDispatcher = new SimpTransectionIdDispatcher(); private EventLoopGroup group; private int inetPort; private String innetAddress; private boolean keepAlive = true; private int socketTimeout = 5000; private int connectTimeout = 5000; private long requestLifeTime = 5000; private boolean tcpNoDelay = true; private ChannelFactory<Channel> channelFactory = new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new NioSocketChannel(); } }; protected ChannelFuture genConnectFuture() { initializer = new SimpModbusMasterChannelInitializer(); initializer.setRequestLifeTime(requestLifeTime); bootstrap = new Bootstrap(); bootstrap.group(group).channelFactory(channelFactory).handler(initializer) .option(ChannelOption.TCP_NODELAY, tcpNoDelay).option(ChannelOption.SO_KEEPALIVE, keepAlive) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout) .option(ChannelOption.SO_TIMEOUT, socketTimeout); return bootstrap.connect(innetAddress, inetPort); }
public CompletableFuture<ModbusResponse> request(ModbusRequest req) {
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/ModbusClientMaster.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusRequest.java // public class ModbusRequest { // private ModbusFunction function; // private int transectionId; // private int unitId; // // public ModbusFunction getFunction() { // return function; // } // // public void setFunction(ModbusFunction function) { // this.function = function; // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public ModbusRequest(int transectionId, int unitId, ModbusFunction function) { // this.transectionId = transectionId; // this.unitId = unitId; // this.function = function; // } // // public ModbusRequest() { // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((function == null) ? 0 : function.hashCode()); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusRequest other = (ModbusRequest) obj; // if (function == null) { // if (other.function != null) // return false; // } else if (!function.equals(other.function)) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // @Override // public String toString() { // return "ModbusRequest [transectionId=" + transectionId + ", unitId=" + unitId + ", function=" + function + "]"; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import net.epsilony.utils.codec.modbus.reqres.ModbusRequest; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import java.rmi.ConnectException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantLock; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ChannelFactory;
private TransectionIdDispatcher transectionIdDispatcher = new SimpTransectionIdDispatcher(); private EventLoopGroup group; private int inetPort; private String innetAddress; private boolean keepAlive = true; private int socketTimeout = 5000; private int connectTimeout = 5000; private long requestLifeTime = 5000; private boolean tcpNoDelay = true; private ChannelFactory<Channel> channelFactory = new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new NioSocketChannel(); } }; protected ChannelFuture genConnectFuture() { initializer = new SimpModbusMasterChannelInitializer(); initializer.setRequestLifeTime(requestLifeTime); bootstrap = new Bootstrap(); bootstrap.group(group).channelFactory(channelFactory).handler(initializer) .option(ChannelOption.TCP_NODELAY, tcpNoDelay).option(ChannelOption.SO_KEEPALIVE, keepAlive) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout) .option(ChannelOption.SO_TIMEOUT, socketTimeout); return bootstrap.connect(innetAddress, inetPort); }
// Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusRequest.java // public class ModbusRequest { // private ModbusFunction function; // private int transectionId; // private int unitId; // // public ModbusFunction getFunction() { // return function; // } // // public void setFunction(ModbusFunction function) { // this.function = function; // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public ModbusRequest(int transectionId, int unitId, ModbusFunction function) { // this.transectionId = transectionId; // this.unitId = unitId; // this.function = function; // } // // public ModbusRequest() { // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((function == null) ? 0 : function.hashCode()); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusRequest other = (ModbusRequest) obj; // if (function == null) { // if (other.function != null) // return false; // } else if (!function.equals(other.function)) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // @Override // public String toString() { // return "ModbusRequest [transectionId=" + transectionId + ", unitId=" + unitId + ", function=" + function + "]"; // } // // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusClientMaster.java import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import net.epsilony.utils.codec.modbus.reqres.ModbusRequest; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; import java.rmi.ConnectException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.ReentrantLock; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ChannelFactory; private TransectionIdDispatcher transectionIdDispatcher = new SimpTransectionIdDispatcher(); private EventLoopGroup group; private int inetPort; private String innetAddress; private boolean keepAlive = true; private int socketTimeout = 5000; private int connectTimeout = 5000; private long requestLifeTime = 5000; private boolean tcpNoDelay = true; private ChannelFactory<Channel> channelFactory = new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new NioSocketChannel(); } }; protected ChannelFuture genConnectFuture() { initializer = new SimpModbusMasterChannelInitializer(); initializer.setRequestLifeTime(requestLifeTime); bootstrap = new Bootstrap(); bootstrap.group(group).channelFactory(channelFactory).handler(initializer) .option(ChannelOption.TCP_NODELAY, tcpNoDelay).option(ChannelOption.SO_KEEPALIVE, keepAlive) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout) .option(ChannelOption.SO_TIMEOUT, socketTimeout); return bootstrap.connect(innetAddress, inetPort); }
public CompletableFuture<ModbusResponse> request(ModbusRequest req) {
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/func/ModbusFunction.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse;
/* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.func; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public interface ModbusFunction { String getName(); int getCode(); void decodeRequestData(ByteBuf data);
// Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/func/ModbusFunction.java import io.netty.buffer.ByteBuf; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; /* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.func; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public interface ModbusFunction { String getName(); int getCode(); void decodeRequestData(ByteBuf data);
void decodeResponseData(ByteBuf data, ModbusResponse response);
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/handler/ModbusMasterRequestEncoder.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusRequest.java // public class ModbusRequest { // private ModbusFunction function; // private int transectionId; // private int unitId; // // public ModbusFunction getFunction() { // return function; // } // // public void setFunction(ModbusFunction function) { // this.function = function; // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public ModbusRequest(int transectionId, int unitId, ModbusFunction function) { // this.transectionId = transectionId; // this.unitId = unitId; // this.function = function; // } // // public ModbusRequest() { // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((function == null) ? 0 : function.hashCode()); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusRequest other = (ModbusRequest) obj; // if (function == null) { // if (other.function != null) // return false; // } else if (!function.equals(other.function)) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // @Override // public String toString() { // return "ModbusRequest [transectionId=" + transectionId + ", unitId=" + unitId + ", function=" + function + "]"; // } // // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusRequest;
/* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.handler; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ModbusMasterRequestEncoder extends MessageToByteEncoder<ModbusRequest> { private boolean withCheckSum = false; public ModbusMasterRequestEncoder() { } public boolean isWithCheckSum() { return withCheckSum; } public void setWithCheckSum(boolean withCheckSum) { this.withCheckSum = withCheckSum; } @Override protected void encode(ChannelHandlerContext ctx, ModbusRequest msg, ByteBuf out) throws Exception { int from = out.writerIndex(); out.writeShort(msg.getTransectionId()); out.writeShort(0); out.writeShort(2 + msg.getFunction().getRequestDataLength()); out.writeByte(msg.getUnitId()); out.writeByte(msg.getFunction().getCode()); msg.getFunction().encodeRequestData(out); if (withCheckSum) { out.writeShort(checkSum(out, from)); } } private int checkSum(ByteBuf out, int from) {
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusRequest.java // public class ModbusRequest { // private ModbusFunction function; // private int transectionId; // private int unitId; // // public ModbusFunction getFunction() { // return function; // } // // public void setFunction(ModbusFunction function) { // this.function = function; // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public ModbusRequest(int transectionId, int unitId, ModbusFunction function) { // this.transectionId = transectionId; // this.unitId = unitId; // this.function = function; // } // // public ModbusRequest() { // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((function == null) ? 0 : function.hashCode()); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusRequest other = (ModbusRequest) obj; // if (function == null) { // if (other.function != null) // return false; // } else if (!function.equals(other.function)) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // @Override // public String toString() { // return "ModbusRequest [transectionId=" + transectionId + ", unitId=" + unitId + ", function=" + function + "]"; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/handler/ModbusMasterRequestEncoder.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusRequest; /* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.handler; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ModbusMasterRequestEncoder extends MessageToByteEncoder<ModbusRequest> { private boolean withCheckSum = false; public ModbusMasterRequestEncoder() { } public boolean isWithCheckSum() { return withCheckSum; } public void setWithCheckSum(boolean withCheckSum) { this.withCheckSum = withCheckSum; } @Override protected void encode(ChannelHandlerContext ctx, ModbusRequest msg, ByteBuf out) throws Exception { int from = out.writerIndex(); out.writeShort(msg.getTransectionId()); out.writeShort(0); out.writeShort(2 + msg.getFunction().getRequestDataLength()); out.writeByte(msg.getUnitId()); out.writeByte(msg.getFunction().getCode()); msg.getFunction().encodeRequestData(out); if (withCheckSum) { out.writeShort(checkSum(out, from)); } } private int checkSum(ByteBuf out, int from) {
return Utils.crc(out, from, out.writerIndex() - from);
epsilony/codec-modbus
src/main/java/net/epsilony/utils/codec/modbus/handler/ModbusSlaveResponseEncoder.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse;
/* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.handler; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ModbusSlaveResponseEncoder extends MessageToByteEncoder<ModbusResponse> { boolean withCheckSum; public boolean isWithCheckSum() { return withCheckSum; } public void setWithCheckSum(boolean withCheckSum) { this.withCheckSum = withCheckSum; } @Override protected void encode(ChannelHandlerContext ctx, ModbusResponse msg, ByteBuf out) throws Exception { int from = out.writerIndex(); msg.encode(out); if (withCheckSum) {
// Path: src/main/java/net/epsilony/utils/codec/modbus/Utils.java // public class Utils { // public static int crc(ByteBuf byteBuf, int start, int numBytes) { // int polynomial = 0xA001; // int crc = 0xFFFF; // for (int i = start; i < start + numBytes; i++) { // byte b = byteBuf.getByte(i); // int low = (crc & 0xFF) ^ (b & 0xFF); // crc &= (0xFF00); // crc |= (low); // for (int j = 0; j < 8; j++) { // int t = crc & 0x01; // crc >>= 1; // if (t == 0) { // continue; // } // crc ^= polynomial; // } // } // int first = (crc & 0xFF) << 8; // crc = (crc & 0xFF00) >> 8 | first; // return crc; // } // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ModbusResponse.java // public abstract class ModbusResponse { // protected int transectionId; // protected int unitId; // // public ModbusResponse(int transectionId, int unitId) { // this.transectionId = transectionId; // this.unitId = unitId; // } // // public ModbusResponse() { // } // // public int getTransectionId() { // return transectionId; // } // // public void setTransectionId(int transectionId) { // this.transectionId = transectionId; // } // // public int getUnitId() { // return unitId; // } // // public void setUnitId(int unitId) { // this.unitId = unitId; // } // // public abstract int getFunctionCode(); // // public void encode(ByteBuf out) { // out.writeShort(transectionId); // out.writeShort(0); // out.writeShort(getPduCoreLength() + 2); // out.writeByte(unitId); // out.writeByte(getFunctionCode()); // writePduCore(out); // } // // public abstract void writePduCore(ByteBuf out); // // public abstract int getPduCoreLength(); // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + getFunctionCode(); // result = prime * result + transectionId; // result = prime * result + unitId; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // ModbusResponse other = (ModbusResponse) obj; // if (getFunctionCode() != other.getFunctionCode()) // return false; // if (transectionId != other.transectionId) // return false; // if (unitId != other.unitId) // return false; // return true; // } // // } // Path: src/main/java/net/epsilony/utils/codec/modbus/handler/ModbusSlaveResponseEncoder.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import net.epsilony.utils.codec.modbus.Utils; import net.epsilony.utils.codec.modbus.reqres.ModbusResponse; /* * * The MIT License (MIT) * * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.epsilony.utils.codec.modbus.handler; /** * @author <a href="mailto:epsilony@epsilony.net">Man YUAN</a> * */ public class ModbusSlaveResponseEncoder extends MessageToByteEncoder<ModbusResponse> { boolean withCheckSum; public boolean isWithCheckSum() { return withCheckSum; } public void setWithCheckSum(boolean withCheckSum) { this.withCheckSum = withCheckSum; } @Override protected void encode(ChannelHandlerContext ctx, ModbusResponse msg, ByteBuf out) throws Exception { int from = out.writerIndex(); msg.encode(out); if (withCheckSum) {
out.writeShort(Utils.crc(out, from, out.writerIndex() - from));
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/func/ReadWordRegistersFunctionTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadWordRegistersResponse.java // public class ReadWordRegistersResponse extends ReadRegistersResponse { // private TShortArrayList values; // // public ReadWordRegistersResponse() { // } // // public ReadWordRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, int[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.quantity = values.length; // this.values = new TShortArrayList(values.length); // for (int v : values) { // this.values.add((short) v); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // if (null == values) { // values = new TShortArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // this.quantity = quantity; // values.fill(0, quantity, (short) 0); // } // // public void setValue(int index, int value) { // values.set(index, (short) value); // } // // public int getValue(int offset) { // return values.get(offset) & 0xFFFF; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(2 * quantity); // for (int i = 0; i < quantity; i++) { // out.writeShort(getValue(i)); // } // } // // @Override // public int getPduCoreLength() { // return 1 + 2 * quantity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadWordRegistersResponse other = (ReadWordRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.INPUT && registerType != ModbusRegisterType.HOLDING) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadWordRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // }
import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadWordRegistersResponse;
package net.epsilony.utils.codec.modbus.func; public class ReadWordRegistersFunctionTest { static class SampleData {
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadWordRegistersResponse.java // public class ReadWordRegistersResponse extends ReadRegistersResponse { // private TShortArrayList values; // // public ReadWordRegistersResponse() { // } // // public ReadWordRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, int[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.quantity = values.length; // this.values = new TShortArrayList(values.length); // for (int v : values) { // this.values.add((short) v); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // if (null == values) { // values = new TShortArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // this.quantity = quantity; // values.fill(0, quantity, (short) 0); // } // // public void setValue(int index, int value) { // values.set(index, (short) value); // } // // public int getValue(int offset) { // return values.get(offset) & 0xFFFF; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(2 * quantity); // for (int i = 0; i < quantity; i++) { // out.writeShort(getValue(i)); // } // } // // @Override // public int getPduCoreLength() { // return 1 + 2 * quantity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadWordRegistersResponse other = (ReadWordRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.INPUT && registerType != ModbusRegisterType.HOLDING) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadWordRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/func/ReadWordRegistersFunctionTest.java import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadWordRegistersResponse; package net.epsilony.utils.codec.modbus.func; public class ReadWordRegistersFunctionTest { static class SampleData {
ModbusRegisterType registerType;
epsilony/codec-modbus
src/test/java/net/epsilony/utils/codec/modbus/func/ReadWordRegistersFunctionTest.java
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadWordRegistersResponse.java // public class ReadWordRegistersResponse extends ReadRegistersResponse { // private TShortArrayList values; // // public ReadWordRegistersResponse() { // } // // public ReadWordRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, int[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.quantity = values.length; // this.values = new TShortArrayList(values.length); // for (int v : values) { // this.values.add((short) v); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // if (null == values) { // values = new TShortArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // this.quantity = quantity; // values.fill(0, quantity, (short) 0); // } // // public void setValue(int index, int value) { // values.set(index, (short) value); // } // // public int getValue(int offset) { // return values.get(offset) & 0xFFFF; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(2 * quantity); // for (int i = 0; i < quantity; i++) { // out.writeShort(getValue(i)); // } // } // // @Override // public int getPduCoreLength() { // return 1 + 2 * quantity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadWordRegistersResponse other = (ReadWordRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.INPUT && registerType != ModbusRegisterType.HOLDING) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadWordRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // }
import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadWordRegistersResponse;
package net.epsilony.utils.codec.modbus.func; public class ReadWordRegistersFunctionTest { static class SampleData { ModbusRegisterType registerType; int startingAddress; int values[]; int[] buffer; ReadWordRegistersFunction function() { ReadWordRegistersFunction func = new ReadWordRegistersFunction(); func.setRegisterType(registerType); func.setStartingAddress(startingAddress); func.setQuantity(values.length); return func; } void write(ByteBuf buf) { for (int byteData : buffer) { buf.writeByte(byteData); } }
// Path: src/main/java/net/epsilony/utils/codec/modbus/ModbusRegisterType.java // public enum ModbusRegisterType { // COIL, DISCRETE_INPUT, HOLDING, INPUT // } // // Path: src/main/java/net/epsilony/utils/codec/modbus/reqres/ReadWordRegistersResponse.java // public class ReadWordRegistersResponse extends ReadRegistersResponse { // private TShortArrayList values; // // public ReadWordRegistersResponse() { // } // // public ReadWordRegistersResponse(int transectionId, int unitId, ModbusRegisterType registerType, // int startingAddress, int[] values) { // super(transectionId, unitId, registerType, startingAddress); // this.quantity = values.length; // this.values = new TShortArrayList(values.length); // for (int v : values) { // this.values.add((short) v); // } // } // // @Override // public void setQuantityAndAllocate(int quantity) { // if (null == values) { // values = new TShortArrayList(quantity); // } else { // values.clear(); // values.ensureCapacity(quantity); // } // this.quantity = quantity; // values.fill(0, quantity, (short) 0); // } // // public void setValue(int index, int value) { // values.set(index, (short) value); // } // // public int getValue(int offset) { // return values.get(offset) & 0xFFFF; // } // // @Override // public void writePduCore(ByteBuf out) { // out.writeByte(2 * quantity); // for (int i = 0; i < quantity; i++) { // out.writeShort(getValue(i)); // } // } // // @Override // public int getPduCoreLength() { // return 1 + 2 * quantity; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = super.hashCode(); // result = prime * result + ((values == null) ? 0 : values.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (!super.equals(obj)) // return false; // if (getClass() != obj.getClass()) // return false; // ReadWordRegistersResponse other = (ReadWordRegistersResponse) obj; // if (values == null) { // if (other.values != null) // return false; // } else if (!values.equals(other.values)) // return false; // return true; // } // // @Override // protected void checkRegisterType(ModbusRegisterType registerType) { // if (registerType != ModbusRegisterType.INPUT && registerType != ModbusRegisterType.HOLDING) { // throw new IllegalArgumentException(); // } // // } // // @Override // public String toString() { // return "ReadWordRegistersResponse [transectionId=" + transectionId + ", unitId=" + unitId + ", registerType=" // + registerType + ", startingAddress=" + startingAddress + ", quantity=" + quantity + ", values=" // + values + "]"; // } // // } // Path: src/test/java/net/epsilony/utils/codec/modbus/func/ReadWordRegistersFunctionTest.java import static org.junit.Assert.assertEquals; import java.util.Random; import org.junit.Test; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.epsilony.utils.codec.modbus.ModbusRegisterType; import net.epsilony.utils.codec.modbus.reqres.ReadWordRegistersResponse; package net.epsilony.utils.codec.modbus.func; public class ReadWordRegistersFunctionTest { static class SampleData { ModbusRegisterType registerType; int startingAddress; int values[]; int[] buffer; ReadWordRegistersFunction function() { ReadWordRegistersFunction func = new ReadWordRegistersFunction(); func.setRegisterType(registerType); func.setStartingAddress(startingAddress); func.setQuantity(values.length); return func; } void write(ByteBuf buf) { for (int byteData : buffer) { buf.writeByte(byteData); } }
public void assertResponse(ReadWordRegistersResponse response) {
annefried/sitent
de.uni-saarland.coli.sitent/src/main/java/sitent/util/WordNetUtils.java
// Path: de.uni-saarland.coli.sitent/src/main/java/sitent/types/ClassificationAnnotation.java // public class ClassificationAnnotation extends Annotation { // /** @generated // * @ordered // */ // @SuppressWarnings ("hiding") // public final static int typeIndexID = JCasRegistry.register(ClassificationAnnotation.class); // /** @generated // * @ordered // */ // @SuppressWarnings ("hiding") // public final static int type = typeIndexID; // /** @generated // * @return index of the type // */ // @Override // public int getTypeIndexID() {return typeIndexID;} // // /** Never called. Disable default constructor // * @generated */ // protected ClassificationAnnotation() {/* intentionally empty block */} // // /** Internal - constructor used by generator // * @generated // * @param addr low level Feature Structure reference // * @param type the type of this Feature Structure // */ // public ClassificationAnnotation(int addr, TOP_Type type) { // super(addr, type); // readObject(); // } // // /** @generated // * @param jcas JCas to which this Feature Structure belongs // */ // public ClassificationAnnotation(JCas jcas) { // super(jcas); // readObject(); // } // // /** @generated // * @param jcas JCas to which this Feature Structure belongs // * @param begin offset to the begin spot in the SofA // * @param end offset to the end spot in the SofA // */ // public ClassificationAnnotation(JCas jcas, int begin, int end) { // super(jcas); // setBegin(begin); // setEnd(end); // readObject(); // } // // /** // * <!-- begin-user-doc --> // * Write your own initialization here // * <!-- end-user-doc --> // * // * @generated modifiable // */ // private void readObject() {/*default - does nothing empty block */} // // // // //*--------------* // //* Feature: features // // /** getter for features - gets // * @generated // * @return value of the feature // */ // public FSList getFeatures() { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_features == null) // jcasType.jcas.throwFeatMissing("features", "sitent.types.ClassificationAnnotation"); // return (FSList)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_features)));} // // /** setter for features - sets // * @generated // * @param v value to set into the feature // */ // public void setFeatures(FSList v) { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_features == null) // jcasType.jcas.throwFeatMissing("features", "sitent.types.ClassificationAnnotation"); // jcasType.ll_cas.ll_setRefValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_features, jcasType.ll_cas.ll_getFSRef(v));} // // // //*--------------* // //* Feature: task // // /** getter for task - gets identifier of this classification task (in case items for more than one task are marked on the same JCas, this can be used to filter). Here, different features are extracted for "NP" and for "VERB". // * @generated // * @return value of the feature // */ // public String getTask() { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_task == null) // jcasType.jcas.throwFeatMissing("task", "sitent.types.ClassificationAnnotation"); // return jcasType.ll_cas.ll_getStringValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_task);} // // /** setter for task - sets identifier of this classification task (in case items for more than one task are marked on the same JCas, this can be used to filter). Here, different features are extracted for "NP" and for "VERB". // * @generated // * @param v value to set into the feature // */ // public void setTask(String v) { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_task == null) // jcasType.jcas.throwFeatMissing("task", "sitent.types.ClassificationAnnotation"); // jcasType.ll_cas.ll_setStringValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_task, v);} // }
import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.uima.jcas.JCas; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import edu.mit.jwi.Dictionary; import edu.mit.jwi.IDictionary; import edu.mit.jwi.item.IIndexWord; import edu.mit.jwi.item.ISynset; import edu.mit.jwi.item.ISynsetID; import edu.mit.jwi.item.IWord; import edu.mit.jwi.item.IWordID; import edu.mit.jwi.item.POS; import edu.mit.jwi.item.Pointer; import edu.mit.jwi.morph.WordnetStemmer; import sitent.types.ClassificationAnnotation;
case 'J': case 'j': pos = POS.ADJECTIVE; break; case 'N': case 'n': pos = POS.NOUN; break; case 'V': case 'v': pos = POS.VERB; break; case 'R': case 'r': if (postag.charAt(1) == 'B' || postag.charAt(1) == 'b') pos = POS.ADVERB; break; } return pos; } /** * @author afried, Annemarie Friedrich * * WordNet based features, use Most Frequent Sense heuristic. * Adapted from code by Nils Reiter. * * @param token * @param classAnnot */
// Path: de.uni-saarland.coli.sitent/src/main/java/sitent/types/ClassificationAnnotation.java // public class ClassificationAnnotation extends Annotation { // /** @generated // * @ordered // */ // @SuppressWarnings ("hiding") // public final static int typeIndexID = JCasRegistry.register(ClassificationAnnotation.class); // /** @generated // * @ordered // */ // @SuppressWarnings ("hiding") // public final static int type = typeIndexID; // /** @generated // * @return index of the type // */ // @Override // public int getTypeIndexID() {return typeIndexID;} // // /** Never called. Disable default constructor // * @generated */ // protected ClassificationAnnotation() {/* intentionally empty block */} // // /** Internal - constructor used by generator // * @generated // * @param addr low level Feature Structure reference // * @param type the type of this Feature Structure // */ // public ClassificationAnnotation(int addr, TOP_Type type) { // super(addr, type); // readObject(); // } // // /** @generated // * @param jcas JCas to which this Feature Structure belongs // */ // public ClassificationAnnotation(JCas jcas) { // super(jcas); // readObject(); // } // // /** @generated // * @param jcas JCas to which this Feature Structure belongs // * @param begin offset to the begin spot in the SofA // * @param end offset to the end spot in the SofA // */ // public ClassificationAnnotation(JCas jcas, int begin, int end) { // super(jcas); // setBegin(begin); // setEnd(end); // readObject(); // } // // /** // * <!-- begin-user-doc --> // * Write your own initialization here // * <!-- end-user-doc --> // * // * @generated modifiable // */ // private void readObject() {/*default - does nothing empty block */} // // // // //*--------------* // //* Feature: features // // /** getter for features - gets // * @generated // * @return value of the feature // */ // public FSList getFeatures() { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_features == null) // jcasType.jcas.throwFeatMissing("features", "sitent.types.ClassificationAnnotation"); // return (FSList)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_features)));} // // /** setter for features - sets // * @generated // * @param v value to set into the feature // */ // public void setFeatures(FSList v) { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_features == null) // jcasType.jcas.throwFeatMissing("features", "sitent.types.ClassificationAnnotation"); // jcasType.ll_cas.ll_setRefValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_features, jcasType.ll_cas.ll_getFSRef(v));} // // // //*--------------* // //* Feature: task // // /** getter for task - gets identifier of this classification task (in case items for more than one task are marked on the same JCas, this can be used to filter). Here, different features are extracted for "NP" and for "VERB". // * @generated // * @return value of the feature // */ // public String getTask() { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_task == null) // jcasType.jcas.throwFeatMissing("task", "sitent.types.ClassificationAnnotation"); // return jcasType.ll_cas.ll_getStringValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_task);} // // /** setter for task - sets identifier of this classification task (in case items for more than one task are marked on the same JCas, this can be used to filter). Here, different features are extracted for "NP" and for "VERB". // * @generated // * @param v value to set into the feature // */ // public void setTask(String v) { // if (ClassificationAnnotation_Type.featOkTst && ((ClassificationAnnotation_Type)jcasType).casFeat_task == null) // jcasType.jcas.throwFeatMissing("task", "sitent.types.ClassificationAnnotation"); // jcasType.ll_cas.ll_setStringValue(addr, ((ClassificationAnnotation_Type)jcasType).casFeatCode_task, v);} // } // Path: de.uni-saarland.coli.sitent/src/main/java/sitent/util/WordNetUtils.java import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.uima.jcas.JCas; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import edu.mit.jwi.Dictionary; import edu.mit.jwi.IDictionary; import edu.mit.jwi.item.IIndexWord; import edu.mit.jwi.item.ISynset; import edu.mit.jwi.item.ISynsetID; import edu.mit.jwi.item.IWord; import edu.mit.jwi.item.IWordID; import edu.mit.jwi.item.POS; import edu.mit.jwi.item.Pointer; import edu.mit.jwi.morph.WordnetStemmer; import sitent.types.ClassificationAnnotation; case 'J': case 'j': pos = POS.ADJECTIVE; break; case 'N': case 'n': pos = POS.NOUN; break; case 'V': case 'v': pos = POS.VERB; break; case 'R': case 'r': if (postag.charAt(1) == 'B' || postag.charAt(1) == 'b') pos = POS.ADVERB; break; } return pos; } /** * @author afried, Annemarie Friedrich * * WordNet based features, use Most Frequent Sense heuristic. * Adapted from code by Nils Reiter. * * @param token * @param classAnnot */
public static void setWordNetFeatures(Token token, ClassificationAnnotation classAnnot, JCas jCas,
annefried/sitent
de.uni-saarland.coli.sitent/src/main/java/sitent/classifiers/Experiment.java
// Path: de.uni-saarland.coli.sitent/src/main/java/sitent/util/WekaUtils.java // public class WekaUtils { // // /** // * Removes all instances that have one of the given values. // * // * @param data // * Array of Instances (e.g., folds). // * @param attribute The name of the attribute according to which is filtered. // * @param values Instances where the attribute takes one of these values are to be removed. // * @return The filtered set of Instances, again an array of Instances. // * @throws Exception // */ // public static Instances[] removeWithValues(Instances[] data, String attribute, String[] values) throws Exception { // // String valueRegex = ""; // for (String v : values) { // valueRegex += v + "|"; // } // valueRegex = valueRegex.substring(0, valueRegex.length() - 1); // // List<Integer> indicesToRemove = new LinkedList<Integer>(); // // find indices of values that should be removed // Attribute classAttr = data[0].attribute(attribute); // int classAttrIndex = classAttr.index(); // // for (int i = 0; i < classAttr.numValues(); i++) { // String value = classAttr.value(i); // if (value.matches(valueRegex)) { // indicesToRemove.add(i); // } // } // if (!indicesToRemove.isEmpty()) { // int[] indices = new int[indicesToRemove.size()]; // for (int i = 0; i < indicesToRemove.size(); i++) { // indices[i] = indicesToRemove.get(i); // } // // RemoveWithValues removeValuesFilter = new RemoveWithValues(); // // at RemoveWithValuesFilter for whatever reason the indices // // need to be increased by 1. But that's not the case for the // // other filters. // removeValuesFilter.setAttributeIndex(new Integer(classAttrIndex + 1).toString()); // removeValuesFilter.setNominalIndicesArr(indices); // removeValuesFilter.setInputFormat(data[0]); // for (int i = 0; i < data.length; i++) { // data[i] = Filter.useFilter(data[i], removeValuesFilter); // } // } // // return data; // // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; import sitent.util.WekaUtils; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.BayesNet; import weka.classifiers.functions.Logistic; import weka.classifiers.rules.ZeroR; import weka.classifiers.trees.J48; import weka.classifiers.trees.RandomForest; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Copy; import weka.filters.unsupervised.attribute.MergeManyValues; import weka.filters.unsupervised.attribute.Remove;
*/ private Instances[] prepareData(Instances[] data) throws Exception { // Need to use batch filtering to make sure all folds get the same // filtering: Filter.useFilter(...) log.info(setting + "\t" + "Setting class attribute and filtering instances..."); log.info(setting + "\t" + "number of attributes at beginning: " + data[0].numAttributes()); log.info(setting + "\t" + "size of class values " + classValues.length); log.info(setting + "\t" + "Number of folds: " + data.length); // for applyModel case: read in arff used for training model Set<String> keepFeatures = new HashSet<String>(); if (setting.equals("applyModel")) { System.out.println("Working Directory = " + System.getProperty("user.dir")); BufferedReader reader = new BufferedReader(new FileReader(trainDataArff)); Instances keepFeaturesInst = new Instances(reader); log.info(setting + "\tattributes in training: " + keepFeaturesInst.numAttributes()); for (int a = 0; a < keepFeaturesInst.numAttributes(); a++) { keepFeatures.add(keepFeaturesInst.attribute(a).name()); } } List<Integer> indicesToRemove; int[] indices; // Filter out cases without a situation entity label or where one of the // other layers did not get a meaningful label. if (PARAM_USE_FULL_SITUATIONS) {
// Path: de.uni-saarland.coli.sitent/src/main/java/sitent/util/WekaUtils.java // public class WekaUtils { // // /** // * Removes all instances that have one of the given values. // * // * @param data // * Array of Instances (e.g., folds). // * @param attribute The name of the attribute according to which is filtered. // * @param values Instances where the attribute takes one of these values are to be removed. // * @return The filtered set of Instances, again an array of Instances. // * @throws Exception // */ // public static Instances[] removeWithValues(Instances[] data, String attribute, String[] values) throws Exception { // // String valueRegex = ""; // for (String v : values) { // valueRegex += v + "|"; // } // valueRegex = valueRegex.substring(0, valueRegex.length() - 1); // // List<Integer> indicesToRemove = new LinkedList<Integer>(); // // find indices of values that should be removed // Attribute classAttr = data[0].attribute(attribute); // int classAttrIndex = classAttr.index(); // // for (int i = 0; i < classAttr.numValues(); i++) { // String value = classAttr.value(i); // if (value.matches(valueRegex)) { // indicesToRemove.add(i); // } // } // if (!indicesToRemove.isEmpty()) { // int[] indices = new int[indicesToRemove.size()]; // for (int i = 0; i < indicesToRemove.size(); i++) { // indices[i] = indicesToRemove.get(i); // } // // RemoveWithValues removeValuesFilter = new RemoveWithValues(); // // at RemoveWithValuesFilter for whatever reason the indices // // need to be increased by 1. But that's not the case for the // // other filters. // removeValuesFilter.setAttributeIndex(new Integer(classAttrIndex + 1).toString()); // removeValuesFilter.setNominalIndicesArr(indices); // removeValuesFilter.setInputFormat(data[0]); // for (int i = 0; i < data.length; i++) { // data[i] = Filter.useFilter(data[i], removeValuesFilter); // } // } // // return data; // // } // // } // Path: de.uni-saarland.coli.sitent/src/main/java/sitent/classifiers/Experiment.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; import sitent.util.WekaUtils; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.BayesNet; import weka.classifiers.functions.Logistic; import weka.classifiers.rules.ZeroR; import weka.classifiers.trees.J48; import weka.classifiers.trees.RandomForest; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Copy; import weka.filters.unsupervised.attribute.MergeManyValues; import weka.filters.unsupervised.attribute.Remove; */ private Instances[] prepareData(Instances[] data) throws Exception { // Need to use batch filtering to make sure all folds get the same // filtering: Filter.useFilter(...) log.info(setting + "\t" + "Setting class attribute and filtering instances..."); log.info(setting + "\t" + "number of attributes at beginning: " + data[0].numAttributes()); log.info(setting + "\t" + "size of class values " + classValues.length); log.info(setting + "\t" + "Number of folds: " + data.length); // for applyModel case: read in arff used for training model Set<String> keepFeatures = new HashSet<String>(); if (setting.equals("applyModel")) { System.out.println("Working Directory = " + System.getProperty("user.dir")); BufferedReader reader = new BufferedReader(new FileReader(trainDataArff)); Instances keepFeaturesInst = new Instances(reader); log.info(setting + "\tattributes in training: " + keepFeaturesInst.numAttributes()); for (int a = 0; a < keepFeaturesInst.numAttributes(); a++) { keepFeatures.add(keepFeaturesInst.attribute(a).name()); } } List<Integer> indicesToRemove; int[] indices; // Filter out cases without a situation entity label or where one of the // other layers did not get a meaningful label. if (PARAM_USE_FULL_SITUATIONS) {
data = WekaUtils.removeWithValues(data, "class_sitent_type", new String[] { "THE-DUMMY-VALUE" });
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/ScheduleModule.java
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // }
import static com.google.common.base.Preconditions.checkArgument; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.matcher.Matchers; import com.google.inject.spi.TypeListener; import de.skuzzle.inject.async.guice.DefaultBinding; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.ExecutionScope; import de.skuzzle.inject.async.schedule.annotation.ScheduledScope; import de.skuzzle.inject.proxy.ScopedProxyBinder;
package de.skuzzle.inject.async.schedule; /** * Purely used internal to install context related bindings into the main module. * * @author Simon Taddiken */ public final class ScheduleModule extends AbstractModule { private final ScheduleProperties scheduleProperties; /** * This constructor is only allowed to be called from within the {@link GuiceAsync} * class. * * @param principal Restricts construction, not allowed to be null. * @param scheduleProperties Additional settings to be passed to the scheduling * features. */
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // } // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleModule.java import static com.google.common.base.Preconditions.checkArgument; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.matcher.Matchers; import com.google.inject.spi.TypeListener; import de.skuzzle.inject.async.guice.DefaultBinding; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.ExecutionScope; import de.skuzzle.inject.async.schedule.annotation.ScheduledScope; import de.skuzzle.inject.proxy.ScopedProxyBinder; package de.skuzzle.inject.async.schedule; /** * Purely used internal to install context related bindings into the main module. * * @author Simon Taddiken */ public final class ScheduleModule extends AbstractModule { private final ScheduleProperties scheduleProperties; /** * This constructor is only allowed to be called from within the {@link GuiceAsync} * class. * * @param principal Restricts construction, not allowed to be null. * @param scheduleProperties Additional settings to be passed to the scheduling * features. */
public ScheduleModule(GuiceAsync principal, ScheduleProperties scheduleProperties) {
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/InjectedMethodInvocationTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/InjectedMethodInvocation.java // public class InjectedMethodInvocation { // // private final Injector injector; // private final Object self; // private final Method method; // // private InjectedMethodInvocation(Injector injector, Object self, Method method) { // this.injector = injector; // this.self = self; // this.method = method; // } // // /** // * Creates an {@linkplain InjectedMethodInvocation} object that is able to invoke the // * provided static method. The actual parameters for the invocation will be looked up // * using the given injector. // * <p> // * You can call {@link InjectedMethodInvocation#proceed()} to invoke the method. // * </p> // * // * @param method A static method. // * @param injector The injector which is queried for actual method arguments. // * @return The MethodInvocation. // */ // public static InjectedMethodInvocation forStatic(Method method, Injector injector) { // checkArgument(method != null); // checkArgument(Modifier.isStatic(method.getModifiers())); // checkArgument(injector != null); // return new InjectedMethodInvocation(injector, null, method); // } // // /** // * Creates a {@linkplain InjectedMethodInvocation} object that is able to invoke the // * provided method. The actual parameters for the invocation will be looked up using // * the given injector. This method supports static methods by leaving the self // * parameter null. // * <p> // * You can call {@link InjectedMethodInvocation#proceed()} to invoke the method. // * </p> // * // * @param method A method. // * @param self The object on which the method will be called. May be null for invoking // * static methods. // * @param injector The injector which is queried for actual method arguments. // * @return The MethodInvocation. // */ // public static InjectedMethodInvocation forMethod(Method method, Object self, // Injector injector) { // checkArgument(method != null, "Method must not be null"); // checkArgument(self != null ^ Modifier.isStatic(method.getModifiers()), // "Method must either be static or a reference object must be passed"); // checkArgument(injector != null, "Injector must not be null"); // return new InjectedMethodInvocation(injector, self, method); // } // // private Object[] getArguments() { // final Object[] result = new Object[this.method.getParameterCount()]; // final Errors errors = new Errors(this.method); // for (int i = 0; i < result.length; ++i) { // final Class<?> type = this.method.getParameterTypes()[i]; // final Annotation[] annotations = this.method.getParameterAnnotations()[i]; // final Annotation bindingAnnotation = Annotations.findBindingAnnotation( // errors, this.method, annotations); // // final Key<?> key; // if (bindingAnnotation == null) { // key = Key.get(type); // } else { // key = Key.get(type, bindingAnnotation); // } // result[i] = this.injector.getInstance(key); // } // errors.throwProvisionExceptionIfErrorsExist(); // return result; // } // // /** // * Actually executes the method. // * // * @return The result of the method invocation. // * @throws Throwable If method invocation failed or the method itself threw an // * exception. // */ // public Object proceed() throws Throwable { // final boolean accessible = this.method.isAccessible(); // try { // this.method.setAccessible(true); // return this.method.invoke(this.self, getArguments()); // } finally { // this.method.setAccessible(accessible); // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("self", self) // .add("method", method) // .toString(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import org.junit.Before; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; import de.skuzzle.inject.async.schedule.InjectedMethodInvocation;
public void setUp() throws Exception { invokedStatic = false; this.invoked = false; this.injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Integer.class).toInstance(5); bind(String.class).annotatedWith(Names.named("foo")).toInstance("foobar"); } }); } public void nonStaticMethod(Integer i, @Named("foo") String s) { assertEquals(5, i.intValue()); assertEquals("foobar", s); this.invoked = true; } public static void staticMethod(Integer i, @Named("foo") String s) { assertEquals(5, i.intValue()); assertEquals("foobar", s); invokedStatic = true; } @Test(expected = IllegalArgumentException.class) public void testForStaticMethodWithSelf() throws Exception { final Method method = getClass().getMethod("staticMethod", Integer.class, String.class);
// Path: src/main/java/de/skuzzle/inject/async/schedule/InjectedMethodInvocation.java // public class InjectedMethodInvocation { // // private final Injector injector; // private final Object self; // private final Method method; // // private InjectedMethodInvocation(Injector injector, Object self, Method method) { // this.injector = injector; // this.self = self; // this.method = method; // } // // /** // * Creates an {@linkplain InjectedMethodInvocation} object that is able to invoke the // * provided static method. The actual parameters for the invocation will be looked up // * using the given injector. // * <p> // * You can call {@link InjectedMethodInvocation#proceed()} to invoke the method. // * </p> // * // * @param method A static method. // * @param injector The injector which is queried for actual method arguments. // * @return The MethodInvocation. // */ // public static InjectedMethodInvocation forStatic(Method method, Injector injector) { // checkArgument(method != null); // checkArgument(Modifier.isStatic(method.getModifiers())); // checkArgument(injector != null); // return new InjectedMethodInvocation(injector, null, method); // } // // /** // * Creates a {@linkplain InjectedMethodInvocation} object that is able to invoke the // * provided method. The actual parameters for the invocation will be looked up using // * the given injector. This method supports static methods by leaving the self // * parameter null. // * <p> // * You can call {@link InjectedMethodInvocation#proceed()} to invoke the method. // * </p> // * // * @param method A method. // * @param self The object on which the method will be called. May be null for invoking // * static methods. // * @param injector The injector which is queried for actual method arguments. // * @return The MethodInvocation. // */ // public static InjectedMethodInvocation forMethod(Method method, Object self, // Injector injector) { // checkArgument(method != null, "Method must not be null"); // checkArgument(self != null ^ Modifier.isStatic(method.getModifiers()), // "Method must either be static or a reference object must be passed"); // checkArgument(injector != null, "Injector must not be null"); // return new InjectedMethodInvocation(injector, self, method); // } // // private Object[] getArguments() { // final Object[] result = new Object[this.method.getParameterCount()]; // final Errors errors = new Errors(this.method); // for (int i = 0; i < result.length; ++i) { // final Class<?> type = this.method.getParameterTypes()[i]; // final Annotation[] annotations = this.method.getParameterAnnotations()[i]; // final Annotation bindingAnnotation = Annotations.findBindingAnnotation( // errors, this.method, annotations); // // final Key<?> key; // if (bindingAnnotation == null) { // key = Key.get(type); // } else { // key = Key.get(type, bindingAnnotation); // } // result[i] = this.injector.getInstance(key); // } // errors.throwProvisionExceptionIfErrorsExist(); // return result; // } // // /** // * Actually executes the method. // * // * @return The result of the method invocation. // * @throws Throwable If method invocation failed or the method itself threw an // * exception. // */ // public Object proceed() throws Throwable { // final boolean accessible = this.method.isAccessible(); // try { // this.method.setAccessible(true); // return this.method.invoke(this.self, getArguments()); // } finally { // this.method.setAccessible(accessible); // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("self", self) // .add("method", method) // .toString(); // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/InjectedMethodInvocationTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import org.junit.Before; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.name.Named; import com.google.inject.name.Names; import de.skuzzle.inject.async.schedule.InjectedMethodInvocation; public void setUp() throws Exception { invokedStatic = false; this.invoked = false; this.injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Integer.class).toInstance(5); bind(String.class).annotatedWith(Names.named("foo")).toInstance("foobar"); } }); } public void nonStaticMethod(Integer i, @Named("foo") String s) { assertEquals(5, i.intValue()); assertEquals("foobar", s); this.invoked = true; } public static void staticMethod(Integer i, @Named("foo") String s) { assertEquals(5, i.intValue()); assertEquals("foobar", s); invokedStatic = true; } @Test(expected = IllegalArgumentException.class) public void testForStaticMethodWithSelf() throws Exception { final Method method = getClass().getMethod("staticMethod", Integer.class, String.class);
InjectedMethodInvocation.forMethod(method, this, this.injector);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/DefaultExceptionHandlerTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/DefaultExceptionHandler.java // class DefaultExceptionHandler implements ExceptionHandler { // // private static final Logger LOG = LoggerFactory.getLogger(DefaultExceptionHandler.class); // // @Override // public void onException(Exception exception) { // if (ScheduledContextHolder.isContextActive()) { // final ScheduledContext ctx = ScheduledContextHolder.getContext(); // LOG.error("Unexpected error while executing a scheduled method. Context: {}", // ctx, exception); // } else { // LOG.error("Unexpected error occurred while executing scheduled method. " // + "Note: there is no ScheduledContext information available. " // + "Either the TriggerStrategy in place does not support scoped " // + "executions or it may be buggy.", // exception); // } // } // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // }
import static org.mockito.Mockito.mock; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.DefaultExceptionHandler; import de.skuzzle.inject.async.schedule.ScheduledContext;
package de.skuzzle.inject.async.schedule; public class DefaultExceptionHandlerTest { private final DefaultExceptionHandler subject = new DefaultExceptionHandler(); @Before public void setup() { if (ScheduledContextHolder.isContextActive()) { ScheduledContextHolder.pop(); } } @Test public void testHandleWithContext() throws Exception {
// Path: src/main/java/de/skuzzle/inject/async/schedule/DefaultExceptionHandler.java // class DefaultExceptionHandler implements ExceptionHandler { // // private static final Logger LOG = LoggerFactory.getLogger(DefaultExceptionHandler.class); // // @Override // public void onException(Exception exception) { // if (ScheduledContextHolder.isContextActive()) { // final ScheduledContext ctx = ScheduledContextHolder.getContext(); // LOG.error("Unexpected error while executing a scheduled method. Context: {}", // ctx, exception); // } else { // LOG.error("Unexpected error occurred while executing scheduled method. " // + "Note: there is no ScheduledContext information available. " // + "Either the TriggerStrategy in place does not support scoped " // + "executions or it may be buggy.", // exception); // } // } // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // Path: src/test/java/de/skuzzle/inject/async/schedule/DefaultExceptionHandlerTest.java import static org.mockito.Mockito.mock; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.DefaultExceptionHandler; import de.skuzzle.inject.async.schedule.ScheduledContext; package de.skuzzle.inject.async.schedule; public class DefaultExceptionHandlerTest { private final DefaultExceptionHandler subject = new DefaultExceptionHandler(); @Before public void setup() { if (ScheduledContextHolder.isContextActive()) { ScheduledContextHolder.pop(); } } @Test public void testHandleWithContext() throws Exception {
ScheduledContextHolder.push(mock(ScheduledContext.class));
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/trigger/DelayTriggerTest.java
// Path: src/main/java/de/skuzzle/inject/async/guice/DefaultFeatures.java // public enum DefaultFeatures implements Feature { // /** This feature enables handling of the {@link Async} annotation. */ // ASYNC { // // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // binder.install(new AsyncModule(principal)); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // final ExecutorService executor = injector.getInstance(Keys.DEFAULT_EXECUTOR_KEY); // if (!Shutdown.executor(executor, timeout, timeUnit)) { // LOG.warn("There are still active tasks lingering in default executor after shutdown. Wait time: {} {}", // timeout, timeUnit); // return false; // } // return true; // } // }, // /** // * This feature enables handling of the {@link Scheduled} annotation. You may also use // * an instance of {@link ScheduleFeature} instead of this instance (but better do not // * provide both). // */ // SCHEDULE { // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // ScheduleFeature.DEFAULT.installModuleTo(binder, principal); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // return ScheduleFeature.DEFAULT.cleanupExecutor(injector, timeout, timeUnit); // } // }; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultFeatures.class); // // } // // Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // }
import org.junit.Test; import com.google.inject.Guice; import de.skuzzle.inject.async.guice.DefaultFeatures; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled;
package de.skuzzle.inject.async.schedule.trigger; public class DelayTriggerTest { static { System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug"); } @Test public void testCallExceptionHandler() throws Exception { final AbstractMethodHolder methods = new AbstractMethodHolder() { @Override @Scheduled @DelayedTrigger(1000) @OnError(MockExceptionHandler.class) protected void throwingException() { super.throwingException(); } };
// Path: src/main/java/de/skuzzle/inject/async/guice/DefaultFeatures.java // public enum DefaultFeatures implements Feature { // /** This feature enables handling of the {@link Async} annotation. */ // ASYNC { // // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // binder.install(new AsyncModule(principal)); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // final ExecutorService executor = injector.getInstance(Keys.DEFAULT_EXECUTOR_KEY); // if (!Shutdown.executor(executor, timeout, timeUnit)) { // LOG.warn("There are still active tasks lingering in default executor after shutdown. Wait time: {} {}", // timeout, timeUnit); // return false; // } // return true; // } // }, // /** // * This feature enables handling of the {@link Scheduled} annotation. You may also use // * an instance of {@link ScheduleFeature} instead of this instance (but better do not // * provide both). // */ // SCHEDULE { // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // ScheduleFeature.DEFAULT.installModuleTo(binder, principal); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // return ScheduleFeature.DEFAULT.cleanupExecutor(injector, timeout, timeUnit); // } // }; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultFeatures.class); // // } // // Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/trigger/DelayTriggerTest.java import org.junit.Test; import com.google.inject.Guice; import de.skuzzle.inject.async.guice.DefaultFeatures; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; package de.skuzzle.inject.async.schedule.trigger; public class DelayTriggerTest { static { System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug"); } @Test public void testCallExceptionHandler() throws Exception { final AbstractMethodHolder methods = new AbstractMethodHolder() { @Override @Scheduled @DelayedTrigger(1000) @OnError(MockExceptionHandler.class) protected void throwingException() { super.throwingException(); } };
Guice.createInjector(GuiceAsync.createModuleWithFeatures(DefaultFeatures.SCHEDULE), methods);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/trigger/DelayTriggerTest.java
// Path: src/main/java/de/skuzzle/inject/async/guice/DefaultFeatures.java // public enum DefaultFeatures implements Feature { // /** This feature enables handling of the {@link Async} annotation. */ // ASYNC { // // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // binder.install(new AsyncModule(principal)); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // final ExecutorService executor = injector.getInstance(Keys.DEFAULT_EXECUTOR_KEY); // if (!Shutdown.executor(executor, timeout, timeUnit)) { // LOG.warn("There are still active tasks lingering in default executor after shutdown. Wait time: {} {}", // timeout, timeUnit); // return false; // } // return true; // } // }, // /** // * This feature enables handling of the {@link Scheduled} annotation. You may also use // * an instance of {@link ScheduleFeature} instead of this instance (but better do not // * provide both). // */ // SCHEDULE { // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // ScheduleFeature.DEFAULT.installModuleTo(binder, principal); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // return ScheduleFeature.DEFAULT.cleanupExecutor(injector, timeout, timeUnit); // } // }; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultFeatures.class); // // } // // Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // }
import org.junit.Test; import com.google.inject.Guice; import de.skuzzle.inject.async.guice.DefaultFeatures; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled;
package de.skuzzle.inject.async.schedule.trigger; public class DelayTriggerTest { static { System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug"); } @Test public void testCallExceptionHandler() throws Exception { final AbstractMethodHolder methods = new AbstractMethodHolder() { @Override @Scheduled @DelayedTrigger(1000) @OnError(MockExceptionHandler.class) protected void throwingException() { super.throwingException(); } };
// Path: src/main/java/de/skuzzle/inject/async/guice/DefaultFeatures.java // public enum DefaultFeatures implements Feature { // /** This feature enables handling of the {@link Async} annotation. */ // ASYNC { // // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // binder.install(new AsyncModule(principal)); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // final ExecutorService executor = injector.getInstance(Keys.DEFAULT_EXECUTOR_KEY); // if (!Shutdown.executor(executor, timeout, timeUnit)) { // LOG.warn("There are still active tasks lingering in default executor after shutdown. Wait time: {} {}", // timeout, timeUnit); // return false; // } // return true; // } // }, // /** // * This feature enables handling of the {@link Scheduled} annotation. You may also use // * an instance of {@link ScheduleFeature} instead of this instance (but better do not // * provide both). // */ // SCHEDULE { // @Override // public void installModuleTo(Binder binder, GuiceAsync principal) { // ScheduleFeature.DEFAULT.installModuleTo(binder, principal); // } // // @Override // public boolean cleanupExecutor(Injector injector, long timeout, TimeUnit timeUnit) { // return ScheduleFeature.DEFAULT.cleanupExecutor(injector, timeout, timeUnit); // } // }; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultFeatures.class); // // } // // Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/trigger/DelayTriggerTest.java import org.junit.Test; import com.google.inject.Guice; import de.skuzzle.inject.async.guice.DefaultFeatures; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; package de.skuzzle.inject.async.schedule.trigger; public class DelayTriggerTest { static { System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug"); } @Test public void testCallExceptionHandler() throws Exception { final AbstractMethodHolder methods = new AbstractMethodHolder() { @Override @Scheduled @DelayedTrigger(1000) @OnError(MockExceptionHandler.class) protected void throwingException() { super.throwingException(); } };
Guice.createInjector(GuiceAsync.createModuleWithFeatures(DefaultFeatures.SCHEDULE), methods);
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/annotation/OnError.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Provider; import de.skuzzle.inject.async.schedule.ExceptionHandler;
package de.skuzzle.inject.async.schedule.annotation; /** * Can be put on a method which is annotated with {@link Scheduled} to additionally * specify an exception handler. Please note that the exception handler instance is * obtained from the injector in early stages, <em>before</em> initially scheduling the * method. If you intend to inject {@link ScheduledScope} or {@link ExecutionScope} * objects into the exception handler, you need to bind them as * <a href="https://github.com/skuzzle/guice-scoped-proxy-extension">scoped proxy</a> or * inject a {@link Provider} * * @author Simon Taddiken * @see Scheduled * @since 0.3.0 * @see ExceptionHandler */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnError { /** * The type of the {@link ExceptionHandler} to use for the scheduled method. * * @return The type. */
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // } // Path: src/main/java/de/skuzzle/inject/async/schedule/annotation/OnError.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Provider; import de.skuzzle.inject.async.schedule.ExceptionHandler; package de.skuzzle.inject.async.schedule.annotation; /** * Can be put on a method which is annotated with {@link Scheduled} to additionally * specify an exception handler. Please note that the exception handler instance is * obtained from the injector in early stages, <em>before</em> initially scheduling the * method. If you intend to inject {@link ScheduledScope} or {@link ExecutionScope} * objects into the exception handler, you need to bind them as * <a href="https://github.com/skuzzle/guice-scoped-proxy-extension">scoped proxy</a> or * inject a {@link Provider} * * @author Simon Taddiken * @see Scheduled * @since 0.3.0 * @see ExceptionHandler */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnError { /** * The type of the {@link ExceptionHandler} to use for the scheduled method. * * @return The type. */
Class<? extends ExceptionHandler> value();
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/trigger/SimpleTriggerStrategy.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // }
import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.SimpleTrigger;
package de.skuzzle.inject.async.schedule.trigger; /** * TriggerStrategy that handles the {@link SimpleTrigger} annotation for defining simple * periodic executions. * * @author Simon Taddiken */ public class SimpleTriggerStrategy implements TriggerStrategy { @Override public Class<SimpleTrigger> getTriggerType() { return SimpleTrigger.class; } @Override
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/SimpleTriggerStrategy.java import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.SimpleTrigger; package de.skuzzle.inject.async.schedule.trigger; /** * TriggerStrategy that handles the {@link SimpleTrigger} annotation for defining simple * periodic executions. * * @author Simon Taddiken */ public class SimpleTriggerStrategy implements TriggerStrategy { @Override public Class<SimpleTrigger> getTriggerType() { return SimpleTrigger.class; } @Override
public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) {
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/trigger/SimpleTriggerStrategy.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // }
import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.SimpleTrigger;
package de.skuzzle.inject.async.schedule.trigger; /** * TriggerStrategy that handles the {@link SimpleTrigger} annotation for defining simple * periodic executions. * * @author Simon Taddiken */ public class SimpleTriggerStrategy implements TriggerStrategy { @Override public Class<SimpleTrigger> getTriggerType() { return SimpleTrigger.class; } @Override
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/SimpleTriggerStrategy.java import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.SimpleTrigger; package de.skuzzle.inject.async.schedule.trigger; /** * TriggerStrategy that handles the {@link SimpleTrigger} annotation for defining simple * periodic executions. * * @author Simon Taddiken */ public class SimpleTriggerStrategy implements TriggerStrategy { @Override public Class<SimpleTrigger> getTriggerType() { return SimpleTrigger.class; } @Override
public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) {
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/trigger/DelayedTriggerStrategy.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // }
import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger;
package de.skuzzle.inject.async.schedule.trigger; /** * Handles the {@link DelayedTrigger}. * * @author Simon Taddiken * @since 0.2.0 */ public class DelayedTriggerStrategy implements TriggerStrategy { @Override public Class<DelayedTrigger> getTriggerType() { return DelayedTrigger.class; } @Override
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/DelayedTriggerStrategy.java import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; package de.skuzzle.inject.async.schedule.trigger; /** * Handles the {@link DelayedTrigger}. * * @author Simon Taddiken * @since 0.2.0 */ public class DelayedTriggerStrategy implements TriggerStrategy { @Override public Class<DelayedTrigger> getTriggerType() { return DelayedTrigger.class; } @Override
public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) {
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/trigger/DelayedTriggerStrategy.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // }
import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger;
package de.skuzzle.inject.async.schedule.trigger; /** * Handles the {@link DelayedTrigger}. * * @author Simon Taddiken * @since 0.2.0 */ public class DelayedTriggerStrategy implements TriggerStrategy { @Override public Class<DelayedTrigger> getTriggerType() { return DelayedTrigger.class; } @Override
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/DelayedTriggerStrategy.java import static com.google.common.base.Preconditions.checkArgument; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; package de.skuzzle.inject.async.schedule.trigger; /** * Handles the {@link DelayedTrigger}. * * @author Simon Taddiken * @since 0.2.0 */ public class DelayedTriggerStrategy implements TriggerStrategy { @Override public Class<DelayedTrigger> getTriggerType() { return DelayedTrigger.class; } @Override
public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) {
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/SchedulingServiceImpl.java
// Path: src/main/java/de/skuzzle/inject/async/guice/Keys.java // public final class Keys { // // /** Fall back key if the user did not bind any scheduled executor service. */ // static final Key<? extends ScheduledExecutorService> DEFAULT_SCHEDULER_KEY = Key // .get(ScheduledExecutorService.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any exception handlder. */ // private static final Key<? extends ExceptionHandler> DEFAULT_EXCEPTION_HANDLER_KEY = Key // .get(ExceptionHandler.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any executor service. */ // static final Key<? extends ExecutorService> DEFAULT_EXECUTOR_KEY = Key // .get(ExecutorService.class, DefaultBinding.class); // // private Keys() { // // hidden ctor // } // // /** // * Finds the key of the {@link ExceptionHandler} to use for the given method. // * // * @param method The method to find the key for. // * @return The exception handler key. // */ // public static Key<? extends ExceptionHandler> getExceptionHandler(Method method) { // // TODO: must support BindingAnnotations // final OnError onError = method.getAnnotation(OnError.class); // if (onError != null) { // return Key.get(onError.value()); // } // return DEFAULT_EXCEPTION_HANDLER_KEY; // } // // /** // * Finds the key of the {@link ExecutorService} to use to execute the given method. // * // * @param method The method to find the key for. // * @return The ExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ExecutorService> getExecutorKey(Method method) { // final Class<? extends ExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Executor.class)) { // type = method.getAnnotation(Executor.class).value(); // executorSpecified = true; // } else { // type = ExecutorService.class; // } // return (Key<? extends ExecutorService>) createKey(type, method, // DEFAULT_EXECUTOR_KEY, executorSpecified); // } // // /** // * Finds the key of the {@link ScheduledExecutorService} to use to execute the given // * method. // * // * @param method the method to find the key for. // * @return The ScheduledExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ScheduledExecutorService> getSchedulerKey(Method method) { // final Class<? extends ScheduledExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Scheduler.class)) { // type = method.getAnnotation(Scheduler.class).value(); // executorSpecified = true; // } else { // type = ScheduledExecutorService.class; // } // return (Key<? extends ScheduledExecutorService>) createKey(type, method, // DEFAULT_SCHEDULER_KEY, executorSpecified); // } // // private static Key<?> createKey( // Class<?> type, // Method method, // Key<?> defaultKey, // boolean typeGiven) { // // final Errors errors = new Errors(method); // final Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, method, method.getAnnotations()); // errors.throwConfigurationExceptionIfErrorsExist(); // final Key<?> key; // if (bindingAnnotation == null && typeGiven) { // key = Key.get(type); // } else if (bindingAnnotation == null) { // key = defaultKey; // } else { // key = Key.get(type, bindingAnnotation); // } // return key; // } // }
import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ScheduledExecutorService; import javax.inject.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Injector; import com.google.inject.Key; import de.skuzzle.inject.async.guice.Keys; import de.skuzzle.inject.async.schedule.annotation.Scheduled;
this.injector = injector; this.registry = registry; this.manuallyStarted = new ArrayList<>(); } @Override public void scheduleMemberMethod(Method method, Object self) { scheduleMethod(method, self); } @Override public void scheduleStaticMethod(Method method) { scheduleMethod(method, null); } @Override public void startManualScheduling() { synchronized (manuallyStarted) { manuallyStarted.forEach(ManuallyStarted::scheduleNow); manuallyStarted.clear(); } } private void scheduleMethod(Method method, Object self) { if (!method.isAnnotationPresent(Scheduled.class)) { return; } final Annotation trigger = Annotations.findTriggerAnnotation(method); LOG.trace("Method '{}' is elligible for scheduling. Trigger is: {}", method, trigger);
// Path: src/main/java/de/skuzzle/inject/async/guice/Keys.java // public final class Keys { // // /** Fall back key if the user did not bind any scheduled executor service. */ // static final Key<? extends ScheduledExecutorService> DEFAULT_SCHEDULER_KEY = Key // .get(ScheduledExecutorService.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any exception handlder. */ // private static final Key<? extends ExceptionHandler> DEFAULT_EXCEPTION_HANDLER_KEY = Key // .get(ExceptionHandler.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any executor service. */ // static final Key<? extends ExecutorService> DEFAULT_EXECUTOR_KEY = Key // .get(ExecutorService.class, DefaultBinding.class); // // private Keys() { // // hidden ctor // } // // /** // * Finds the key of the {@link ExceptionHandler} to use for the given method. // * // * @param method The method to find the key for. // * @return The exception handler key. // */ // public static Key<? extends ExceptionHandler> getExceptionHandler(Method method) { // // TODO: must support BindingAnnotations // final OnError onError = method.getAnnotation(OnError.class); // if (onError != null) { // return Key.get(onError.value()); // } // return DEFAULT_EXCEPTION_HANDLER_KEY; // } // // /** // * Finds the key of the {@link ExecutorService} to use to execute the given method. // * // * @param method The method to find the key for. // * @return The ExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ExecutorService> getExecutorKey(Method method) { // final Class<? extends ExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Executor.class)) { // type = method.getAnnotation(Executor.class).value(); // executorSpecified = true; // } else { // type = ExecutorService.class; // } // return (Key<? extends ExecutorService>) createKey(type, method, // DEFAULT_EXECUTOR_KEY, executorSpecified); // } // // /** // * Finds the key of the {@link ScheduledExecutorService} to use to execute the given // * method. // * // * @param method the method to find the key for. // * @return The ScheduledExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ScheduledExecutorService> getSchedulerKey(Method method) { // final Class<? extends ScheduledExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Scheduler.class)) { // type = method.getAnnotation(Scheduler.class).value(); // executorSpecified = true; // } else { // type = ScheduledExecutorService.class; // } // return (Key<? extends ScheduledExecutorService>) createKey(type, method, // DEFAULT_SCHEDULER_KEY, executorSpecified); // } // // private static Key<?> createKey( // Class<?> type, // Method method, // Key<?> defaultKey, // boolean typeGiven) { // // final Errors errors = new Errors(method); // final Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, method, method.getAnnotations()); // errors.throwConfigurationExceptionIfErrorsExist(); // final Key<?> key; // if (bindingAnnotation == null && typeGiven) { // key = Key.get(type); // } else if (bindingAnnotation == null) { // key = defaultKey; // } else { // key = Key.get(type, bindingAnnotation); // } // return key; // } // } // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulingServiceImpl.java import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ScheduledExecutorService; import javax.inject.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Injector; import com.google.inject.Key; import de.skuzzle.inject.async.guice.Keys; import de.skuzzle.inject.async.schedule.annotation.Scheduled; this.injector = injector; this.registry = registry; this.manuallyStarted = new ArrayList<>(); } @Override public void scheduleMemberMethod(Method method, Object self) { scheduleMethod(method, self); } @Override public void scheduleStaticMethod(Method method) { scheduleMethod(method, null); } @Override public void startManualScheduling() { synchronized (manuallyStarted) { manuallyStarted.forEach(ManuallyStarted::scheduleNow); manuallyStarted.clear(); } } private void scheduleMethod(Method method, Object self) { if (!method.isAnnotationPresent(Scheduled.class)) { return; } final Annotation trigger = Annotations.findTriggerAnnotation(method); LOG.trace("Method '{}' is elligible for scheduling. Trigger is: {}", method, trigger);
final Key<? extends ScheduledExecutorService> key = Keys.getSchedulerKey(method);
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/guice/ScheduleFeature.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleModule.java // public final class ScheduleModule extends AbstractModule { // // private final ScheduleProperties scheduleProperties; // // /** // * This constructor is only allowed to be called from within the {@link GuiceAsync} // * class. // * // * @param principal Restricts construction, not allowed to be null. // * @param scheduleProperties Additional settings to be passed to the scheduling // * features. // */ // public ScheduleModule(GuiceAsync principal, ScheduleProperties scheduleProperties) { // checkArgument(principal != null, // "instantiating this module is not allowed. Use the class " // + "GuiceAsync to enable asynchronous method support."); // // checkArgument(scheduleProperties != null, "scheduleProperties must not be null"); // this.scheduleProperties = scheduleProperties; // } // // @Override // protected void configure() { // bind(TriggerStrategyRegistry.class) // .to(SpiTriggerStrategyRegistryImpl.class) // .in(Singleton.class); // // final SchedulingService schedulingService = new SchedulingServiceImpl( // scheduleProperties, // getProvider(Injector.class), // getProvider(TriggerStrategyRegistry.class)); // bind(SchedulingService.class).toInstance(schedulingService); // // final TypeListener scheduleListener = new SchedulerTypeListener(schedulingService); // requestInjection(scheduleListener); // bindListener(Matchers.any(), scheduleListener); // // // Execution scope // final Provider<Map<String, Object>> executionMap = () -> ScheduledContextHolder // .getContext().getExecution().getProperties(); // bindScope(ExecutionScope.class, MapBasedScope.withMapSupplier(executionMap)); // // // ScheduledScope // final Provider<Map<String, Object>> scheduledMap = () -> ScheduledContextHolder // .getContext().getProperties(); // bindScope(ScheduledScope.class, MapBasedScope.withMapSupplier(scheduledMap)); // // ScopedProxyBinder.using(binder()) // .bind(ScheduledContext.class) // .toProvider(ScheduledContextHolder::getContext); // // ScopedProxyBinder.using(binder()) // .bind(ExecutionContext.class) // .toProvider( // () -> ScheduledContextHolder.getContext().getExecution()); // } // // @Provides // @Singleton // @DefaultBinding // ScheduledExecutorService provideScheduler( // @DefaultBinding ThreadFactory threadFactory) { // final int cores = Runtime.getRuntime().availableProcessors(); // return Executors.newScheduledThreadPool(cores, threadFactory); // } // // @Provides // @Singleton // @DefaultBinding // ExceptionHandler provideDefaultExceptionHandler() { // return new DefaultExceptionHandler(); // } // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleProperties.java // public final class ScheduleProperties { // // private boolean enableAutoScheduling = true; // // private ScheduleProperties() { // // } // // /** // * Returns the default properties. // * // * @return A new instance with defaults set. // */ // public static ScheduleProperties defaultProperties() { // return new ScheduleProperties(); // } // // /** // * Disables the behavior of automatic method scheduling. If automatic scheduling is // * disabled, methods are only actually be scheduled with their // * {@link ScheduledExecutorService} after manually calling // * {@link SchedulingService#startManualScheduling()}. // * // * @return This instance for method chaining. // */ // public ScheduleProperties disableAutoScheduling() { // this.enableAutoScheduling = false; // return this; // } // // boolean isAutoSchedulingEnabled() { // return enableAutoScheduling; // } // }
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.inject.Binder; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.ScheduleModule; import de.skuzzle.inject.async.schedule.ScheduleProperties;
package de.skuzzle.inject.async.guice; /** * Specialized {@link Feature} that allows customization of the scheduling behavior by * providing a custom instance of {@link ScheduleProperties}. * <p> * * @author Simon Taddiken * @since 2.0.0 * @see DefaultFeatures#SCHEDULE */ public class ScheduleFeature implements Feature { private static final Logger LOG = LoggerFactory.getLogger(ScheduleFeature.class); /** * The default instance. Enables the same behavior as * {@link DefaultFeatures#SCHEDULE}. */ public static final ScheduleFeature DEFAULT = ScheduleFeature
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleModule.java // public final class ScheduleModule extends AbstractModule { // // private final ScheduleProperties scheduleProperties; // // /** // * This constructor is only allowed to be called from within the {@link GuiceAsync} // * class. // * // * @param principal Restricts construction, not allowed to be null. // * @param scheduleProperties Additional settings to be passed to the scheduling // * features. // */ // public ScheduleModule(GuiceAsync principal, ScheduleProperties scheduleProperties) { // checkArgument(principal != null, // "instantiating this module is not allowed. Use the class " // + "GuiceAsync to enable asynchronous method support."); // // checkArgument(scheduleProperties != null, "scheduleProperties must not be null"); // this.scheduleProperties = scheduleProperties; // } // // @Override // protected void configure() { // bind(TriggerStrategyRegistry.class) // .to(SpiTriggerStrategyRegistryImpl.class) // .in(Singleton.class); // // final SchedulingService schedulingService = new SchedulingServiceImpl( // scheduleProperties, // getProvider(Injector.class), // getProvider(TriggerStrategyRegistry.class)); // bind(SchedulingService.class).toInstance(schedulingService); // // final TypeListener scheduleListener = new SchedulerTypeListener(schedulingService); // requestInjection(scheduleListener); // bindListener(Matchers.any(), scheduleListener); // // // Execution scope // final Provider<Map<String, Object>> executionMap = () -> ScheduledContextHolder // .getContext().getExecution().getProperties(); // bindScope(ExecutionScope.class, MapBasedScope.withMapSupplier(executionMap)); // // // ScheduledScope // final Provider<Map<String, Object>> scheduledMap = () -> ScheduledContextHolder // .getContext().getProperties(); // bindScope(ScheduledScope.class, MapBasedScope.withMapSupplier(scheduledMap)); // // ScopedProxyBinder.using(binder()) // .bind(ScheduledContext.class) // .toProvider(ScheduledContextHolder::getContext); // // ScopedProxyBinder.using(binder()) // .bind(ExecutionContext.class) // .toProvider( // () -> ScheduledContextHolder.getContext().getExecution()); // } // // @Provides // @Singleton // @DefaultBinding // ScheduledExecutorService provideScheduler( // @DefaultBinding ThreadFactory threadFactory) { // final int cores = Runtime.getRuntime().availableProcessors(); // return Executors.newScheduledThreadPool(cores, threadFactory); // } // // @Provides // @Singleton // @DefaultBinding // ExceptionHandler provideDefaultExceptionHandler() { // return new DefaultExceptionHandler(); // } // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleProperties.java // public final class ScheduleProperties { // // private boolean enableAutoScheduling = true; // // private ScheduleProperties() { // // } // // /** // * Returns the default properties. // * // * @return A new instance with defaults set. // */ // public static ScheduleProperties defaultProperties() { // return new ScheduleProperties(); // } // // /** // * Disables the behavior of automatic method scheduling. If automatic scheduling is // * disabled, methods are only actually be scheduled with their // * {@link ScheduledExecutorService} after manually calling // * {@link SchedulingService#startManualScheduling()}. // * // * @return This instance for method chaining. // */ // public ScheduleProperties disableAutoScheduling() { // this.enableAutoScheduling = false; // return this; // } // // boolean isAutoSchedulingEnabled() { // return enableAutoScheduling; // } // } // Path: src/main/java/de/skuzzle/inject/async/guice/ScheduleFeature.java import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.inject.Binder; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.ScheduleModule; import de.skuzzle.inject.async.schedule.ScheduleProperties; package de.skuzzle.inject.async.guice; /** * Specialized {@link Feature} that allows customization of the scheduling behavior by * providing a custom instance of {@link ScheduleProperties}. * <p> * * @author Simon Taddiken * @since 2.0.0 * @see DefaultFeatures#SCHEDULE */ public class ScheduleFeature implements Feature { private static final Logger LOG = LoggerFactory.getLogger(ScheduleFeature.class); /** * The default instance. Enables the same behavior as * {@link DefaultFeatures#SCHEDULE}. */ public static final ScheduleFeature DEFAULT = ScheduleFeature
.withProperties(ScheduleProperties.defaultProperties());
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/guice/ScheduleFeature.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleModule.java // public final class ScheduleModule extends AbstractModule { // // private final ScheduleProperties scheduleProperties; // // /** // * This constructor is only allowed to be called from within the {@link GuiceAsync} // * class. // * // * @param principal Restricts construction, not allowed to be null. // * @param scheduleProperties Additional settings to be passed to the scheduling // * features. // */ // public ScheduleModule(GuiceAsync principal, ScheduleProperties scheduleProperties) { // checkArgument(principal != null, // "instantiating this module is not allowed. Use the class " // + "GuiceAsync to enable asynchronous method support."); // // checkArgument(scheduleProperties != null, "scheduleProperties must not be null"); // this.scheduleProperties = scheduleProperties; // } // // @Override // protected void configure() { // bind(TriggerStrategyRegistry.class) // .to(SpiTriggerStrategyRegistryImpl.class) // .in(Singleton.class); // // final SchedulingService schedulingService = new SchedulingServiceImpl( // scheduleProperties, // getProvider(Injector.class), // getProvider(TriggerStrategyRegistry.class)); // bind(SchedulingService.class).toInstance(schedulingService); // // final TypeListener scheduleListener = new SchedulerTypeListener(schedulingService); // requestInjection(scheduleListener); // bindListener(Matchers.any(), scheduleListener); // // // Execution scope // final Provider<Map<String, Object>> executionMap = () -> ScheduledContextHolder // .getContext().getExecution().getProperties(); // bindScope(ExecutionScope.class, MapBasedScope.withMapSupplier(executionMap)); // // // ScheduledScope // final Provider<Map<String, Object>> scheduledMap = () -> ScheduledContextHolder // .getContext().getProperties(); // bindScope(ScheduledScope.class, MapBasedScope.withMapSupplier(scheduledMap)); // // ScopedProxyBinder.using(binder()) // .bind(ScheduledContext.class) // .toProvider(ScheduledContextHolder::getContext); // // ScopedProxyBinder.using(binder()) // .bind(ExecutionContext.class) // .toProvider( // () -> ScheduledContextHolder.getContext().getExecution()); // } // // @Provides // @Singleton // @DefaultBinding // ScheduledExecutorService provideScheduler( // @DefaultBinding ThreadFactory threadFactory) { // final int cores = Runtime.getRuntime().availableProcessors(); // return Executors.newScheduledThreadPool(cores, threadFactory); // } // // @Provides // @Singleton // @DefaultBinding // ExceptionHandler provideDefaultExceptionHandler() { // return new DefaultExceptionHandler(); // } // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleProperties.java // public final class ScheduleProperties { // // private boolean enableAutoScheduling = true; // // private ScheduleProperties() { // // } // // /** // * Returns the default properties. // * // * @return A new instance with defaults set. // */ // public static ScheduleProperties defaultProperties() { // return new ScheduleProperties(); // } // // /** // * Disables the behavior of automatic method scheduling. If automatic scheduling is // * disabled, methods are only actually be scheduled with their // * {@link ScheduledExecutorService} after manually calling // * {@link SchedulingService#startManualScheduling()}. // * // * @return This instance for method chaining. // */ // public ScheduleProperties disableAutoScheduling() { // this.enableAutoScheduling = false; // return this; // } // // boolean isAutoSchedulingEnabled() { // return enableAutoScheduling; // } // }
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.inject.Binder; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.ScheduleModule; import de.skuzzle.inject.async.schedule.ScheduleProperties;
package de.skuzzle.inject.async.guice; /** * Specialized {@link Feature} that allows customization of the scheduling behavior by * providing a custom instance of {@link ScheduleProperties}. * <p> * * @author Simon Taddiken * @since 2.0.0 * @see DefaultFeatures#SCHEDULE */ public class ScheduleFeature implements Feature { private static final Logger LOG = LoggerFactory.getLogger(ScheduleFeature.class); /** * The default instance. Enables the same behavior as * {@link DefaultFeatures#SCHEDULE}. */ public static final ScheduleFeature DEFAULT = ScheduleFeature .withProperties(ScheduleProperties.defaultProperties()); private final ScheduleProperties scheduleProperties; private ScheduleFeature(ScheduleProperties scheduleProperties) { Preconditions.checkArgument(scheduleProperties != null, "scheduleProperties must not be null"); this.scheduleProperties = scheduleProperties; } /** * Creates the feature and uses the given {@link ScheduleProperties}. * * @param scheduleProperties The properties. * @return The Feature instance that can be passed to {@link GuiceAsync} during * initialization. */ public static ScheduleFeature withProperties(ScheduleProperties scheduleProperties) { return new ScheduleFeature(scheduleProperties); } @Override public void installModuleTo(Binder binder, GuiceAsync principal) {
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleModule.java // public final class ScheduleModule extends AbstractModule { // // private final ScheduleProperties scheduleProperties; // // /** // * This constructor is only allowed to be called from within the {@link GuiceAsync} // * class. // * // * @param principal Restricts construction, not allowed to be null. // * @param scheduleProperties Additional settings to be passed to the scheduling // * features. // */ // public ScheduleModule(GuiceAsync principal, ScheduleProperties scheduleProperties) { // checkArgument(principal != null, // "instantiating this module is not allowed. Use the class " // + "GuiceAsync to enable asynchronous method support."); // // checkArgument(scheduleProperties != null, "scheduleProperties must not be null"); // this.scheduleProperties = scheduleProperties; // } // // @Override // protected void configure() { // bind(TriggerStrategyRegistry.class) // .to(SpiTriggerStrategyRegistryImpl.class) // .in(Singleton.class); // // final SchedulingService schedulingService = new SchedulingServiceImpl( // scheduleProperties, // getProvider(Injector.class), // getProvider(TriggerStrategyRegistry.class)); // bind(SchedulingService.class).toInstance(schedulingService); // // final TypeListener scheduleListener = new SchedulerTypeListener(schedulingService); // requestInjection(scheduleListener); // bindListener(Matchers.any(), scheduleListener); // // // Execution scope // final Provider<Map<String, Object>> executionMap = () -> ScheduledContextHolder // .getContext().getExecution().getProperties(); // bindScope(ExecutionScope.class, MapBasedScope.withMapSupplier(executionMap)); // // // ScheduledScope // final Provider<Map<String, Object>> scheduledMap = () -> ScheduledContextHolder // .getContext().getProperties(); // bindScope(ScheduledScope.class, MapBasedScope.withMapSupplier(scheduledMap)); // // ScopedProxyBinder.using(binder()) // .bind(ScheduledContext.class) // .toProvider(ScheduledContextHolder::getContext); // // ScopedProxyBinder.using(binder()) // .bind(ExecutionContext.class) // .toProvider( // () -> ScheduledContextHolder.getContext().getExecution()); // } // // @Provides // @Singleton // @DefaultBinding // ScheduledExecutorService provideScheduler( // @DefaultBinding ThreadFactory threadFactory) { // final int cores = Runtime.getRuntime().availableProcessors(); // return Executors.newScheduledThreadPool(cores, threadFactory); // } // // @Provides // @Singleton // @DefaultBinding // ExceptionHandler provideDefaultExceptionHandler() { // return new DefaultExceptionHandler(); // } // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduleProperties.java // public final class ScheduleProperties { // // private boolean enableAutoScheduling = true; // // private ScheduleProperties() { // // } // // /** // * Returns the default properties. // * // * @return A new instance with defaults set. // */ // public static ScheduleProperties defaultProperties() { // return new ScheduleProperties(); // } // // /** // * Disables the behavior of automatic method scheduling. If automatic scheduling is // * disabled, methods are only actually be scheduled with their // * {@link ScheduledExecutorService} after manually calling // * {@link SchedulingService#startManualScheduling()}. // * // * @return This instance for method chaining. // */ // public ScheduleProperties disableAutoScheduling() { // this.enableAutoScheduling = false; // return this; // } // // boolean isAutoSchedulingEnabled() { // return enableAutoScheduling; // } // } // Path: src/main/java/de/skuzzle/inject/async/guice/ScheduleFeature.java import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.inject.Binder; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.ScheduleModule; import de.skuzzle.inject.async.schedule.ScheduleProperties; package de.skuzzle.inject.async.guice; /** * Specialized {@link Feature} that allows customization of the scheduling behavior by * providing a custom instance of {@link ScheduleProperties}. * <p> * * @author Simon Taddiken * @since 2.0.0 * @see DefaultFeatures#SCHEDULE */ public class ScheduleFeature implements Feature { private static final Logger LOG = LoggerFactory.getLogger(ScheduleFeature.class); /** * The default instance. Enables the same behavior as * {@link DefaultFeatures#SCHEDULE}. */ public static final ScheduleFeature DEFAULT = ScheduleFeature .withProperties(ScheduleProperties.defaultProperties()); private final ScheduleProperties scheduleProperties; private ScheduleFeature(ScheduleProperties scheduleProperties) { Preconditions.checkArgument(scheduleProperties != null, "scheduleProperties must not be null"); this.scheduleProperties = scheduleProperties; } /** * Creates the feature and uses the given {@link ScheduleProperties}. * * @param scheduleProperties The properties. * @return The Feature instance that can be passed to {@link GuiceAsync} during * initialization. */ public static ScheduleFeature withProperties(ScheduleProperties scheduleProperties) { return new ScheduleFeature(scheduleProperties); } @Override public void installModuleTo(Binder binder, GuiceAsync principal) {
binder.install(new ScheduleModule(principal, scheduleProperties));
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/trigger/CronScheduler.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // }
import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cronutils.model.time.ExecutionTime; import com.google.common.base.MoreObjects; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext;
package de.skuzzle.inject.async.schedule.trigger; /** * Periodically schedules a Runnable with a a {@link ScheduledExecutorService} according * to a given cron pattern. * <p> * Prior to executing the actual action, the time until the next execution will be * calculated according to the provided cron pattern. The action will then be scheduled to * be executed again at the calculated time * * @author Simon Taddiken */ class CronScheduler { private static final Logger LOG = LoggerFactory.getLogger(CronScheduler.class); private final Runnable invocation; private final ScheduledExecutorService executor; private final ExecutionTime executionTime;
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronScheduler.java import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cronutils.model.time.ExecutionTime; import com.google.common.base.MoreObjects; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; package de.skuzzle.inject.async.schedule.trigger; /** * Periodically schedules a Runnable with a a {@link ScheduledExecutorService} according * to a given cron pattern. * <p> * Prior to executing the actual action, the time until the next execution will be * calculated according to the provided cron pattern. The action will then be scheduled to * be executed again at the calculated time * * @author Simon Taddiken */ class CronScheduler { private static final Logger LOG = LoggerFactory.getLogger(CronScheduler.class); private final Runnable invocation; private final ScheduledExecutorService executor; private final ExecutionTime executionTime;
private final ScheduledContext context;
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/schedule/trigger/CronScheduler.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // }
import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cronutils.model.time.ExecutionTime; import com.google.common.base.MoreObjects; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext;
package de.skuzzle.inject.async.schedule.trigger; /** * Periodically schedules a Runnable with a a {@link ScheduledExecutorService} according * to a given cron pattern. * <p> * Prior to executing the actual action, the time until the next execution will be * calculated according to the provided cron pattern. The action will then be scheduled to * be executed again at the calculated time * * @author Simon Taddiken */ class CronScheduler { private static final Logger LOG = LoggerFactory.getLogger(CronScheduler.class); private final Runnable invocation; private final ScheduledExecutorService executor; private final ExecutionTime executionTime; private final ScheduledContext context; // The time at which this Runnable will be called again by the Scheduler. This // reference is only null until the first call to #scheduleNextExecution. This // reference is guarded by the monitor of this instance to guarantee thread safe // updates private ZonedDateTime expectedNextExecution = null; private CronScheduler(ScheduledContext context, Runnable invocation, ScheduledExecutorService executor, ExecutionTime executionTime) { this.context = context; this.invocation = invocation; this.executor = executor; this.executionTime = executionTime; } static CronScheduler createWith(ScheduledContext context, Runnable invocation, ScheduledExecutorService scheduler, ExecutionTime executionTime) { return new CronScheduler(context, invocation, scheduler, executionTime); } public void start() { scheduleNextExecution(); } private void scheduleNextExecution() { LOG.debug("Scheduling next invocation of {}", invocation); final long delayUntilNextExecution = millisUntilNextExecution();
// Path: src/main/java/de/skuzzle/inject/async/schedule/LockableRunnable.java // public interface LockableRunnable extends Runnable { // // /** // * Wraps the given Runnable into a {@link LockableRunnable}. // * // * @param runnable The runnable to wrap. // * @return The {@link LockableRunnable}. // */ // public static LockableRunnable locked(Runnable runnable) { // return Runnables.LatchLockableRunnable.locked(runnable); // } // // /** // * Releases the lock which causes this runnable to block. Note: since 1.1.0 this // * method may be called multiple times without throwing an exception. // * // * @return This. // */ // LockableRunnable release(); // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronScheduler.java import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cronutils.model.time.ExecutionTime; import com.google.common.base.MoreObjects; import de.skuzzle.inject.async.schedule.LockableRunnable; import de.skuzzle.inject.async.schedule.ScheduledContext; package de.skuzzle.inject.async.schedule.trigger; /** * Periodically schedules a Runnable with a a {@link ScheduledExecutorService} according * to a given cron pattern. * <p> * Prior to executing the actual action, the time until the next execution will be * calculated according to the provided cron pattern. The action will then be scheduled to * be executed again at the calculated time * * @author Simon Taddiken */ class CronScheduler { private static final Logger LOG = LoggerFactory.getLogger(CronScheduler.class); private final Runnable invocation; private final ScheduledExecutorService executor; private final ExecutionTime executionTime; private final ScheduledContext context; // The time at which this Runnable will be called again by the Scheduler. This // reference is only null until the first call to #scheduleNextExecution. This // reference is guarded by the monitor of this instance to guarantee thread safe // updates private ZonedDateTime expectedNextExecution = null; private CronScheduler(ScheduledContext context, Runnable invocation, ScheduledExecutorService executor, ExecutionTime executionTime) { this.context = context; this.invocation = invocation; this.executor = executor; this.executionTime = executionTime; } static CronScheduler createWith(ScheduledContext context, Runnable invocation, ScheduledExecutorService scheduler, ExecutionTime executionTime) { return new CronScheduler(context, invocation, scheduler, executionTime); } public void start() { scheduleNextExecution(); } private void scheduleNextExecution() { LOG.debug("Scheduling next invocation of {}", invocation); final long delayUntilNextExecution = millisUntilNextExecution();
final LockableRunnable lockedRunnable = createRunnableForNextExecution();
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/methods/AsynchronousMethodInterceptor.java
// Path: src/main/java/de/skuzzle/inject/async/guice/Keys.java // public final class Keys { // // /** Fall back key if the user did not bind any scheduled executor service. */ // static final Key<? extends ScheduledExecutorService> DEFAULT_SCHEDULER_KEY = Key // .get(ScheduledExecutorService.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any exception handlder. */ // private static final Key<? extends ExceptionHandler> DEFAULT_EXCEPTION_HANDLER_KEY = Key // .get(ExceptionHandler.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any executor service. */ // static final Key<? extends ExecutorService> DEFAULT_EXECUTOR_KEY = Key // .get(ExecutorService.class, DefaultBinding.class); // // private Keys() { // // hidden ctor // } // // /** // * Finds the key of the {@link ExceptionHandler} to use for the given method. // * // * @param method The method to find the key for. // * @return The exception handler key. // */ // public static Key<? extends ExceptionHandler> getExceptionHandler(Method method) { // // TODO: must support BindingAnnotations // final OnError onError = method.getAnnotation(OnError.class); // if (onError != null) { // return Key.get(onError.value()); // } // return DEFAULT_EXCEPTION_HANDLER_KEY; // } // // /** // * Finds the key of the {@link ExecutorService} to use to execute the given method. // * // * @param method The method to find the key for. // * @return The ExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ExecutorService> getExecutorKey(Method method) { // final Class<? extends ExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Executor.class)) { // type = method.getAnnotation(Executor.class).value(); // executorSpecified = true; // } else { // type = ExecutorService.class; // } // return (Key<? extends ExecutorService>) createKey(type, method, // DEFAULT_EXECUTOR_KEY, executorSpecified); // } // // /** // * Finds the key of the {@link ScheduledExecutorService} to use to execute the given // * method. // * // * @param method the method to find the key for. // * @return The ScheduledExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ScheduledExecutorService> getSchedulerKey(Method method) { // final Class<? extends ScheduledExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Scheduler.class)) { // type = method.getAnnotation(Scheduler.class).value(); // executorSpecified = true; // } else { // type = ScheduledExecutorService.class; // } // return (Key<? extends ScheduledExecutorService>) createKey(type, method, // DEFAULT_SCHEDULER_KEY, executorSpecified); // } // // private static Key<?> createKey( // Class<?> type, // Method method, // Key<?> defaultKey, // boolean typeGiven) { // // final Errors errors = new Errors(method); // final Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, method, method.getAnnotations()); // errors.throwConfigurationExceptionIfErrorsExist(); // final Key<?> key; // if (bindingAnnotation == null && typeGiven) { // key = Key.get(type); // } else if (bindingAnnotation == null) { // key = defaultKey; // } else { // key = Key.get(type, bindingAnnotation); // } // return key; // } // }
import java.lang.reflect.Method; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import javax.inject.Inject; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import com.google.inject.Injector; import com.google.inject.Key; import de.skuzzle.inject.async.guice.Keys;
package de.skuzzle.inject.async.methods; class AsynchronousMethodInterceptor implements MethodInterceptor { @Inject private Injector injector; @Override public Object invoke(MethodInvocation invocation) throws Throwable { final Method method = invocation.getMethod(); checkReturnType(method.getReturnType());
// Path: src/main/java/de/skuzzle/inject/async/guice/Keys.java // public final class Keys { // // /** Fall back key if the user did not bind any scheduled executor service. */ // static final Key<? extends ScheduledExecutorService> DEFAULT_SCHEDULER_KEY = Key // .get(ScheduledExecutorService.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any exception handlder. */ // private static final Key<? extends ExceptionHandler> DEFAULT_EXCEPTION_HANDLER_KEY = Key // .get(ExceptionHandler.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any executor service. */ // static final Key<? extends ExecutorService> DEFAULT_EXECUTOR_KEY = Key // .get(ExecutorService.class, DefaultBinding.class); // // private Keys() { // // hidden ctor // } // // /** // * Finds the key of the {@link ExceptionHandler} to use for the given method. // * // * @param method The method to find the key for. // * @return The exception handler key. // */ // public static Key<? extends ExceptionHandler> getExceptionHandler(Method method) { // // TODO: must support BindingAnnotations // final OnError onError = method.getAnnotation(OnError.class); // if (onError != null) { // return Key.get(onError.value()); // } // return DEFAULT_EXCEPTION_HANDLER_KEY; // } // // /** // * Finds the key of the {@link ExecutorService} to use to execute the given method. // * // * @param method The method to find the key for. // * @return The ExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ExecutorService> getExecutorKey(Method method) { // final Class<? extends ExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Executor.class)) { // type = method.getAnnotation(Executor.class).value(); // executorSpecified = true; // } else { // type = ExecutorService.class; // } // return (Key<? extends ExecutorService>) createKey(type, method, // DEFAULT_EXECUTOR_KEY, executorSpecified); // } // // /** // * Finds the key of the {@link ScheduledExecutorService} to use to execute the given // * method. // * // * @param method the method to find the key for. // * @return The ScheduledExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ScheduledExecutorService> getSchedulerKey(Method method) { // final Class<? extends ScheduledExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Scheduler.class)) { // type = method.getAnnotation(Scheduler.class).value(); // executorSpecified = true; // } else { // type = ScheduledExecutorService.class; // } // return (Key<? extends ScheduledExecutorService>) createKey(type, method, // DEFAULT_SCHEDULER_KEY, executorSpecified); // } // // private static Key<?> createKey( // Class<?> type, // Method method, // Key<?> defaultKey, // boolean typeGiven) { // // final Errors errors = new Errors(method); // final Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, method, method.getAnnotations()); // errors.throwConfigurationExceptionIfErrorsExist(); // final Key<?> key; // if (bindingAnnotation == null && typeGiven) { // key = Key.get(type); // } else if (bindingAnnotation == null) { // key = defaultKey; // } else { // key = Key.get(type, bindingAnnotation); // } // return key; // } // } // Path: src/main/java/de/skuzzle/inject/async/methods/AsynchronousMethodInterceptor.java import java.lang.reflect.Method; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import javax.inject.Inject; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import com.google.inject.Injector; import com.google.inject.Key; import de.skuzzle.inject.async.guice.Keys; package de.skuzzle.inject.async.methods; class AsynchronousMethodInterceptor implements MethodInterceptor { @Inject private Injector injector; @Override public Object invoke(MethodInvocation invocation) throws Throwable { final Method method = invocation.getMethod(); checkReturnType(method.getReturnType());
final Key<? extends ExecutorService> key = Keys.getExecutorKey(method);
skuzzle/guice-async-extension
src/main/java/de/skuzzle/inject/async/methods/AsyncModule.java
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // }
import static com.google.common.base.Preconditions.checkArgument; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.inject.Singleton; import org.aopalliance.intercept.MethodInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.matcher.Matchers; import de.skuzzle.inject.async.guice.DefaultBinding; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.methods.annotation.Async;
package de.skuzzle.inject.async.methods; /** * Exposes required bindings. Use {@link GuiceAsync} to install this module for your own * environment. * * @author Simon Taddiken */ public final class AsyncModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(AsyncModule.class); /** * As {@link GuiceAsync} is not instantiatable from outside, the constructor guards * this class from being created unintentionally. * * @param principal The {@link GuiceAsync} instance that is installing this module. */
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // } // Path: src/main/java/de/skuzzle/inject/async/methods/AsyncModule.java import static com.google.common.base.Preconditions.checkArgument; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.inject.Singleton; import org.aopalliance.intercept.MethodInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.matcher.Matchers; import de.skuzzle.inject.async.guice.DefaultBinding; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.methods.annotation.Async; package de.skuzzle.inject.async.methods; /** * Exposes required bindings. Use {@link GuiceAsync} to install this module for your own * environment. * * @author Simon Taddiken */ public final class AsyncModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(AsyncModule.class); /** * As {@link GuiceAsync} is not instantiatable from outside, the constructor guards * this class from being created unintentionally. * * @param principal The {@link GuiceAsync} instance that is installing this module. */
public AsyncModule(GuiceAsync principal) {
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImplTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImpl.java // class SpiTriggerStrategyRegistryImpl implements TriggerStrategyRegistry { // // private static final Logger LOG = LoggerFactory.getLogger(SpiTriggerStrategyRegistryImpl.class); // // private final Map<Class<? extends Annotation>, TriggerStrategy> strategies; // // private final Injector injector; // // @Inject // public SpiTriggerStrategyRegistryImpl(Injector injector) { // this.injector = injector; // this.strategies = collectTriggerStrategies(); // } // // private Map<Class<? extends Annotation>, TriggerStrategy> collectTriggerStrategies() { // final ServiceLoader<TriggerStrategy> services = ServiceLoader.load( // TriggerStrategy.class); // // return asStream(services) // .peek(strategy -> LOG.debug("Installing strategy '{}' to handle '{}'", // strategy, strategy.getTriggerType())) // .peek(this.injector::injectMembers) // .collect(Collectors.toMap( // TriggerStrategy::getTriggerType, // Function.identity())); // } // // private static <T> Stream<T> asStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // @Override // public TriggerStrategy getStrategyFor(Annotation triggerAnnotation) { // checkArgument(triggerAnnotation != null); // final Class<? extends Annotation> type = triggerAnnotation.annotationType(); // final TriggerStrategy result = this.strategies.get(type); // checkState(result != null, // "There is no TriggerStrategy registered which is able to handle '%s'", // type.getName()); // return result; // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronTriggerStrategy.java // public class CronTriggerStrategy implements TriggerStrategy { // // private static final Logger LOG = LoggerFactory.getLogger(CronTriggerStrategy.class); // // @Override // public Class<CronTrigger> getTriggerType() { // return CronTrigger.class; // } // // @Override // public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) { // final Method method = context.getMethod(); // final CronTrigger trigger = method.getAnnotation(getTriggerType()); // checkArgument(trigger != null, "Method '%s' not annotated with @CronTrigger", method); // // LOG.debug("Initially scheduling method '{}' on '{}' with trigger: {}", method, context.getSelf(), trigger); // final CronType cronType = trigger.cronType(); // final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType.getType()); // final CronParser parser = new CronParser(cronDefinition); // final Cron cron = parser.parse(trigger.value()); // final ExecutionTime execTime = ExecutionTime.forCron(cron); // // CronScheduler // .createWith(context, runnable.release(), executor, execTime) // .start(); // } // }
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.SpiTriggerStrategyRegistryImpl; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.trigger.CronTriggerStrategy;
package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SpiTriggerStrategyRegistryImplTest { @Mock private Injector injector; @Mock private Annotation triggerAnnotation; @InjectMocks
// Path: src/main/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImpl.java // class SpiTriggerStrategyRegistryImpl implements TriggerStrategyRegistry { // // private static final Logger LOG = LoggerFactory.getLogger(SpiTriggerStrategyRegistryImpl.class); // // private final Map<Class<? extends Annotation>, TriggerStrategy> strategies; // // private final Injector injector; // // @Inject // public SpiTriggerStrategyRegistryImpl(Injector injector) { // this.injector = injector; // this.strategies = collectTriggerStrategies(); // } // // private Map<Class<? extends Annotation>, TriggerStrategy> collectTriggerStrategies() { // final ServiceLoader<TriggerStrategy> services = ServiceLoader.load( // TriggerStrategy.class); // // return asStream(services) // .peek(strategy -> LOG.debug("Installing strategy '{}' to handle '{}'", // strategy, strategy.getTriggerType())) // .peek(this.injector::injectMembers) // .collect(Collectors.toMap( // TriggerStrategy::getTriggerType, // Function.identity())); // } // // private static <T> Stream<T> asStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // @Override // public TriggerStrategy getStrategyFor(Annotation triggerAnnotation) { // checkArgument(triggerAnnotation != null); // final Class<? extends Annotation> type = triggerAnnotation.annotationType(); // final TriggerStrategy result = this.strategies.get(type); // checkState(result != null, // "There is no TriggerStrategy registered which is able to handle '%s'", // type.getName()); // return result; // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronTriggerStrategy.java // public class CronTriggerStrategy implements TriggerStrategy { // // private static final Logger LOG = LoggerFactory.getLogger(CronTriggerStrategy.class); // // @Override // public Class<CronTrigger> getTriggerType() { // return CronTrigger.class; // } // // @Override // public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) { // final Method method = context.getMethod(); // final CronTrigger trigger = method.getAnnotation(getTriggerType()); // checkArgument(trigger != null, "Method '%s' not annotated with @CronTrigger", method); // // LOG.debug("Initially scheduling method '{}' on '{}' with trigger: {}", method, context.getSelf(), trigger); // final CronType cronType = trigger.cronType(); // final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType.getType()); // final CronParser parser = new CronParser(cronDefinition); // final Cron cron = parser.parse(trigger.value()); // final ExecutionTime execTime = ExecutionTime.forCron(cron); // // CronScheduler // .createWith(context, runnable.release(), executor, execTime) // .start(); // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImplTest.java import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.SpiTriggerStrategyRegistryImpl; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.trigger.CronTriggerStrategy; package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SpiTriggerStrategyRegistryImplTest { @Mock private Injector injector; @Mock private Annotation triggerAnnotation; @InjectMocks
private SpiTriggerStrategyRegistryImpl subject;
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImplTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImpl.java // class SpiTriggerStrategyRegistryImpl implements TriggerStrategyRegistry { // // private static final Logger LOG = LoggerFactory.getLogger(SpiTriggerStrategyRegistryImpl.class); // // private final Map<Class<? extends Annotation>, TriggerStrategy> strategies; // // private final Injector injector; // // @Inject // public SpiTriggerStrategyRegistryImpl(Injector injector) { // this.injector = injector; // this.strategies = collectTriggerStrategies(); // } // // private Map<Class<? extends Annotation>, TriggerStrategy> collectTriggerStrategies() { // final ServiceLoader<TriggerStrategy> services = ServiceLoader.load( // TriggerStrategy.class); // // return asStream(services) // .peek(strategy -> LOG.debug("Installing strategy '{}' to handle '{}'", // strategy, strategy.getTriggerType())) // .peek(this.injector::injectMembers) // .collect(Collectors.toMap( // TriggerStrategy::getTriggerType, // Function.identity())); // } // // private static <T> Stream<T> asStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // @Override // public TriggerStrategy getStrategyFor(Annotation triggerAnnotation) { // checkArgument(triggerAnnotation != null); // final Class<? extends Annotation> type = triggerAnnotation.annotationType(); // final TriggerStrategy result = this.strategies.get(type); // checkState(result != null, // "There is no TriggerStrategy registered which is able to handle '%s'", // type.getName()); // return result; // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronTriggerStrategy.java // public class CronTriggerStrategy implements TriggerStrategy { // // private static final Logger LOG = LoggerFactory.getLogger(CronTriggerStrategy.class); // // @Override // public Class<CronTrigger> getTriggerType() { // return CronTrigger.class; // } // // @Override // public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) { // final Method method = context.getMethod(); // final CronTrigger trigger = method.getAnnotation(getTriggerType()); // checkArgument(trigger != null, "Method '%s' not annotated with @CronTrigger", method); // // LOG.debug("Initially scheduling method '{}' on '{}' with trigger: {}", method, context.getSelf(), trigger); // final CronType cronType = trigger.cronType(); // final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType.getType()); // final CronParser parser = new CronParser(cronDefinition); // final Cron cron = parser.parse(trigger.value()); // final ExecutionTime execTime = ExecutionTime.forCron(cron); // // CronScheduler // .createWith(context, runnable.release(), executor, execTime) // .start(); // } // }
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.SpiTriggerStrategyRegistryImpl; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.trigger.CronTriggerStrategy;
package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SpiTriggerStrategyRegistryImplTest { @Mock private Injector injector; @Mock private Annotation triggerAnnotation; @InjectMocks private SpiTriggerStrategyRegistryImpl subject; @Before public void setup() { when(this.triggerAnnotation.annotationType()).thenReturn( (Class) CronTrigger.class); } @Test public void testGetStrategyFor() throws Exception {
// Path: src/main/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImpl.java // class SpiTriggerStrategyRegistryImpl implements TriggerStrategyRegistry { // // private static final Logger LOG = LoggerFactory.getLogger(SpiTriggerStrategyRegistryImpl.class); // // private final Map<Class<? extends Annotation>, TriggerStrategy> strategies; // // private final Injector injector; // // @Inject // public SpiTriggerStrategyRegistryImpl(Injector injector) { // this.injector = injector; // this.strategies = collectTriggerStrategies(); // } // // private Map<Class<? extends Annotation>, TriggerStrategy> collectTriggerStrategies() { // final ServiceLoader<TriggerStrategy> services = ServiceLoader.load( // TriggerStrategy.class); // // return asStream(services) // .peek(strategy -> LOG.debug("Installing strategy '{}' to handle '{}'", // strategy, strategy.getTriggerType())) // .peek(this.injector::injectMembers) // .collect(Collectors.toMap( // TriggerStrategy::getTriggerType, // Function.identity())); // } // // private static <T> Stream<T> asStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // @Override // public TriggerStrategy getStrategyFor(Annotation triggerAnnotation) { // checkArgument(triggerAnnotation != null); // final Class<? extends Annotation> type = triggerAnnotation.annotationType(); // final TriggerStrategy result = this.strategies.get(type); // checkState(result != null, // "There is no TriggerStrategy registered which is able to handle '%s'", // type.getName()); // return result; // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronTriggerStrategy.java // public class CronTriggerStrategy implements TriggerStrategy { // // private static final Logger LOG = LoggerFactory.getLogger(CronTriggerStrategy.class); // // @Override // public Class<CronTrigger> getTriggerType() { // return CronTrigger.class; // } // // @Override // public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) { // final Method method = context.getMethod(); // final CronTrigger trigger = method.getAnnotation(getTriggerType()); // checkArgument(trigger != null, "Method '%s' not annotated with @CronTrigger", method); // // LOG.debug("Initially scheduling method '{}' on '{}' with trigger: {}", method, context.getSelf(), trigger); // final CronType cronType = trigger.cronType(); // final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType.getType()); // final CronParser parser = new CronParser(cronDefinition); // final Cron cron = parser.parse(trigger.value()); // final ExecutionTime execTime = ExecutionTime.forCron(cron); // // CronScheduler // .createWith(context, runnable.release(), executor, execTime) // .start(); // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImplTest.java import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.SpiTriggerStrategyRegistryImpl; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.trigger.CronTriggerStrategy; package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SpiTriggerStrategyRegistryImplTest { @Mock private Injector injector; @Mock private Annotation triggerAnnotation; @InjectMocks private SpiTriggerStrategyRegistryImpl subject; @Before public void setup() { when(this.triggerAnnotation.annotationType()).thenReturn( (Class) CronTrigger.class); } @Test public void testGetStrategyFor() throws Exception {
final TriggerStrategy strategy = this.subject
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImplTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImpl.java // class SpiTriggerStrategyRegistryImpl implements TriggerStrategyRegistry { // // private static final Logger LOG = LoggerFactory.getLogger(SpiTriggerStrategyRegistryImpl.class); // // private final Map<Class<? extends Annotation>, TriggerStrategy> strategies; // // private final Injector injector; // // @Inject // public SpiTriggerStrategyRegistryImpl(Injector injector) { // this.injector = injector; // this.strategies = collectTriggerStrategies(); // } // // private Map<Class<? extends Annotation>, TriggerStrategy> collectTriggerStrategies() { // final ServiceLoader<TriggerStrategy> services = ServiceLoader.load( // TriggerStrategy.class); // // return asStream(services) // .peek(strategy -> LOG.debug("Installing strategy '{}' to handle '{}'", // strategy, strategy.getTriggerType())) // .peek(this.injector::injectMembers) // .collect(Collectors.toMap( // TriggerStrategy::getTriggerType, // Function.identity())); // } // // private static <T> Stream<T> asStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // @Override // public TriggerStrategy getStrategyFor(Annotation triggerAnnotation) { // checkArgument(triggerAnnotation != null); // final Class<? extends Annotation> type = triggerAnnotation.annotationType(); // final TriggerStrategy result = this.strategies.get(type); // checkState(result != null, // "There is no TriggerStrategy registered which is able to handle '%s'", // type.getName()); // return result; // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronTriggerStrategy.java // public class CronTriggerStrategy implements TriggerStrategy { // // private static final Logger LOG = LoggerFactory.getLogger(CronTriggerStrategy.class); // // @Override // public Class<CronTrigger> getTriggerType() { // return CronTrigger.class; // } // // @Override // public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) { // final Method method = context.getMethod(); // final CronTrigger trigger = method.getAnnotation(getTriggerType()); // checkArgument(trigger != null, "Method '%s' not annotated with @CronTrigger", method); // // LOG.debug("Initially scheduling method '{}' on '{}' with trigger: {}", method, context.getSelf(), trigger); // final CronType cronType = trigger.cronType(); // final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType.getType()); // final CronParser parser = new CronParser(cronDefinition); // final Cron cron = parser.parse(trigger.value()); // final ExecutionTime execTime = ExecutionTime.forCron(cron); // // CronScheduler // .createWith(context, runnable.release(), executor, execTime) // .start(); // } // }
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.SpiTriggerStrategyRegistryImpl; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.trigger.CronTriggerStrategy;
package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SpiTriggerStrategyRegistryImplTest { @Mock private Injector injector; @Mock private Annotation triggerAnnotation; @InjectMocks private SpiTriggerStrategyRegistryImpl subject; @Before public void setup() { when(this.triggerAnnotation.annotationType()).thenReturn( (Class) CronTrigger.class); } @Test public void testGetStrategyFor() throws Exception { final TriggerStrategy strategy = this.subject .getStrategyFor(this.triggerAnnotation);
// Path: src/main/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImpl.java // class SpiTriggerStrategyRegistryImpl implements TriggerStrategyRegistry { // // private static final Logger LOG = LoggerFactory.getLogger(SpiTriggerStrategyRegistryImpl.class); // // private final Map<Class<? extends Annotation>, TriggerStrategy> strategies; // // private final Injector injector; // // @Inject // public SpiTriggerStrategyRegistryImpl(Injector injector) { // this.injector = injector; // this.strategies = collectTriggerStrategies(); // } // // private Map<Class<? extends Annotation>, TriggerStrategy> collectTriggerStrategies() { // final ServiceLoader<TriggerStrategy> services = ServiceLoader.load( // TriggerStrategy.class); // // return asStream(services) // .peek(strategy -> LOG.debug("Installing strategy '{}' to handle '{}'", // strategy, strategy.getTriggerType())) // .peek(this.injector::injectMembers) // .collect(Collectors.toMap( // TriggerStrategy::getTriggerType, // Function.identity())); // } // // private static <T> Stream<T> asStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // @Override // public TriggerStrategy getStrategyFor(Annotation triggerAnnotation) { // checkArgument(triggerAnnotation != null); // final Class<? extends Annotation> type = triggerAnnotation.annotationType(); // final TriggerStrategy result = this.strategies.get(type); // checkState(result != null, // "There is no TriggerStrategy registered which is able to handle '%s'", // type.getName()); // return result; // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/TriggerStrategy.java // public interface TriggerStrategy { // // /** // * Returns the annotation type that this strategy can handle. // * // * @return The annotation type. // */ // Class<? extends Annotation> getTriggerType(); // // /** // * Extracts scheduling information from the provided {@link Method} and then schedules // * invocations of that method according to the information. // * // * <p> // * To support invocation of parameterized methods, implementors can refer to // * {@link InjectedMethodInvocation} to inject actual parameters of a method. // * </p> // * // * @param context The schedule context for the annotated method. // * @param executor The executor to use for scheduling. // * @param runnable A runnable that, when scheduled, will execute the annotated method. // */ // void schedule(ScheduledContext context, // ScheduledExecutorService executor, LockableRunnable runnable); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/trigger/CronTriggerStrategy.java // public class CronTriggerStrategy implements TriggerStrategy { // // private static final Logger LOG = LoggerFactory.getLogger(CronTriggerStrategy.class); // // @Override // public Class<CronTrigger> getTriggerType() { // return CronTrigger.class; // } // // @Override // public void schedule(ScheduledContext context, ScheduledExecutorService executor, LockableRunnable runnable) { // final Method method = context.getMethod(); // final CronTrigger trigger = method.getAnnotation(getTriggerType()); // checkArgument(trigger != null, "Method '%s' not annotated with @CronTrigger", method); // // LOG.debug("Initially scheduling method '{}' on '{}' with trigger: {}", method, context.getSelf(), trigger); // final CronType cronType = trigger.cronType(); // final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(cronType.getType()); // final CronParser parser = new CronParser(cronDefinition); // final Cron cron = parser.parse(trigger.value()); // final ExecutionTime execTime = ExecutionTime.forCron(cron); // // CronScheduler // .createWith(context, runnable.release(), executor, execTime) // .start(); // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/SpiTriggerStrategyRegistryImplTest.java import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.annotation.Annotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import de.skuzzle.inject.async.schedule.SpiTriggerStrategyRegistryImpl; import de.skuzzle.inject.async.schedule.TriggerStrategy; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.trigger.CronTriggerStrategy; package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SpiTriggerStrategyRegistryImplTest { @Mock private Injector injector; @Mock private Annotation triggerAnnotation; @InjectMocks private SpiTriggerStrategyRegistryImpl subject; @Before public void setup() { when(this.triggerAnnotation.annotationType()).thenReturn( (Class) CronTrigger.class); } @Test public void testGetStrategyFor() throws Exception { final TriggerStrategy strategy = this.subject .getStrategyFor(this.triggerAnnotation);
verify(this.injector).injectMembers(Mockito.isA(CronTriggerStrategy.class));
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/ScheduledContextHolderTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContextHolder.java // final class ScheduledContextHolder { // // private static final ThreadLocal<ScheduledContext> STACK = new ThreadLocal<>(); // // private ScheduledContextHolder() { // // hidden // } // // /** // * Tests whether the current thread is currently executing a scheduled method. // * // * @return Whether the current thread is currently executing a scheduled method. // */ // public static boolean isContextActive() { // return STACK.get() != null; // } // // /** // * May be used to access the {@link ScheduledContext} which is currently active for // * the current thread. Will throw an exception if no context is in place. // * // * @return The active context. // */ // public static ScheduledContext getContext() { // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext != null, "Scope 'ScheduledScope' is currently not " // + "active. Either there is no scheduled method being executed on the " // + "current thread or the TriggerStrategy that scheduled the method " // + "does not support scoped executions"); // return activeContext; // } // // /** // * Registers the given context to be active for the current thread. Callers must // * ensure to also <code>pop()</code> after the execution of the scoped method is done. // * // * @param context The context to record as active. // */ // public static void push(ScheduledContext context) { // checkArgument(context != null, "context may not be null. " // + "Use .pop() to disable the currently active context."); // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext == null, "there is currently another ScheduledContext " // + "active. There may only be one active context per thread at a time. " // + "Currently active context is: '%s'. Tried to set '%s' as active context", // activeContext, context); // STACK.set(context); // } // // /** // * Removes the context for the current thread. // */ // public static void pop() { // checkState(STACK.get() != null, "there is no active ScheduledContext"); // STACK.set(null); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import org.junit.After; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.ScheduledContextHolder;
package de.skuzzle.inject.async.schedule; public class ScheduledContextHolderTest { @Before public void setup() {
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContextHolder.java // final class ScheduledContextHolder { // // private static final ThreadLocal<ScheduledContext> STACK = new ThreadLocal<>(); // // private ScheduledContextHolder() { // // hidden // } // // /** // * Tests whether the current thread is currently executing a scheduled method. // * // * @return Whether the current thread is currently executing a scheduled method. // */ // public static boolean isContextActive() { // return STACK.get() != null; // } // // /** // * May be used to access the {@link ScheduledContext} which is currently active for // * the current thread. Will throw an exception if no context is in place. // * // * @return The active context. // */ // public static ScheduledContext getContext() { // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext != null, "Scope 'ScheduledScope' is currently not " // + "active. Either there is no scheduled method being executed on the " // + "current thread or the TriggerStrategy that scheduled the method " // + "does not support scoped executions"); // return activeContext; // } // // /** // * Registers the given context to be active for the current thread. Callers must // * ensure to also <code>pop()</code> after the execution of the scoped method is done. // * // * @param context The context to record as active. // */ // public static void push(ScheduledContext context) { // checkArgument(context != null, "context may not be null. " // + "Use .pop() to disable the currently active context."); // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext == null, "there is currently another ScheduledContext " // + "active. There may only be one active context per thread at a time. " // + "Currently active context is: '%s'. Tried to set '%s' as active context", // activeContext, context); // STACK.set(context); // } // // /** // * Removes the context for the current thread. // */ // public static void pop() { // checkState(STACK.get() != null, "there is no active ScheduledContext"); // STACK.set(null); // } // // } // Path: src/test/java/de/skuzzle/inject/async/schedule/ScheduledContextHolderTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import org.junit.After; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.ScheduledContextHolder; package de.skuzzle.inject.async.schedule; public class ScheduledContextHolderTest { @Before public void setup() {
if (ScheduledContextHolder.isContextActive()) {
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/ScheduledContextHolderTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContextHolder.java // final class ScheduledContextHolder { // // private static final ThreadLocal<ScheduledContext> STACK = new ThreadLocal<>(); // // private ScheduledContextHolder() { // // hidden // } // // /** // * Tests whether the current thread is currently executing a scheduled method. // * // * @return Whether the current thread is currently executing a scheduled method. // */ // public static boolean isContextActive() { // return STACK.get() != null; // } // // /** // * May be used to access the {@link ScheduledContext} which is currently active for // * the current thread. Will throw an exception if no context is in place. // * // * @return The active context. // */ // public static ScheduledContext getContext() { // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext != null, "Scope 'ScheduledScope' is currently not " // + "active. Either there is no scheduled method being executed on the " // + "current thread or the TriggerStrategy that scheduled the method " // + "does not support scoped executions"); // return activeContext; // } // // /** // * Registers the given context to be active for the current thread. Callers must // * ensure to also <code>pop()</code> after the execution of the scoped method is done. // * // * @param context The context to record as active. // */ // public static void push(ScheduledContext context) { // checkArgument(context != null, "context may not be null. " // + "Use .pop() to disable the currently active context."); // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext == null, "there is currently another ScheduledContext " // + "active. There may only be one active context per thread at a time. " // + "Currently active context is: '%s'. Tried to set '%s' as active context", // activeContext, context); // STACK.set(context); // } // // /** // * Removes the context for the current thread. // */ // public static void pop() { // checkState(STACK.get() != null, "there is no active ScheduledContext"); // STACK.set(null); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import org.junit.After; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.ScheduledContextHolder;
package de.skuzzle.inject.async.schedule; public class ScheduledContextHolderTest { @Before public void setup() { if (ScheduledContextHolder.isContextActive()) { ScheduledContextHolder.pop(); } } @After public void after() { if (ScheduledContextHolder.isContextActive()) { ScheduledContextHolder.pop(); } } @Test(expected = IllegalStateException.class) public void testPopNotPresent() throws Exception { ScheduledContextHolder.pop(); } @Test public void testPushPop() throws Exception {
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContextHolder.java // final class ScheduledContextHolder { // // private static final ThreadLocal<ScheduledContext> STACK = new ThreadLocal<>(); // // private ScheduledContextHolder() { // // hidden // } // // /** // * Tests whether the current thread is currently executing a scheduled method. // * // * @return Whether the current thread is currently executing a scheduled method. // */ // public static boolean isContextActive() { // return STACK.get() != null; // } // // /** // * May be used to access the {@link ScheduledContext} which is currently active for // * the current thread. Will throw an exception if no context is in place. // * // * @return The active context. // */ // public static ScheduledContext getContext() { // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext != null, "Scope 'ScheduledScope' is currently not " // + "active. Either there is no scheduled method being executed on the " // + "current thread or the TriggerStrategy that scheduled the method " // + "does not support scoped executions"); // return activeContext; // } // // /** // * Registers the given context to be active for the current thread. Callers must // * ensure to also <code>pop()</code> after the execution of the scoped method is done. // * // * @param context The context to record as active. // */ // public static void push(ScheduledContext context) { // checkArgument(context != null, "context may not be null. " // + "Use .pop() to disable the currently active context."); // final ScheduledContext activeContext = STACK.get(); // checkState(activeContext == null, "there is currently another ScheduledContext " // + "active. There may only be one active context per thread at a time. " // + "Currently active context is: '%s'. Tried to set '%s' as active context", // activeContext, context); // STACK.set(context); // } // // /** // * Removes the context for the current thread. // */ // public static void pop() { // checkState(STACK.get() != null, "there is no active ScheduledContext"); // STACK.set(null); // } // // } // Path: src/test/java/de/skuzzle/inject/async/schedule/ScheduledContextHolderTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import org.junit.After; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.ScheduledContext; import de.skuzzle.inject.async.schedule.ScheduledContextHolder; package de.skuzzle.inject.async.schedule; public class ScheduledContextHolderTest { @Before public void setup() { if (ScheduledContextHolder.isContextActive()) { ScheduledContextHolder.pop(); } } @After public void after() { if (ScheduledContextHolder.isContextActive()) { ScheduledContextHolder.pop(); } } @Test(expected = IllegalStateException.class) public void testPopNotPresent() throws Exception { ScheduledContextHolder.pop(); } @Test public void testPushPop() throws Exception {
final ScheduledContext ctx = mock(ScheduledContext.class);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/SchedulerTypeListenerTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulerTypeListener.java // class SchedulerTypeListener implements TypeListener { // // private static final Logger LOG = LoggerFactory.getLogger(SchedulerTypeListener.class); // // // synchronized in case the injector is set up asynchronously // private List<Class<?>> scheduleStatics = Collections.synchronizedList(new ArrayList<>()); // private volatile boolean injectorReady; // // private final SchedulingService schedulingService; // // SchedulerTypeListener(SchedulingService schedulingService) { // this.schedulingService = schedulingService; // } // // @Inject // void injectorReady() { // this.injectorReady = true; // final Consumer<Method> schedule = this.schedulingService::scheduleStaticMethod; // // this.scheduleStatics.forEach(type -> MethodVisitor.forEachStaticMethod(type, schedule)); // this.scheduleStatics.clear(); // this.scheduleStatics = null; // } // // @Override // public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { // handleStaticScheduling(type.getRawType()); // handleMemberScheduling(encounter); // } // // private void handleStaticScheduling(Class<?> type) { // // need to distinguish two states here: the types we encounter while the injector // // is not ready and those that are encountered while the injector is already // // ready. In the first case, we collect the types for later handling in second // // case we can schedule them immediately // if (this.injectorReady) { // LOG.trace("Encountered type {} while Injector was ready", type); // MethodVisitor.forEachStaticMethod(type, this.schedulingService::scheduleStaticMethod); // } else { // LOG.trace("Encountered type {} while Injector was NOT ready", type); // this.scheduleStatics.add(type); // } // } // // private <I> void handleMemberScheduling(TypeEncounter<I> encounter) { // encounter.register(new InjectionListener<I>() { // // @Override // public void afterInjection(I injectee) { // final Consumer<Method> scheduleMemberMethod = method -> schedulingService.scheduleMemberMethod(method, // injectee); // MethodVisitor.forEachMemberMethod(injectee.getClass(), scheduleMemberMethod); // } // }); // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulingService.java // public interface SchedulingService { // // /** // * Schedules the given member method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a non-static member method. // * @param self The object to invoke the method on. // */ // void scheduleMemberMethod(Method method, Object self); // // /** // * Schedules the given static method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a static method. // */ // void scheduleStaticMethod(Method method); // // /** // * Schedules all encountered methods that are annotated with {@link ManuallyStarted}. // * This method should only be called once during the lifetime of your Guice // * {@link Injector}. Calling it multiple times will have no effect. // * // * @since 2.0.0 // */ // void startManualScheduling(); // }
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import de.skuzzle.inject.async.schedule.ExceptionHandler; import de.skuzzle.inject.async.schedule.SchedulerTypeListener; import de.skuzzle.inject.async.schedule.SchedulingService; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler;
package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SchedulerTypeListenerTest { @Mock private TypeEncounter<SchedulerTypeListenerTest> encounter; @Mock private Injector injector; @Mock private TriggerStrategyRegistry registry; @Captor private ArgumentCaptor<InjectionListener<SchedulerTypeListenerTest>> captor; @Mock private ScheduledExecutorService scheduler; @Mock
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulerTypeListener.java // class SchedulerTypeListener implements TypeListener { // // private static final Logger LOG = LoggerFactory.getLogger(SchedulerTypeListener.class); // // // synchronized in case the injector is set up asynchronously // private List<Class<?>> scheduleStatics = Collections.synchronizedList(new ArrayList<>()); // private volatile boolean injectorReady; // // private final SchedulingService schedulingService; // // SchedulerTypeListener(SchedulingService schedulingService) { // this.schedulingService = schedulingService; // } // // @Inject // void injectorReady() { // this.injectorReady = true; // final Consumer<Method> schedule = this.schedulingService::scheduleStaticMethod; // // this.scheduleStatics.forEach(type -> MethodVisitor.forEachStaticMethod(type, schedule)); // this.scheduleStatics.clear(); // this.scheduleStatics = null; // } // // @Override // public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { // handleStaticScheduling(type.getRawType()); // handleMemberScheduling(encounter); // } // // private void handleStaticScheduling(Class<?> type) { // // need to distinguish two states here: the types we encounter while the injector // // is not ready and those that are encountered while the injector is already // // ready. In the first case, we collect the types for later handling in second // // case we can schedule them immediately // if (this.injectorReady) { // LOG.trace("Encountered type {} while Injector was ready", type); // MethodVisitor.forEachStaticMethod(type, this.schedulingService::scheduleStaticMethod); // } else { // LOG.trace("Encountered type {} while Injector was NOT ready", type); // this.scheduleStatics.add(type); // } // } // // private <I> void handleMemberScheduling(TypeEncounter<I> encounter) { // encounter.register(new InjectionListener<I>() { // // @Override // public void afterInjection(I injectee) { // final Consumer<Method> scheduleMemberMethod = method -> schedulingService.scheduleMemberMethod(method, // injectee); // MethodVisitor.forEachMemberMethod(injectee.getClass(), scheduleMemberMethod); // } // }); // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulingService.java // public interface SchedulingService { // // /** // * Schedules the given member method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a non-static member method. // * @param self The object to invoke the method on. // */ // void scheduleMemberMethod(Method method, Object self); // // /** // * Schedules the given static method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a static method. // */ // void scheduleStaticMethod(Method method); // // /** // * Schedules all encountered methods that are annotated with {@link ManuallyStarted}. // * This method should only be called once during the lifetime of your Guice // * {@link Injector}. Calling it multiple times will have no effect. // * // * @since 2.0.0 // */ // void startManualScheduling(); // } // Path: src/test/java/de/skuzzle/inject/async/schedule/SchedulerTypeListenerTest.java import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import de.skuzzle.inject.async.schedule.ExceptionHandler; import de.skuzzle.inject.async.schedule.SchedulerTypeListener; import de.skuzzle.inject.async.schedule.SchedulingService; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler; package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SchedulerTypeListenerTest { @Mock private TypeEncounter<SchedulerTypeListenerTest> encounter; @Mock private Injector injector; @Mock private TriggerStrategyRegistry registry; @Captor private ArgumentCaptor<InjectionListener<SchedulerTypeListenerTest>> captor; @Mock private ScheduledExecutorService scheduler; @Mock
private ExceptionHandler exceptionHandler;
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/SchedulerTypeListenerTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulerTypeListener.java // class SchedulerTypeListener implements TypeListener { // // private static final Logger LOG = LoggerFactory.getLogger(SchedulerTypeListener.class); // // // synchronized in case the injector is set up asynchronously // private List<Class<?>> scheduleStatics = Collections.synchronizedList(new ArrayList<>()); // private volatile boolean injectorReady; // // private final SchedulingService schedulingService; // // SchedulerTypeListener(SchedulingService schedulingService) { // this.schedulingService = schedulingService; // } // // @Inject // void injectorReady() { // this.injectorReady = true; // final Consumer<Method> schedule = this.schedulingService::scheduleStaticMethod; // // this.scheduleStatics.forEach(type -> MethodVisitor.forEachStaticMethod(type, schedule)); // this.scheduleStatics.clear(); // this.scheduleStatics = null; // } // // @Override // public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { // handleStaticScheduling(type.getRawType()); // handleMemberScheduling(encounter); // } // // private void handleStaticScheduling(Class<?> type) { // // need to distinguish two states here: the types we encounter while the injector // // is not ready and those that are encountered while the injector is already // // ready. In the first case, we collect the types for later handling in second // // case we can schedule them immediately // if (this.injectorReady) { // LOG.trace("Encountered type {} while Injector was ready", type); // MethodVisitor.forEachStaticMethod(type, this.schedulingService::scheduleStaticMethod); // } else { // LOG.trace("Encountered type {} while Injector was NOT ready", type); // this.scheduleStatics.add(type); // } // } // // private <I> void handleMemberScheduling(TypeEncounter<I> encounter) { // encounter.register(new InjectionListener<I>() { // // @Override // public void afterInjection(I injectee) { // final Consumer<Method> scheduleMemberMethod = method -> schedulingService.scheduleMemberMethod(method, // injectee); // MethodVisitor.forEachMemberMethod(injectee.getClass(), scheduleMemberMethod); // } // }); // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulingService.java // public interface SchedulingService { // // /** // * Schedules the given member method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a non-static member method. // * @param self The object to invoke the method on. // */ // void scheduleMemberMethod(Method method, Object self); // // /** // * Schedules the given static method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a static method. // */ // void scheduleStaticMethod(Method method); // // /** // * Schedules all encountered methods that are annotated with {@link ManuallyStarted}. // * This method should only be called once during the lifetime of your Guice // * {@link Injector}. Calling it multiple times will have no effect. // * // * @since 2.0.0 // */ // void startManualScheduling(); // }
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import de.skuzzle.inject.async.schedule.ExceptionHandler; import de.skuzzle.inject.async.schedule.SchedulerTypeListener; import de.skuzzle.inject.async.schedule.SchedulingService; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler;
package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SchedulerTypeListenerTest { @Mock private TypeEncounter<SchedulerTypeListenerTest> encounter; @Mock private Injector injector; @Mock private TriggerStrategyRegistry registry; @Captor private ArgumentCaptor<InjectionListener<SchedulerTypeListenerTest>> captor; @Mock private ScheduledExecutorService scheduler; @Mock private ExceptionHandler exceptionHandler; @Mock
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulerTypeListener.java // class SchedulerTypeListener implements TypeListener { // // private static final Logger LOG = LoggerFactory.getLogger(SchedulerTypeListener.class); // // // synchronized in case the injector is set up asynchronously // private List<Class<?>> scheduleStatics = Collections.synchronizedList(new ArrayList<>()); // private volatile boolean injectorReady; // // private final SchedulingService schedulingService; // // SchedulerTypeListener(SchedulingService schedulingService) { // this.schedulingService = schedulingService; // } // // @Inject // void injectorReady() { // this.injectorReady = true; // final Consumer<Method> schedule = this.schedulingService::scheduleStaticMethod; // // this.scheduleStatics.forEach(type -> MethodVisitor.forEachStaticMethod(type, schedule)); // this.scheduleStatics.clear(); // this.scheduleStatics = null; // } // // @Override // public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { // handleStaticScheduling(type.getRawType()); // handleMemberScheduling(encounter); // } // // private void handleStaticScheduling(Class<?> type) { // // need to distinguish two states here: the types we encounter while the injector // // is not ready and those that are encountered while the injector is already // // ready. In the first case, we collect the types for later handling in second // // case we can schedule them immediately // if (this.injectorReady) { // LOG.trace("Encountered type {} while Injector was ready", type); // MethodVisitor.forEachStaticMethod(type, this.schedulingService::scheduleStaticMethod); // } else { // LOG.trace("Encountered type {} while Injector was NOT ready", type); // this.scheduleStatics.add(type); // } // } // // private <I> void handleMemberScheduling(TypeEncounter<I> encounter) { // encounter.register(new InjectionListener<I>() { // // @Override // public void afterInjection(I injectee) { // final Consumer<Method> scheduleMemberMethod = method -> schedulingService.scheduleMemberMethod(method, // injectee); // MethodVisitor.forEachMemberMethod(injectee.getClass(), scheduleMemberMethod); // } // }); // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulingService.java // public interface SchedulingService { // // /** // * Schedules the given member method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a non-static member method. // * @param self The object to invoke the method on. // */ // void scheduleMemberMethod(Method method, Object self); // // /** // * Schedules the given static method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a static method. // */ // void scheduleStaticMethod(Method method); // // /** // * Schedules all encountered methods that are annotated with {@link ManuallyStarted}. // * This method should only be called once during the lifetime of your Guice // * {@link Injector}. Calling it multiple times will have no effect. // * // * @since 2.0.0 // */ // void startManualScheduling(); // } // Path: src/test/java/de/skuzzle/inject/async/schedule/SchedulerTypeListenerTest.java import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import de.skuzzle.inject.async.schedule.ExceptionHandler; import de.skuzzle.inject.async.schedule.SchedulerTypeListener; import de.skuzzle.inject.async.schedule.SchedulingService; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler; package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class SchedulerTypeListenerTest { @Mock private TypeEncounter<SchedulerTypeListenerTest> encounter; @Mock private Injector injector; @Mock private TriggerStrategyRegistry registry; @Captor private ArgumentCaptor<InjectionListener<SchedulerTypeListenerTest>> captor; @Mock private ScheduledExecutorService scheduler; @Mock private ExceptionHandler exceptionHandler; @Mock
private SchedulingService schedulingService;
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/SchedulerTypeListenerTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulerTypeListener.java // class SchedulerTypeListener implements TypeListener { // // private static final Logger LOG = LoggerFactory.getLogger(SchedulerTypeListener.class); // // // synchronized in case the injector is set up asynchronously // private List<Class<?>> scheduleStatics = Collections.synchronizedList(new ArrayList<>()); // private volatile boolean injectorReady; // // private final SchedulingService schedulingService; // // SchedulerTypeListener(SchedulingService schedulingService) { // this.schedulingService = schedulingService; // } // // @Inject // void injectorReady() { // this.injectorReady = true; // final Consumer<Method> schedule = this.schedulingService::scheduleStaticMethod; // // this.scheduleStatics.forEach(type -> MethodVisitor.forEachStaticMethod(type, schedule)); // this.scheduleStatics.clear(); // this.scheduleStatics = null; // } // // @Override // public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { // handleStaticScheduling(type.getRawType()); // handleMemberScheduling(encounter); // } // // private void handleStaticScheduling(Class<?> type) { // // need to distinguish two states here: the types we encounter while the injector // // is not ready and those that are encountered while the injector is already // // ready. In the first case, we collect the types for later handling in second // // case we can schedule them immediately // if (this.injectorReady) { // LOG.trace("Encountered type {} while Injector was ready", type); // MethodVisitor.forEachStaticMethod(type, this.schedulingService::scheduleStaticMethod); // } else { // LOG.trace("Encountered type {} while Injector was NOT ready", type); // this.scheduleStatics.add(type); // } // } // // private <I> void handleMemberScheduling(TypeEncounter<I> encounter) { // encounter.register(new InjectionListener<I>() { // // @Override // public void afterInjection(I injectee) { // final Consumer<Method> scheduleMemberMethod = method -> schedulingService.scheduleMemberMethod(method, // injectee); // MethodVisitor.forEachMemberMethod(injectee.getClass(), scheduleMemberMethod); // } // }); // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulingService.java // public interface SchedulingService { // // /** // * Schedules the given member method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a non-static member method. // * @param self The object to invoke the method on. // */ // void scheduleMemberMethod(Method method, Object self); // // /** // * Schedules the given static method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a static method. // */ // void scheduleStaticMethod(Method method); // // /** // * Schedules all encountered methods that are annotated with {@link ManuallyStarted}. // * This method should only be called once during the lifetime of your Guice // * {@link Injector}. Calling it multiple times will have no effect. // * // * @since 2.0.0 // */ // void startManualScheduling(); // }
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import de.skuzzle.inject.async.schedule.ExceptionHandler; import de.skuzzle.inject.async.schedule.SchedulerTypeListener; import de.skuzzle.inject.async.schedule.SchedulingService; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler;
when(this.injector.getInstance(Key.get(ExceptionHandler.class))) .thenReturn(this.exceptionHandler); when(this.injector.getInstance(Key.get(ScheduledExecutorService.class))) .thenReturn(this.scheduler); } private static <T> Provider<T> provider(T t) { return () -> t; } @Scheduled @CronTrigger("* * * * * *") @Scheduler(ScheduledExecutorService.class) @OnError(ExceptionHandler.class) public void methodWithTrigger() { } @Scheduled @CronTrigger("* * * * * *") @Scheduler(ScheduledExecutorService.class) @OnError(ExceptionHandler.class) public static void staticMethodWithTrigger() { } @Test public void testHear() throws Exception { final Method expectedMethod = getClass().getMethod("methodWithTrigger"); final Method expectedStaticMethod = getClass() .getMethod("staticMethodWithTrigger"); final TypeLiteral<SchedulerTypeListenerTest> type = new TypeLiteral<SchedulerTypeListenerTest>() {};
// Path: src/main/java/de/skuzzle/inject/async/schedule/ExceptionHandler.java // public interface ExceptionHandler { // // /** // * Call back for handling exceptions that occur in scheduled methods. // * // * @param e The exception. // */ // void onException(Exception e); // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulerTypeListener.java // class SchedulerTypeListener implements TypeListener { // // private static final Logger LOG = LoggerFactory.getLogger(SchedulerTypeListener.class); // // // synchronized in case the injector is set up asynchronously // private List<Class<?>> scheduleStatics = Collections.synchronizedList(new ArrayList<>()); // private volatile boolean injectorReady; // // private final SchedulingService schedulingService; // // SchedulerTypeListener(SchedulingService schedulingService) { // this.schedulingService = schedulingService; // } // // @Inject // void injectorReady() { // this.injectorReady = true; // final Consumer<Method> schedule = this.schedulingService::scheduleStaticMethod; // // this.scheduleStatics.forEach(type -> MethodVisitor.forEachStaticMethod(type, schedule)); // this.scheduleStatics.clear(); // this.scheduleStatics = null; // } // // @Override // public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { // handleStaticScheduling(type.getRawType()); // handleMemberScheduling(encounter); // } // // private void handleStaticScheduling(Class<?> type) { // // need to distinguish two states here: the types we encounter while the injector // // is not ready and those that are encountered while the injector is already // // ready. In the first case, we collect the types for later handling in second // // case we can schedule them immediately // if (this.injectorReady) { // LOG.trace("Encountered type {} while Injector was ready", type); // MethodVisitor.forEachStaticMethod(type, this.schedulingService::scheduleStaticMethod); // } else { // LOG.trace("Encountered type {} while Injector was NOT ready", type); // this.scheduleStatics.add(type); // } // } // // private <I> void handleMemberScheduling(TypeEncounter<I> encounter) { // encounter.register(new InjectionListener<I>() { // // @Override // public void afterInjection(I injectee) { // final Consumer<Method> scheduleMemberMethod = method -> schedulingService.scheduleMemberMethod(method, // injectee); // MethodVisitor.forEachMemberMethod(injectee.getClass(), scheduleMemberMethod); // } // }); // } // // } // // Path: src/main/java/de/skuzzle/inject/async/schedule/SchedulingService.java // public interface SchedulingService { // // /** // * Schedules the given member method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a non-static member method. // * @param self The object to invoke the method on. // */ // void scheduleMemberMethod(Method method, Object self); // // /** // * Schedules the given static method if it is annotated with {@link Scheduled}. If it // * is not, this method returns without performing any actions. // * // * @param method The method to schedule. Must be a static method. // */ // void scheduleStaticMethod(Method method); // // /** // * Schedules all encountered methods that are annotated with {@link ManuallyStarted}. // * This method should only be called once during the lifetime of your Guice // * {@link Injector}. Calling it multiple times will have no effect. // * // * @since 2.0.0 // */ // void startManualScheduling(); // } // Path: src/test/java/de/skuzzle/inject/async/schedule/SchedulerTypeListenerTest.java import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.lang.reflect.Method; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import de.skuzzle.inject.async.schedule.ExceptionHandler; import de.skuzzle.inject.async.schedule.SchedulerTypeListener; import de.skuzzle.inject.async.schedule.SchedulingService; import de.skuzzle.inject.async.schedule.annotation.CronTrigger; import de.skuzzle.inject.async.schedule.annotation.OnError; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler; when(this.injector.getInstance(Key.get(ExceptionHandler.class))) .thenReturn(this.exceptionHandler); when(this.injector.getInstance(Key.get(ScheduledExecutorService.class))) .thenReturn(this.scheduler); } private static <T> Provider<T> provider(T t) { return () -> t; } @Scheduled @CronTrigger("* * * * * *") @Scheduler(ScheduledExecutorService.class) @OnError(ExceptionHandler.class) public void methodWithTrigger() { } @Scheduled @CronTrigger("* * * * * *") @Scheduler(ScheduledExecutorService.class) @OnError(ExceptionHandler.class) public static void staticMethodWithTrigger() { } @Test public void testHear() throws Exception { final Method expectedMethod = getClass().getMethod("methodWithTrigger"); final Method expectedStaticMethod = getClass() .getMethod("staticMethodWithTrigger"); final TypeLiteral<SchedulerTypeListenerTest> type = new TypeLiteral<SchedulerTypeListenerTest>() {};
final SchedulerTypeListener subject = new SchedulerTypeListener(
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/guice/KeysTest.java
// Path: src/main/java/de/skuzzle/inject/async/guice/Keys.java // public final class Keys { // // /** Fall back key if the user did not bind any scheduled executor service. */ // static final Key<? extends ScheduledExecutorService> DEFAULT_SCHEDULER_KEY = Key // .get(ScheduledExecutorService.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any exception handlder. */ // private static final Key<? extends ExceptionHandler> DEFAULT_EXCEPTION_HANDLER_KEY = Key // .get(ExceptionHandler.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any executor service. */ // static final Key<? extends ExecutorService> DEFAULT_EXECUTOR_KEY = Key // .get(ExecutorService.class, DefaultBinding.class); // // private Keys() { // // hidden ctor // } // // /** // * Finds the key of the {@link ExceptionHandler} to use for the given method. // * // * @param method The method to find the key for. // * @return The exception handler key. // */ // public static Key<? extends ExceptionHandler> getExceptionHandler(Method method) { // // TODO: must support BindingAnnotations // final OnError onError = method.getAnnotation(OnError.class); // if (onError != null) { // return Key.get(onError.value()); // } // return DEFAULT_EXCEPTION_HANDLER_KEY; // } // // /** // * Finds the key of the {@link ExecutorService} to use to execute the given method. // * // * @param method The method to find the key for. // * @return The ExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ExecutorService> getExecutorKey(Method method) { // final Class<? extends ExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Executor.class)) { // type = method.getAnnotation(Executor.class).value(); // executorSpecified = true; // } else { // type = ExecutorService.class; // } // return (Key<? extends ExecutorService>) createKey(type, method, // DEFAULT_EXECUTOR_KEY, executorSpecified); // } // // /** // * Finds the key of the {@link ScheduledExecutorService} to use to execute the given // * method. // * // * @param method the method to find the key for. // * @return The ScheduledExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ScheduledExecutorService> getSchedulerKey(Method method) { // final Class<? extends ScheduledExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Scheduler.class)) { // type = method.getAnnotation(Scheduler.class).value(); // executorSpecified = true; // } else { // type = ScheduledExecutorService.class; // } // return (Key<? extends ScheduledExecutorService>) createKey(type, method, // DEFAULT_SCHEDULER_KEY, executorSpecified); // } // // private static Key<?> createKey( // Class<?> type, // Method method, // Key<?> defaultKey, // boolean typeGiven) { // // final Errors errors = new Errors(method); // final Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, method, method.getAnnotations()); // errors.throwConfigurationExceptionIfErrorsExist(); // final Key<?> key; // if (bindingAnnotation == null && typeGiven) { // key = Key.get(type); // } else if (bindingAnnotation == null) { // key = defaultKey; // } else { // key = Key.get(type, bindingAnnotation); // } // return key; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import javax.inject.Named; import org.junit.Test; import com.google.inject.Key; import de.skuzzle.inject.async.guice.Keys; import de.skuzzle.inject.async.methods.annotation.Executor; import de.skuzzle.inject.async.schedule.annotation.Scheduler;
package de.skuzzle.inject.async.guice; public class KeysTest { public void methodWithNoAnnotations() { } @Named("foo") public void methodWithBindingAnnoation() { } @Executor(ScheduledExecutorService.class) @Scheduler(ScheduledExecutorService.class) public void methodWithExecutorOnly() { } @com.google.inject.name.Named("xyz") @Executor(ScheduledExecutorService.class) public void methodWithBindingAndType() { } private void assertType(Class<?> type, Key<?> key) { assertEquals(type, key.getTypeLiteral().getRawType()); } private void assertBindingAnnotation( Class<? extends Annotation> bindingAnnotationType, Key<?> key) { assertEquals(bindingAnnotationType, key.getAnnotationType()); } private Method getMethod(String name) throws NoSuchMethodException, SecurityException { return getClass().getMethod(name); } @Test public void testFallBackDefault() throws Exception { final Method method = getMethod("methodWithNoAnnotations");
// Path: src/main/java/de/skuzzle/inject/async/guice/Keys.java // public final class Keys { // // /** Fall back key if the user did not bind any scheduled executor service. */ // static final Key<? extends ScheduledExecutorService> DEFAULT_SCHEDULER_KEY = Key // .get(ScheduledExecutorService.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any exception handlder. */ // private static final Key<? extends ExceptionHandler> DEFAULT_EXCEPTION_HANDLER_KEY = Key // .get(ExceptionHandler.class, DefaultBinding.class); // // /** Fall back key if the user did not bind any executor service. */ // static final Key<? extends ExecutorService> DEFAULT_EXECUTOR_KEY = Key // .get(ExecutorService.class, DefaultBinding.class); // // private Keys() { // // hidden ctor // } // // /** // * Finds the key of the {@link ExceptionHandler} to use for the given method. // * // * @param method The method to find the key for. // * @return The exception handler key. // */ // public static Key<? extends ExceptionHandler> getExceptionHandler(Method method) { // // TODO: must support BindingAnnotations // final OnError onError = method.getAnnotation(OnError.class); // if (onError != null) { // return Key.get(onError.value()); // } // return DEFAULT_EXCEPTION_HANDLER_KEY; // } // // /** // * Finds the key of the {@link ExecutorService} to use to execute the given method. // * // * @param method The method to find the key for. // * @return The ExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ExecutorService> getExecutorKey(Method method) { // final Class<? extends ExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Executor.class)) { // type = method.getAnnotation(Executor.class).value(); // executorSpecified = true; // } else { // type = ExecutorService.class; // } // return (Key<? extends ExecutorService>) createKey(type, method, // DEFAULT_EXECUTOR_KEY, executorSpecified); // } // // /** // * Finds the key of the {@link ScheduledExecutorService} to use to execute the given // * method. // * // * @param method the method to find the key for. // * @return The ScheduledExecutorService key. // */ // @SuppressWarnings("unchecked") // public static Key<? extends ScheduledExecutorService> getSchedulerKey(Method method) { // final Class<? extends ScheduledExecutorService> type; // boolean executorSpecified = false; // if (method.isAnnotationPresent(Scheduler.class)) { // type = method.getAnnotation(Scheduler.class).value(); // executorSpecified = true; // } else { // type = ScheduledExecutorService.class; // } // return (Key<? extends ScheduledExecutorService>) createKey(type, method, // DEFAULT_SCHEDULER_KEY, executorSpecified); // } // // private static Key<?> createKey( // Class<?> type, // Method method, // Key<?> defaultKey, // boolean typeGiven) { // // final Errors errors = new Errors(method); // final Annotation bindingAnnotation = Annotations.findBindingAnnotation(errors, method, method.getAnnotations()); // errors.throwConfigurationExceptionIfErrorsExist(); // final Key<?> key; // if (bindingAnnotation == null && typeGiven) { // key = Key.get(type); // } else if (bindingAnnotation == null) { // key = defaultKey; // } else { // key = Key.get(type, bindingAnnotation); // } // return key; // } // } // Path: src/test/java/de/skuzzle/inject/async/guice/KeysTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import javax.inject.Named; import org.junit.Test; import com.google.inject.Key; import de.skuzzle.inject.async.guice.Keys; import de.skuzzle.inject.async.methods.annotation.Executor; import de.skuzzle.inject.async.schedule.annotation.Scheduler; package de.skuzzle.inject.async.guice; public class KeysTest { public void methodWithNoAnnotations() { } @Named("foo") public void methodWithBindingAnnoation() { } @Executor(ScheduledExecutorService.class) @Scheduler(ScheduledExecutorService.class) public void methodWithExecutorOnly() { } @com.google.inject.name.Named("xyz") @Executor(ScheduledExecutorService.class) public void methodWithBindingAndType() { } private void assertType(Class<?> type, Key<?> key) { assertEquals(type, key.getTypeLiteral().getRawType()); } private void assertBindingAnnotation( Class<? extends Annotation> bindingAnnotationType, Key<?> key) { assertEquals(bindingAnnotationType, key.getAnnotationType()); } private Method getMethod(String name) throws NoSuchMethodException, SecurityException { return getClass().getMethod(name); } @Test public void testFallBackDefault() throws Exception { final Method method = getMethod("methodWithNoAnnotations");
final Key<? extends ExecutorService> key = Keys.getExecutorKey(method);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/MethodVisitorTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/MethodVisitor.java // public final class MethodVisitor { // // // HACK: during maven compilation, jacoco agents adds a private static method to all // // classes which disturbs the unit tests (that are counting the visited static // // methods). Thus we need to filter out that particular method. // private static final String JACOCO_INIT = "$jacocoInit"; // // private MethodVisitor() { // // hidden ctor // } // // /** // * Starting at given type, traverses all super types (except Object.class) and passes // * each encountered static method (including private ones) to the given consumer. // * // * @param type The type to start traversal. // * @param action Action to execute for each encountered method. // * @since 0.4.0 // */ // public static void forEachStaticMethod(Class<?> type, Consumer<Method> action) { // forEachMethod(type, action, MethodVisitor::isStatic); // } // // /** // * Starting at given type, traverses all super types (except Object.class) and passes // * each encountered member method (including private ones) to the given consumer. // * // * @param type The type to start traversal. // * @param action Action to execute for each encountered method. // */ // public static void forEachMemberMethod(Class<?> type, Consumer<Method> action) { // forEachMethod(type, action, MethodVisitor::notStatic); // } // // private static void forEachMethod(Class<?> type, Consumer<Method> action, // Predicate<Method> filter) { // if (type == Object.class) { // return; // } else { // forEachMethod(type.getSuperclass(), action, filter); // } // Arrays.stream(type.getDeclaredMethods()) // .filter(filter) // .forEach(action); // } // // private static boolean isStatic(Method method) { // return Modifier.isStatic(method.getModifiers()) // && !JACOCO_INIT.equals(method.getName()); // } // // private static boolean notStatic(Method method) { // return !Modifier.isStatic(method.getModifiers()); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.MethodVisitor;
package de.skuzzle.inject.async.schedule; public class MethodVisitorTest { public static class SuperClass { public static void staticSuperMethod() { } public void publicSuperMethod() { } private void privateSuperMethod() { } } public static class SubClass extends SuperClass { private static void staticPrivateMethod() { } public void pulicMethod() { } private void privateMethod() { } } @Before public void setUp() throws Exception { } @Test public void testVisitAll() throws Exception { final Set<Method> visited = new HashSet<>();
// Path: src/main/java/de/skuzzle/inject/async/schedule/MethodVisitor.java // public final class MethodVisitor { // // // HACK: during maven compilation, jacoco agents adds a private static method to all // // classes which disturbs the unit tests (that are counting the visited static // // methods). Thus we need to filter out that particular method. // private static final String JACOCO_INIT = "$jacocoInit"; // // private MethodVisitor() { // // hidden ctor // } // // /** // * Starting at given type, traverses all super types (except Object.class) and passes // * each encountered static method (including private ones) to the given consumer. // * // * @param type The type to start traversal. // * @param action Action to execute for each encountered method. // * @since 0.4.0 // */ // public static void forEachStaticMethod(Class<?> type, Consumer<Method> action) { // forEachMethod(type, action, MethodVisitor::isStatic); // } // // /** // * Starting at given type, traverses all super types (except Object.class) and passes // * each encountered member method (including private ones) to the given consumer. // * // * @param type The type to start traversal. // * @param action Action to execute for each encountered method. // */ // public static void forEachMemberMethod(Class<?> type, Consumer<Method> action) { // forEachMethod(type, action, MethodVisitor::notStatic); // } // // private static void forEachMethod(Class<?> type, Consumer<Method> action, // Predicate<Method> filter) { // if (type == Object.class) { // return; // } else { // forEachMethod(type.getSuperclass(), action, filter); // } // Arrays.stream(type.getDeclaredMethods()) // .filter(filter) // .forEach(action); // } // // private static boolean isStatic(Method method) { // return Modifier.isStatic(method.getModifiers()) // && !JACOCO_INIT.equals(method.getName()); // } // // private static boolean notStatic(Method method) { // return !Modifier.isStatic(method.getModifiers()); // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/MethodVisitorTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import org.junit.Before; import org.junit.Test; import de.skuzzle.inject.async.schedule.MethodVisitor; package de.skuzzle.inject.async.schedule; public class MethodVisitorTest { public static class SuperClass { public static void staticSuperMethod() { } public void publicSuperMethod() { } private void privateSuperMethod() { } } public static class SubClass extends SuperClass { private static void staticPrivateMethod() { } public void pulicMethod() { } private void privateMethod() { } } @Before public void setUp() throws Exception { } @Test public void testVisitAll() throws Exception { final Set<Method> visited = new HashSet<>();
MethodVisitor.forEachMemberMethod(SubClass.class, visited::add);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/annotation/SimpleScheduleTypeTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/annotation/SimpleScheduleType.java // public enum SimpleScheduleType { // /** // * Used to schedule a command using // * {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)} // * . // */ // AT_FIXED_RATE { // // @Override // public ScheduledFuture<?> schedule(ScheduledExecutorService scheduler, // Runnable command, long initialDelay, long period, TimeUnit unit) { // return scheduler.scheduleAtFixedRate(command, initialDelay, period, unit); // } // // }, // /** // * Used to schedule a command using // * {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)} // */ // WITH_FIXED_DELAY { // @Override // public ScheduledFuture<?> schedule(ScheduledExecutorService scheduler, // Runnable command, long initialDelay, long delay, TimeUnit unit) { // return scheduler.scheduleWithFixedDelay(command, initialDelay, delay, unit); // } // }; // // /** // * Schedules a {@link Runnable} according to this scheduling type. // * // * @param scheduler The scheduler to schedule the command with. // * @param command The command to schedule. // * @param initialDelay The initial delay. // * @param rate The scheduling rate. // * @param unit Time unit in which rate and delay are interpreted. // * @return The future object. // */ // public abstract ScheduledFuture<?> schedule(ScheduledExecutorService scheduler, // Runnable command, long initialDelay, long rate, TimeUnit unit); // }
import static org.mockito.Mockito.verify; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import de.skuzzle.inject.async.schedule.annotation.SimpleScheduleType;
package de.skuzzle.inject.async.schedule.annotation; @RunWith(MockitoJUnitRunner.class) public class SimpleScheduleTypeTest { @Mock private ScheduledExecutorService scheduler; @Mock private Runnable command; @Before public void setUp() throws Exception {} @Test public void testAtFixedRate() throws Exception {
// Path: src/main/java/de/skuzzle/inject/async/schedule/annotation/SimpleScheduleType.java // public enum SimpleScheduleType { // /** // * Used to schedule a command using // * {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)} // * . // */ // AT_FIXED_RATE { // // @Override // public ScheduledFuture<?> schedule(ScheduledExecutorService scheduler, // Runnable command, long initialDelay, long period, TimeUnit unit) { // return scheduler.scheduleAtFixedRate(command, initialDelay, period, unit); // } // // }, // /** // * Used to schedule a command using // * {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)} // */ // WITH_FIXED_DELAY { // @Override // public ScheduledFuture<?> schedule(ScheduledExecutorService scheduler, // Runnable command, long initialDelay, long delay, TimeUnit unit) { // return scheduler.scheduleWithFixedDelay(command, initialDelay, delay, unit); // } // }; // // /** // * Schedules a {@link Runnable} according to this scheduling type. // * // * @param scheduler The scheduler to schedule the command with. // * @param command The command to schedule. // * @param initialDelay The initial delay. // * @param rate The scheduling rate. // * @param unit Time unit in which rate and delay are interpreted. // * @return The future object. // */ // public abstract ScheduledFuture<?> schedule(ScheduledExecutorService scheduler, // Runnable command, long initialDelay, long rate, TimeUnit unit); // } // Path: src/test/java/de/skuzzle/inject/async/schedule/annotation/SimpleScheduleTypeTest.java import static org.mockito.Mockito.verify; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import de.skuzzle.inject.async.schedule.annotation.SimpleScheduleType; package de.skuzzle.inject.async.schedule.annotation; @RunWith(MockitoJUnitRunner.class) public class SimpleScheduleTypeTest { @Mock private ScheduledExecutorService scheduler; @Mock private Runnable command; @Before public void setUp() throws Exception {} @Test public void testAtFixedRate() throws Exception {
SimpleScheduleType.AT_FIXED_RATE.schedule(this.scheduler, this.command, 5, 6,
skuzzle/guice-async-extension
src/it/java/de/skuzzle/inject/async/CallerRunsStrategySchedulingTest.java
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // }
import static org.junit.Assert.assertTrue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.junit.Before; import org.junit.Test; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Provides; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler;
System.out.println("First"); firstCalled = true; Thread.sleep(2000); } catch (final InterruptedException e) { throw new RuntimeException(e); } } @Scheduled @Scheduler(ScheduledExecutorService.class) @Named("only-one-thread") @DelayedTrigger(500) public static void scheduleSecond() { secondCalled = true; System.out.println("second"); } } @Inject private TypeWithScheduledMethods typeWithScheduledMethods; @Inject @Named("only-one-thread") private ScheduledExecutorService executor; @Before public void setup() { Guice.createInjector(new AbstractModule() { @Override protected void configure() {
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // } // Path: src/it/java/de/skuzzle/inject/async/CallerRunsStrategySchedulingTest.java import static org.junit.Assert.assertTrue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.junit.Before; import org.junit.Test; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Provides; import de.skuzzle.inject.async.guice.GuiceAsync; import de.skuzzle.inject.async.schedule.annotation.DelayedTrigger; import de.skuzzle.inject.async.schedule.annotation.Scheduled; import de.skuzzle.inject.async.schedule.annotation.Scheduler; System.out.println("First"); firstCalled = true; Thread.sleep(2000); } catch (final InterruptedException e) { throw new RuntimeException(e); } } @Scheduled @Scheduler(ScheduledExecutorService.class) @Named("only-one-thread") @DelayedTrigger(500) public static void scheduleSecond() { secondCalled = true; System.out.println("second"); } } @Inject private TypeWithScheduledMethods typeWithScheduledMethods; @Inject @Named("only-one-thread") private ScheduledExecutorService executor; @Before public void setup() { Guice.createInjector(new AbstractModule() { @Override protected void configure() {
GuiceAsync.enableFor(binder());
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/guice/GuiceAsyncTest.java
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // }
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.Test; import com.google.inject.Binder; import com.google.inject.Guice; import de.skuzzle.inject.async.guice.GuiceAsync;
package de.skuzzle.inject.async.guice; public class GuiceAsyncTest { @Test public void testEnable() throws Exception { final Binder binder = mock(Binder.class);
// Path: src/main/java/de/skuzzle/inject/async/guice/GuiceAsync.java // public final class GuiceAsync { // // private GuiceAsync() { // // hidden constructor // } // // /** // * Enable support for the {@link Async} annotation in classes that are used with the // * injector that will be created from the given {@link Binder}. // * // * @param binder The binder to register with. // */ // public static void enableFor(Binder binder) { // enableFeaturesFor(binder, DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Enable support for the given {@link DefaultFeatures features}. Allows to separately // * enable support for async or scheduled. // * // * @param binder The binder to register with. // * @param features The features to enable. // * @since 2.0.0 // * @see DefaultFeatures // */ // public static void enableFeaturesFor(Binder binder, Feature... features) { // checkArgument(binder != null, "binder must not be null"); // binder.install(createModuleWithFeatures(features)); // } // // /** // * Creates a module that can be used to enable asynchronous method and scheduling // * support. // * // * @return A module that exposes all bindings needed for asynchronous method support. // * @since 0.2.0 // */ // public static Module createModule() { // return createModuleWithFeatures(DefaultFeatures.ASYNC, DefaultFeatures.SCHEDULE); // } // // /** // * Creates a module that can be used to enable the given features. // * // * @param features The features to enable. // * @return The module. // * @since 2.0.0 // */ // public static Module createModuleWithFeatures(Feature... features) { // final GuiceAsync principal = new GuiceAsync(); // final Set<Feature> featureSet = ImmutableSet.copyOf(features); // return new GuiceAsyncModule(principal, featureSet); // } // // private static final class GuiceAsyncModule extends AbstractModule { // // private final GuiceAsync principal; // private final Set<Feature> enabledFeatures; // // public GuiceAsyncModule(GuiceAsync principal, Set<Feature> features) { // checkArgument(!features.isEmpty(), "Set of features must not be empty"); // this.principal = principal; // this.enabledFeatures = features; // } // // @Override // protected void configure() { // enabledFeatures.forEach(feature -> feature.installModuleTo(binder(), principal)); // bind(GuiceAsyncService.class).to(GuiceAsyncServiceImpl.class).in(Singleton.class); // } // // @Provides // @Singleton // @DefaultBinding // Set<Feature> provideFeatures() { // return enabledFeatures; // } // // @Provides // @Singleton // @DefaultBinding // ThreadFactory provideThreadFactory() { // return new ThreadFactoryBuilder() // .setNameFormat("guice-async-%d") // .build(); // } // // @Override // public int hashCode() { // return 31; // } // // @Override // public boolean equals(Object obj) { // return obj instanceof GuiceAsyncModule; // } // } // } // Path: src/test/java/de/skuzzle/inject/async/guice/GuiceAsyncTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.Test; import com.google.inject.Binder; import com.google.inject.Guice; import de.skuzzle.inject.async.guice.GuiceAsync; package de.skuzzle.inject.async.guice; public class GuiceAsyncTest { @Test public void testEnable() throws Exception { final Binder binder = mock(Binder.class);
GuiceAsync.enableFor(binder);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/MapBasedScopeTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/MapBasedScope.java // public class MapBasedScope implements Scope { // // private enum NullObject { // INSTANCE // } // // private final Provider<Map<String, Object>> mapProvider; // // private MapBasedScope(Provider<Map<String, Object>> mapProvider) { // this.mapProvider = mapProvider; // } // // /** // * Creates a new scope which stores all instances into the map provided by the passed // * provider. The actual scope is thus determined by the map instance returned by the // * provider. // * // * @param mapProvider Provider which supplies the map for storing scoped instances. // * @return The scope. // */ // public static Scope withMapSupplier(Provider<Map<String, Object>> mapProvider) { // checkArgument(mapProvider != null, "mapProvider is null"); // return new MapBasedScope(mapProvider); // } // // @Override // public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) { // final String name = key.toString(); // return () -> { // final Map<String, Object> beans = this.mapProvider.get(); // // synchronized (beans) { // final Object bean = beans.get(name); // if (bean == NullObject.INSTANCE) { // return null; // } // // @SuppressWarnings("unchecked") // T t = (T) bean; // if (t == null) { // t = unscoped.get(); // if (!Scopes.isCircularProxy(t)) { // beans.put(name, t == null ? NullObject.INSTANCE : t); // } // } // return t; // } // }; // } // }
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.internal.CircularDependencyProxy; import de.skuzzle.inject.async.schedule.MapBasedScope;
package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class MapBasedScopeTest { private Map<String, Object> scopeMap; private Scope subject; @Before public void setup() { this.scopeMap = new HashMap<>(); final Provider<Map<String, Object>> provider = () -> this.scopeMap;
// Path: src/main/java/de/skuzzle/inject/async/schedule/MapBasedScope.java // public class MapBasedScope implements Scope { // // private enum NullObject { // INSTANCE // } // // private final Provider<Map<String, Object>> mapProvider; // // private MapBasedScope(Provider<Map<String, Object>> mapProvider) { // this.mapProvider = mapProvider; // } // // /** // * Creates a new scope which stores all instances into the map provided by the passed // * provider. The actual scope is thus determined by the map instance returned by the // * provider. // * // * @param mapProvider Provider which supplies the map for storing scoped instances. // * @return The scope. // */ // public static Scope withMapSupplier(Provider<Map<String, Object>> mapProvider) { // checkArgument(mapProvider != null, "mapProvider is null"); // return new MapBasedScope(mapProvider); // } // // @Override // public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) { // final String name = key.toString(); // return () -> { // final Map<String, Object> beans = this.mapProvider.get(); // // synchronized (beans) { // final Object bean = beans.get(name); // if (bean == NullObject.INSTANCE) { // return null; // } // // @SuppressWarnings("unchecked") // T t = (T) bean; // if (t == null) { // t = unscoped.get(); // if (!Scopes.isCircularProxy(t)) { // beans.put(name, t == null ? NullObject.INSTANCE : t); // } // } // return t; // } // }; // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/MapBasedScopeTest.java import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.internal.CircularDependencyProxy; import de.skuzzle.inject.async.schedule.MapBasedScope; package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class MapBasedScopeTest { private Map<String, Object> scopeMap; private Scope subject; @Before public void setup() { this.scopeMap = new HashMap<>(); final Provider<Map<String, Object>> provider = () -> this.scopeMap;
this.subject = MapBasedScope.withMapSupplier(provider);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/InvokeMethodRunnableTest.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/InvokeMethodRunnable.java // class InvokeMethodRunnable implements Runnable { // // private final InjectedMethodInvocation invocation; // // private InvokeMethodRunnable(InjectedMethodInvocation invocation) { // this.invocation = invocation; // } // // /** // * Creates a Runnable which will proceed the given MethodInvocation when being // * executed. // * // * @param invocation the invocation to call. // * @return The runnable. // */ // public static Runnable of(InjectedMethodInvocation invocation) { // checkArgument(invocation != null); // return new InvokeMethodRunnable(invocation); // } // // @Override // public void run() { // try { // this.invocation.proceed(); // } catch (final InvocationTargetException e) { // Throwables.throwIfUnchecked(e.getTargetException()); // throw new RuntimeException(e); // } catch (final Throwable e) { // Throwables.throwIfUnchecked(e); // throw new RuntimeException(e); // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("invocation", invocation) // .toString(); // } // }
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import de.skuzzle.inject.async.schedule.InvokeMethodRunnable;
package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class InvokeMethodRunnableTest { @Mock private InjectedMethodInvocation invocation; @Before public void setUp() throws Exception {} @Test public void testRun() throws Throwable {
// Path: src/main/java/de/skuzzle/inject/async/schedule/InvokeMethodRunnable.java // class InvokeMethodRunnable implements Runnable { // // private final InjectedMethodInvocation invocation; // // private InvokeMethodRunnable(InjectedMethodInvocation invocation) { // this.invocation = invocation; // } // // /** // * Creates a Runnable which will proceed the given MethodInvocation when being // * executed. // * // * @param invocation the invocation to call. // * @return The runnable. // */ // public static Runnable of(InjectedMethodInvocation invocation) { // checkArgument(invocation != null); // return new InvokeMethodRunnable(invocation); // } // // @Override // public void run() { // try { // this.invocation.proceed(); // } catch (final InvocationTargetException e) { // Throwables.throwIfUnchecked(e.getTargetException()); // throw new RuntimeException(e); // } catch (final Throwable e) { // Throwables.throwIfUnchecked(e); // throw new RuntimeException(e); // } // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("invocation", invocation) // .toString(); // } // } // Path: src/test/java/de/skuzzle/inject/async/schedule/InvokeMethodRunnableTest.java import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import de.skuzzle.inject.async.schedule.InvokeMethodRunnable; package de.skuzzle.inject.async.schedule; @RunWith(MockitoJUnitRunner.class) public class InvokeMethodRunnableTest { @Mock private InjectedMethodInvocation invocation; @Before public void setUp() throws Exception {} @Test public void testRun() throws Throwable {
final Runnable r = InvokeMethodRunnable.of(this.invocation);
skuzzle/guice-async-extension
src/test/java/de/skuzzle/inject/async/schedule/trigger/AbstractMethodHolder.java
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // }
import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Binder; import com.google.inject.Module; import de.skuzzle.inject.async.schedule.ScheduledContext;
package de.skuzzle.inject.async.schedule.trigger; abstract class AbstractMethodHolder implements Module { private static final Logger LOG = LoggerFactory.getLogger(AbstractMethodHolder.class); protected final CountDownLatch throwingException = new CountDownLatch(1); protected final CountDownLatch threeTimes = new CountDownLatch(3); protected final CountDownLatch cancel = new CountDownLatch(4); protected final MockExceptionHandler exceptionHandler = new MockExceptionHandler(throwingException); @Override public void configure(Binder binder) { binder.bind((Class) this.getClass()).toInstance(this); binder.bind(MockExceptionHandler.class).toInstance(exceptionHandler); } protected void throwingException() { throw new RuntimeException("This exception is expected to be thrown!"); } protected void threeTimes() { threeTimes.countDown(); }
// Path: src/main/java/de/skuzzle/inject/async/schedule/ScheduledContext.java // public interface ScheduledContext { // // /** // * Gets the scheduled method to which this scope belongs. // * // * @return The method. // */ // Method getMethod(); // // /** // * Returns the object on which this method will be invoked. Returns null in case this // * context belongs to a static method. // * // * @return The object. // */ // Object getSelf(); // // /** // * Gets the properties that are attached to this context. This map is also used by the // * {@link ScheduledScope} implementation to store cached objects. // * // * @return The context properties. // */ // Map<String, Object> getProperties(); // // /** // * Gets the number of times that this method has been executed. Note: the value might // * be out of date by the time it is returned. You might want to use // * {@link ExecutionContext#getExecutionNr()} to figure out the number of the current // * execution. // * // * <p> // * Since version 1.1.0 this number no longer denotes the number of times that the // * method had <em>finished</em> executing. It now returns the number of times that the // * method has been called, disregarding whether all calls have already returned. // * </p> // * // * @return The number of times this method has been called. // */ // int getExecutionCount(); // // /** // * Gets the current execution context. This will yield a new object for every time the // * method is scheduled again. // * // * @return The execution context. // */ // ExecutionContext getExecution(); // // /** // * Cancels this scheduled method. The method will never be scheduled again on the // * current instance after this method has been called. Current executions will be // * interrupted if the flag is passed. // * <p> // * In case the scheduled method is not contained in a singleton scoped object it // * <b>will</b> be scheduled again once another instance of the object has been // * created. If the scheduled method was a static one, it will never be scheduled // * again. // * </p> // * // * @param mayInterrupt Whether running executions may be interrupted. // * @since 0.4.0 // */ // void cancel(boolean mayInterrupt); // // /** // * Atomically updates the Future object that represents the current scheduling. The // * future will be obtained by invoking the given supplier. This method should only be // * called by {@link TriggerStrategy} implementations to make the context support the // * {@link #cancel(boolean)} method. If no Future object is set by the strategy, // * canceling will not be possible. // * // * @param futureSupplier Supplies the future instance. // */ // void updateFuture(Supplier<Future<?>> futureSupplier); // // /** // * Returns true if cancel has been called on this context. // * // * @return Whether this scheduled method has been cancelled. // * @since 0.4.0 // */ // boolean isCancelled(); // } // Path: src/test/java/de/skuzzle/inject/async/schedule/trigger/AbstractMethodHolder.java import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Binder; import com.google.inject.Module; import de.skuzzle.inject.async.schedule.ScheduledContext; package de.skuzzle.inject.async.schedule.trigger; abstract class AbstractMethodHolder implements Module { private static final Logger LOG = LoggerFactory.getLogger(AbstractMethodHolder.class); protected final CountDownLatch throwingException = new CountDownLatch(1); protected final CountDownLatch threeTimes = new CountDownLatch(3); protected final CountDownLatch cancel = new CountDownLatch(4); protected final MockExceptionHandler exceptionHandler = new MockExceptionHandler(throwingException); @Override public void configure(Binder binder) { binder.bind((Class) this.getClass()).toInstance(this); binder.bind(MockExceptionHandler.class).toInstance(exceptionHandler); } protected void throwingException() { throw new RuntimeException("This exception is expected to be thrown!"); } protected void threeTimes() { threeTimes.countDown(); }
protected void cancel(ScheduledContext ctx) {
liucijus/jinsist
expectations/src/main/java/jinsist/expectations/Expectations.java
// Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // }
import jinsist.matchers.Arguments; import java.lang.reflect.Method;
package jinsist.expectations; public interface Expectations { <ReturnType, MockType> void recordStub( Class<MockType> classToMock, MockType instance, Method method,
// Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // Path: expectations/src/main/java/jinsist/expectations/Expectations.java import jinsist.matchers.Arguments; import java.lang.reflect.Method; package jinsist.expectations; public interface Expectations { <ReturnType, MockType> void recordStub( Class<MockType> classToMock, MockType instance, Method method,
Arguments arguments,
liucijus/jinsist
expectations/src/test/java/jinsist/expectations/ReportExpectationsTest.java
// Path: expectations/src/test/java/jinsist/expectations/testtypes/TestCollaborator.java // public class TestCollaborator implements Collaborator { // @Override // public void firstMethod() { // // } // // @Override // public void secondMethod() { // // } // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // }
import jinsist.expectations.testtypes.TestCollaborator; import jinsist.matchers.Arguments; import org.junit.Test; import java.lang.reflect.Method; import static com.googlecode.catchexception.CatchException.caughtException; import static com.googlecode.catchexception.CatchException.verifyException; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals;
package jinsist.expectations; public class ReportExpectationsTest { private Expectations orderedExpectations = new OrderedExpectations();
// Path: expectations/src/test/java/jinsist/expectations/testtypes/TestCollaborator.java // public class TestCollaborator implements Collaborator { // @Override // public void firstMethod() { // // } // // @Override // public void secondMethod() { // // } // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // Path: expectations/src/test/java/jinsist/expectations/ReportExpectationsTest.java import jinsist.expectations.testtypes.TestCollaborator; import jinsist.matchers.Arguments; import org.junit.Test; import java.lang.reflect.Method; import static com.googlecode.catchexception.CatchException.caughtException; import static com.googlecode.catchexception.CatchException.verifyException; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; package jinsist.expectations; public class ReportExpectationsTest { private Expectations orderedExpectations = new OrderedExpectations();
private TestCollaborator instance = new TestCollaborator();
liucijus/jinsist
expectations/src/test/java/jinsist/expectations/ReportExpectationsTest.java
// Path: expectations/src/test/java/jinsist/expectations/testtypes/TestCollaborator.java // public class TestCollaborator implements Collaborator { // @Override // public void firstMethod() { // // } // // @Override // public void secondMethod() { // // } // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // }
import jinsist.expectations.testtypes.TestCollaborator; import jinsist.matchers.Arguments; import org.junit.Test; import java.lang.reflect.Method; import static com.googlecode.catchexception.CatchException.caughtException; import static com.googlecode.catchexception.CatchException.verifyException; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals;
package jinsist.expectations; public class ReportExpectationsTest { private Expectations orderedExpectations = new OrderedExpectations(); private TestCollaborator instance = new TestCollaborator(); private Class<TestCollaborator> mockClass = TestCollaborator.class; private Method method1 = mockClass.getMethod("firstMethod"); private Method method2 = mockClass.getMethod("secondMethod");
// Path: expectations/src/test/java/jinsist/expectations/testtypes/TestCollaborator.java // public class TestCollaborator implements Collaborator { // @Override // public void firstMethod() { // // } // // @Override // public void secondMethod() { // // } // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // Path: expectations/src/test/java/jinsist/expectations/ReportExpectationsTest.java import jinsist.expectations.testtypes.TestCollaborator; import jinsist.matchers.Arguments; import org.junit.Test; import java.lang.reflect.Method; import static com.googlecode.catchexception.CatchException.caughtException; import static com.googlecode.catchexception.CatchException.verifyException; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; package jinsist.expectations; public class ReportExpectationsTest { private Expectations orderedExpectations = new OrderedExpectations(); private TestCollaborator instance = new TestCollaborator(); private Class<TestCollaborator> mockClass = TestCollaborator.class; private Method method1 = mockClass.getMethod("firstMethod"); private Method method2 = mockClass.getMethod("secondMethod");
private Arguments noArgumentsMatchers = new Arguments(emptyList());
liucijus/jinsist
expectations/src/main/java/jinsist/expectations/ExpectationEvent.java
// Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: report/src/main/java/jinsist/report/FormattedMethod.java // public class FormattedMethod { // private final Class<?> type; // private final Method method; // private final List<?> arguments; // // public FormattedMethod(Class<?> type, Method method, List<?> arguments) { // this.type = type; // this.method = method; // this.arguments = arguments; // } // // @Override // public String toString() { // return String.format("%s.%s(%s)", type.getSimpleName(), method.getName(), formatArguments(arguments)); // } // // private String formatArguments(List<?> arguments) { // return arguments.stream().map(Object::toString).collect(Collectors.joining(", ")); // } // } // // Path: report/src/main/java/jinsist/report/ReportEvent.java // public interface ReportEvent { // }
import jinsist.matchers.Arguments; import jinsist.report.FormattedMethod; import jinsist.report.ReportEvent; import java.lang.reflect.Method;
package jinsist.expectations; public class ExpectationEvent<MockType> implements ReportEvent { private final Class<MockType> classToMock; private final Method method;
// Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: report/src/main/java/jinsist/report/FormattedMethod.java // public class FormattedMethod { // private final Class<?> type; // private final Method method; // private final List<?> arguments; // // public FormattedMethod(Class<?> type, Method method, List<?> arguments) { // this.type = type; // this.method = method; // this.arguments = arguments; // } // // @Override // public String toString() { // return String.format("%s.%s(%s)", type.getSimpleName(), method.getName(), formatArguments(arguments)); // } // // private String formatArguments(List<?> arguments) { // return arguments.stream().map(Object::toString).collect(Collectors.joining(", ")); // } // } // // Path: report/src/main/java/jinsist/report/ReportEvent.java // public interface ReportEvent { // } // Path: expectations/src/main/java/jinsist/expectations/ExpectationEvent.java import jinsist.matchers.Arguments; import jinsist.report.FormattedMethod; import jinsist.report.ReportEvent; import java.lang.reflect.Method; package jinsist.expectations; public class ExpectationEvent<MockType> implements ReportEvent { private final Class<MockType> classToMock; private final Method method;
private final Arguments arguments;
liucijus/jinsist
expectations/src/main/java/jinsist/expectations/ExpectationEvent.java
// Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: report/src/main/java/jinsist/report/FormattedMethod.java // public class FormattedMethod { // private final Class<?> type; // private final Method method; // private final List<?> arguments; // // public FormattedMethod(Class<?> type, Method method, List<?> arguments) { // this.type = type; // this.method = method; // this.arguments = arguments; // } // // @Override // public String toString() { // return String.format("%s.%s(%s)", type.getSimpleName(), method.getName(), formatArguments(arguments)); // } // // private String formatArguments(List<?> arguments) { // return arguments.stream().map(Object::toString).collect(Collectors.joining(", ")); // } // } // // Path: report/src/main/java/jinsist/report/ReportEvent.java // public interface ReportEvent { // }
import jinsist.matchers.Arguments; import jinsist.report.FormattedMethod; import jinsist.report.ReportEvent; import java.lang.reflect.Method;
package jinsist.expectations; public class ExpectationEvent<MockType> implements ReportEvent { private final Class<MockType> classToMock; private final Method method; private final Arguments arguments; ExpectationEvent(Class<MockType> classToMock, Method method, Arguments arguments) { this.classToMock = classToMock; this.method = method; this.arguments = arguments; } @Override public String toString() {
// Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: report/src/main/java/jinsist/report/FormattedMethod.java // public class FormattedMethod { // private final Class<?> type; // private final Method method; // private final List<?> arguments; // // public FormattedMethod(Class<?> type, Method method, List<?> arguments) { // this.type = type; // this.method = method; // this.arguments = arguments; // } // // @Override // public String toString() { // return String.format("%s.%s(%s)", type.getSimpleName(), method.getName(), formatArguments(arguments)); // } // // private String formatArguments(List<?> arguments) { // return arguments.stream().map(Object::toString).collect(Collectors.joining(", ")); // } // } // // Path: report/src/main/java/jinsist/report/ReportEvent.java // public interface ReportEvent { // } // Path: expectations/src/main/java/jinsist/expectations/ExpectationEvent.java import jinsist.matchers.Arguments; import jinsist.report.FormattedMethod; import jinsist.report.ReportEvent; import java.lang.reflect.Method; package jinsist.expectations; public class ExpectationEvent<MockType> implements ReportEvent { private final Class<MockType> classToMock; private final Method method; private final Arguments arguments; ExpectationEvent(Class<MockType> classToMock, Method method, Arguments arguments) { this.classToMock = classToMock; this.method = method; this.arguments = arguments; } @Override public String toString() {
return new FormattedMethod(classToMock, method, arguments.getArgumentMatchers()).toString();
liucijus/jinsist
expectations/src/main/java/jinsist/expectations/ExecuteEvent.java
// Path: report/src/main/java/jinsist/report/FormattedMethod.java // public class FormattedMethod { // private final Class<?> type; // private final Method method; // private final List<?> arguments; // // public FormattedMethod(Class<?> type, Method method, List<?> arguments) { // this.type = type; // this.method = method; // this.arguments = arguments; // } // // @Override // public String toString() { // return String.format("%s.%s(%s)", type.getSimpleName(), method.getName(), formatArguments(arguments)); // } // // private String formatArguments(List<?> arguments) { // return arguments.stream().map(Object::toString).collect(Collectors.joining(", ")); // } // } // // Path: report/src/main/java/jinsist/report/ReportEvent.java // public interface ReportEvent { // }
import jinsist.report.FormattedMethod; import jinsist.report.ReportEvent; import java.lang.reflect.Method; import static java.util.Arrays.asList;
package jinsist.expectations; public class ExecuteEvent<MockType> implements ReportEvent { private final Class<MockType> mockClass; private final Method method; private final Object[] arguments; ExecuteEvent(Class<MockType> mockClass, Method method, Object[] arguments) { this.mockClass = mockClass; this.method = method; this.arguments = arguments; } @Override public String toString() {
// Path: report/src/main/java/jinsist/report/FormattedMethod.java // public class FormattedMethod { // private final Class<?> type; // private final Method method; // private final List<?> arguments; // // public FormattedMethod(Class<?> type, Method method, List<?> arguments) { // this.type = type; // this.method = method; // this.arguments = arguments; // } // // @Override // public String toString() { // return String.format("%s.%s(%s)", type.getSimpleName(), method.getName(), formatArguments(arguments)); // } // // private String formatArguments(List<?> arguments) { // return arguments.stream().map(Object::toString).collect(Collectors.joining(", ")); // } // } // // Path: report/src/main/java/jinsist/report/ReportEvent.java // public interface ReportEvent { // } // Path: expectations/src/main/java/jinsist/expectations/ExecuteEvent.java import jinsist.report.FormattedMethod; import jinsist.report.ReportEvent; import java.lang.reflect.Method; import static java.util.Arrays.asList; package jinsist.expectations; public class ExecuteEvent<MockType> implements ReportEvent { private final Class<MockType> mockClass; private final Method method; private final Object[] arguments; ExecuteEvent(Class<MockType> mockClass, Method method, Object[] arguments) { this.mockClass = mockClass; this.method = method; this.arguments = arguments; } @Override public String toString() {
return new FormattedMethod(mockClass, method, asList(arguments)).toString();
liucijus/jinsist
mock/src/main/java/jinsist/mock/delegators/SetupRecorder.java
// Path: expectations/src/main/java/jinsist/expectations/Expectations.java // public interface Expectations { // <ReturnType, MockType> void recordStub( // Class<MockType> classToMock, // MockType instance, // Method method, // Arguments arguments, // ReturnType result // ); // // <MockType> Object execute( // Class<MockType> classToMock, // MockType instance, // Method method, // Object[] arguments // ); // // void verify(); // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: matchers/src/main/java/jinsist/matchers/EqualsMatcher.java // public class EqualsMatcher<T> implements ArgumentMatcher<T> { // private T value; // // public EqualsMatcher(T value) { // this.value = value; // } // // @Override // public boolean matches(T argument) { // boolean isValueNull = value == null; // boolean isArgumentNull = argument == null; // // return isArgumentNull && isValueNull || !isValueNull && value.equals(argument); // } // // @Override // public String toString() { // return "EqualsMatcher " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // EqualsMatcher<?> that = (EqualsMatcher<?>) o; // // return value != null ? value.equals(that.value) : that.value == null; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // } // // Path: mock/src/main/java/jinsist/mock/SetupResult.java // public class SetupResult { // private boolean wasRecorded = false; // // public void setSuccess() { // this.wasRecorded = true; // } // // void verify() { // if (!wasRecorded) throw new MethodToStubNotFound(); // } // } // // Path: proxy/src/main/java/jinsist/proxy/Delegator.java // public interface Delegator<T> { // Object handle(T instance, Method method, Object[] arguments); // }
import jinsist.expectations.Expectations; import jinsist.matchers.Arguments; import jinsist.matchers.EqualsMatcher; import jinsist.mock.SetupResult; import jinsist.proxy.Delegator; import java.lang.reflect.Method; import java.util.stream.Collectors; import static java.util.Arrays.stream;
package jinsist.mock.delegators; public class SetupRecorder<ReturnType, MockType> implements Delegator<MockType> { private MockType instance; private ReturnType result;
// Path: expectations/src/main/java/jinsist/expectations/Expectations.java // public interface Expectations { // <ReturnType, MockType> void recordStub( // Class<MockType> classToMock, // MockType instance, // Method method, // Arguments arguments, // ReturnType result // ); // // <MockType> Object execute( // Class<MockType> classToMock, // MockType instance, // Method method, // Object[] arguments // ); // // void verify(); // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: matchers/src/main/java/jinsist/matchers/EqualsMatcher.java // public class EqualsMatcher<T> implements ArgumentMatcher<T> { // private T value; // // public EqualsMatcher(T value) { // this.value = value; // } // // @Override // public boolean matches(T argument) { // boolean isValueNull = value == null; // boolean isArgumentNull = argument == null; // // return isArgumentNull && isValueNull || !isValueNull && value.equals(argument); // } // // @Override // public String toString() { // return "EqualsMatcher " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // EqualsMatcher<?> that = (EqualsMatcher<?>) o; // // return value != null ? value.equals(that.value) : that.value == null; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // } // // Path: mock/src/main/java/jinsist/mock/SetupResult.java // public class SetupResult { // private boolean wasRecorded = false; // // public void setSuccess() { // this.wasRecorded = true; // } // // void verify() { // if (!wasRecorded) throw new MethodToStubNotFound(); // } // } // // Path: proxy/src/main/java/jinsist/proxy/Delegator.java // public interface Delegator<T> { // Object handle(T instance, Method method, Object[] arguments); // } // Path: mock/src/main/java/jinsist/mock/delegators/SetupRecorder.java import jinsist.expectations.Expectations; import jinsist.matchers.Arguments; import jinsist.matchers.EqualsMatcher; import jinsist.mock.SetupResult; import jinsist.proxy.Delegator; import java.lang.reflect.Method; import java.util.stream.Collectors; import static java.util.Arrays.stream; package jinsist.mock.delegators; public class SetupRecorder<ReturnType, MockType> implements Delegator<MockType> { private MockType instance; private ReturnType result;
private SetupResult setupResult;
liucijus/jinsist
mock/src/main/java/jinsist/mock/delegators/SetupRecorder.java
// Path: expectations/src/main/java/jinsist/expectations/Expectations.java // public interface Expectations { // <ReturnType, MockType> void recordStub( // Class<MockType> classToMock, // MockType instance, // Method method, // Arguments arguments, // ReturnType result // ); // // <MockType> Object execute( // Class<MockType> classToMock, // MockType instance, // Method method, // Object[] arguments // ); // // void verify(); // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: matchers/src/main/java/jinsist/matchers/EqualsMatcher.java // public class EqualsMatcher<T> implements ArgumentMatcher<T> { // private T value; // // public EqualsMatcher(T value) { // this.value = value; // } // // @Override // public boolean matches(T argument) { // boolean isValueNull = value == null; // boolean isArgumentNull = argument == null; // // return isArgumentNull && isValueNull || !isValueNull && value.equals(argument); // } // // @Override // public String toString() { // return "EqualsMatcher " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // EqualsMatcher<?> that = (EqualsMatcher<?>) o; // // return value != null ? value.equals(that.value) : that.value == null; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // } // // Path: mock/src/main/java/jinsist/mock/SetupResult.java // public class SetupResult { // private boolean wasRecorded = false; // // public void setSuccess() { // this.wasRecorded = true; // } // // void verify() { // if (!wasRecorded) throw new MethodToStubNotFound(); // } // } // // Path: proxy/src/main/java/jinsist/proxy/Delegator.java // public interface Delegator<T> { // Object handle(T instance, Method method, Object[] arguments); // }
import jinsist.expectations.Expectations; import jinsist.matchers.Arguments; import jinsist.matchers.EqualsMatcher; import jinsist.mock.SetupResult; import jinsist.proxy.Delegator; import java.lang.reflect.Method; import java.util.stream.Collectors; import static java.util.Arrays.stream;
package jinsist.mock.delegators; public class SetupRecorder<ReturnType, MockType> implements Delegator<MockType> { private MockType instance; private ReturnType result; private SetupResult setupResult;
// Path: expectations/src/main/java/jinsist/expectations/Expectations.java // public interface Expectations { // <ReturnType, MockType> void recordStub( // Class<MockType> classToMock, // MockType instance, // Method method, // Arguments arguments, // ReturnType result // ); // // <MockType> Object execute( // Class<MockType> classToMock, // MockType instance, // Method method, // Object[] arguments // ); // // void verify(); // } // // Path: matchers/src/main/java/jinsist/matchers/Arguments.java // public class Arguments { // private List<ArgumentMatcher<?>> argumentMatchers; // // public Arguments(List<ArgumentMatcher<?>> argumentMatchers) { // this.argumentMatchers = argumentMatchers; // } // // public boolean matches(Object... arguments) { // int length = argumentMatchers.size(); // if (length != arguments.length) // return false; // else // for (int i = 0; i < length; i++) { // ArgumentMatcher matcher = argumentMatchers.get(i); // @SuppressWarnings("unchecked") // boolean matches = matcher.matches(arguments[i]); // if (!matches) return false; // } // return true; // } // // public List<ArgumentMatcher<?>> getArgumentMatchers() { // return argumentMatchers; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Arguments arguments = (Arguments) o; // // return argumentMatchers.equals(arguments.argumentMatchers); // } // // @Override // public int hashCode() { // return argumentMatchers != null ? argumentMatchers.hashCode() : 0; // } // } // // Path: matchers/src/main/java/jinsist/matchers/EqualsMatcher.java // public class EqualsMatcher<T> implements ArgumentMatcher<T> { // private T value; // // public EqualsMatcher(T value) { // this.value = value; // } // // @Override // public boolean matches(T argument) { // boolean isValueNull = value == null; // boolean isArgumentNull = argument == null; // // return isArgumentNull && isValueNull || !isValueNull && value.equals(argument); // } // // @Override // public String toString() { // return "EqualsMatcher " + value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // EqualsMatcher<?> that = (EqualsMatcher<?>) o; // // return value != null ? value.equals(that.value) : that.value == null; // } // // @Override // public int hashCode() { // return value != null ? value.hashCode() : 0; // } // } // // Path: mock/src/main/java/jinsist/mock/SetupResult.java // public class SetupResult { // private boolean wasRecorded = false; // // public void setSuccess() { // this.wasRecorded = true; // } // // void verify() { // if (!wasRecorded) throw new MethodToStubNotFound(); // } // } // // Path: proxy/src/main/java/jinsist/proxy/Delegator.java // public interface Delegator<T> { // Object handle(T instance, Method method, Object[] arguments); // } // Path: mock/src/main/java/jinsist/mock/delegators/SetupRecorder.java import jinsist.expectations.Expectations; import jinsist.matchers.Arguments; import jinsist.matchers.EqualsMatcher; import jinsist.mock.SetupResult; import jinsist.proxy.Delegator; import java.lang.reflect.Method; import java.util.stream.Collectors; import static java.util.Arrays.stream; package jinsist.mock.delegators; public class SetupRecorder<ReturnType, MockType> implements Delegator<MockType> { private MockType instance; private ReturnType result; private SetupResult setupResult;
private Expectations expectations;