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 |
|---|---|---|---|---|---|---|
flownclouds/Timo | src/main/parser/fm/liu/timo/parser/recognizer/mysql/syntax/MySQLDMLSelectParser.java | // Path: src/main/parser/fm/liu/timo/parser/ast/fragment/GroupBy.java
// public class GroupBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
// private boolean withRollup = false;
//
// public boolean isWithRollup() {
// return withRollup;
// }
//
// /**
// * @return never null
// */
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public GroupBy(Expression expr, SortOrder order, boolean withRollup) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// this.withRollup = withRollup;
// }
//
// /**
// * performance tip: linked list is used
// */
// public GroupBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// public GroupBy setWithRollup() {
// withRollup = true;
// return this;
// }
//
// public GroupBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
//
// Path: src/main/parser/fm/liu/timo/parser/ast/fragment/OrderBy.java
// public class OrderBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
//
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: linked list is used
// */
// public OrderBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public OrderBy(Expression expr, SortOrder order) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// }
//
// public OrderBy(List<Pair<Expression, SortOrder>> orderByList) {
// if (orderByList == null)
// throw new IllegalArgumentException("order list is null");
// this.orderByList = orderByList;
// }
//
// public OrderBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
| import static fm.liu.timo.parser.recognizer.mysql.MySQLToken.*;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import fm.liu.timo.parser.ast.expression.Expression;
import fm.liu.timo.parser.ast.fragment.GroupBy;
import fm.liu.timo.parser.ast.fragment.Limit;
import fm.liu.timo.parser.ast.fragment.OrderBy;
import fm.liu.timo.parser.ast.fragment.tableref.Dual;
import fm.liu.timo.parser.ast.fragment.tableref.TableReference;
import fm.liu.timo.parser.ast.fragment.tableref.TableReferences;
import fm.liu.timo.parser.ast.stmt.dml.DMLQueryStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectUnionStatement;
import fm.liu.timo.parser.recognizer.mysql.MySQLToken;
import fm.liu.timo.parser.recognizer.mysql.lexer.MySQLLexer;
import fm.liu.timo.parser.util.Pair; | }
}
private List<Pair<Expression, String>> selectExprList() throws SQLSyntaxErrorException {
Expression expr = exprParser.expression();
String alias = as();
List<Pair<Expression, String>> list;
if (lexer.token() == PUNC_COMMA) {
list = new LinkedList<Pair<Expression, String>>();
list.add(new Pair<Expression, String>(expr, alias));
} else {
list = new ArrayList<Pair<Expression, String>>(1);
list.add(new Pair<Expression, String>(expr, alias));
return list;
}
for (; lexer.token() == PUNC_COMMA; list.add(new Pair<Expression, String>(expr, alias))) {
lexer.nextToken();
expr = exprParser.expression();
alias = as();
}
return list;
}
@Override
public DMLSelectStatement select() throws SQLSyntaxErrorException {
match(KW_SELECT);
DMLSelectStatement.SelectOption option = selectOption();
List<Pair<Expression, String>> exprList = selectExprList();
TableReferences tables = null;
Expression where = null; | // Path: src/main/parser/fm/liu/timo/parser/ast/fragment/GroupBy.java
// public class GroupBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
// private boolean withRollup = false;
//
// public boolean isWithRollup() {
// return withRollup;
// }
//
// /**
// * @return never null
// */
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public GroupBy(Expression expr, SortOrder order, boolean withRollup) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// this.withRollup = withRollup;
// }
//
// /**
// * performance tip: linked list is used
// */
// public GroupBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// public GroupBy setWithRollup() {
// withRollup = true;
// return this;
// }
//
// public GroupBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
//
// Path: src/main/parser/fm/liu/timo/parser/ast/fragment/OrderBy.java
// public class OrderBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
//
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: linked list is used
// */
// public OrderBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public OrderBy(Expression expr, SortOrder order) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// }
//
// public OrderBy(List<Pair<Expression, SortOrder>> orderByList) {
// if (orderByList == null)
// throw new IllegalArgumentException("order list is null");
// this.orderByList = orderByList;
// }
//
// public OrderBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
// Path: src/main/parser/fm/liu/timo/parser/recognizer/mysql/syntax/MySQLDMLSelectParser.java
import static fm.liu.timo.parser.recognizer.mysql.MySQLToken.*;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import fm.liu.timo.parser.ast.expression.Expression;
import fm.liu.timo.parser.ast.fragment.GroupBy;
import fm.liu.timo.parser.ast.fragment.Limit;
import fm.liu.timo.parser.ast.fragment.OrderBy;
import fm.liu.timo.parser.ast.fragment.tableref.Dual;
import fm.liu.timo.parser.ast.fragment.tableref.TableReference;
import fm.liu.timo.parser.ast.fragment.tableref.TableReferences;
import fm.liu.timo.parser.ast.stmt.dml.DMLQueryStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectUnionStatement;
import fm.liu.timo.parser.recognizer.mysql.MySQLToken;
import fm.liu.timo.parser.recognizer.mysql.lexer.MySQLLexer;
import fm.liu.timo.parser.util.Pair;
}
}
private List<Pair<Expression, String>> selectExprList() throws SQLSyntaxErrorException {
Expression expr = exprParser.expression();
String alias = as();
List<Pair<Expression, String>> list;
if (lexer.token() == PUNC_COMMA) {
list = new LinkedList<Pair<Expression, String>>();
list.add(new Pair<Expression, String>(expr, alias));
} else {
list = new ArrayList<Pair<Expression, String>>(1);
list.add(new Pair<Expression, String>(expr, alias));
return list;
}
for (; lexer.token() == PUNC_COMMA; list.add(new Pair<Expression, String>(expr, alias))) {
lexer.nextToken();
expr = exprParser.expression();
alias = as();
}
return list;
}
@Override
public DMLSelectStatement select() throws SQLSyntaxErrorException {
match(KW_SELECT);
DMLSelectStatement.SelectOption option = selectOption();
List<Pair<Expression, String>> exprList = selectExprList();
TableReferences tables = null;
Expression where = null; | GroupBy group = null; |
flownclouds/Timo | src/main/parser/fm/liu/timo/parser/recognizer/mysql/syntax/MySQLDMLSelectParser.java | // Path: src/main/parser/fm/liu/timo/parser/ast/fragment/GroupBy.java
// public class GroupBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
// private boolean withRollup = false;
//
// public boolean isWithRollup() {
// return withRollup;
// }
//
// /**
// * @return never null
// */
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public GroupBy(Expression expr, SortOrder order, boolean withRollup) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// this.withRollup = withRollup;
// }
//
// /**
// * performance tip: linked list is used
// */
// public GroupBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// public GroupBy setWithRollup() {
// withRollup = true;
// return this;
// }
//
// public GroupBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
//
// Path: src/main/parser/fm/liu/timo/parser/ast/fragment/OrderBy.java
// public class OrderBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
//
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: linked list is used
// */
// public OrderBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public OrderBy(Expression expr, SortOrder order) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// }
//
// public OrderBy(List<Pair<Expression, SortOrder>> orderByList) {
// if (orderByList == null)
// throw new IllegalArgumentException("order list is null");
// this.orderByList = orderByList;
// }
//
// public OrderBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
| import static fm.liu.timo.parser.recognizer.mysql.MySQLToken.*;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import fm.liu.timo.parser.ast.expression.Expression;
import fm.liu.timo.parser.ast.fragment.GroupBy;
import fm.liu.timo.parser.ast.fragment.Limit;
import fm.liu.timo.parser.ast.fragment.OrderBy;
import fm.liu.timo.parser.ast.fragment.tableref.Dual;
import fm.liu.timo.parser.ast.fragment.tableref.TableReference;
import fm.liu.timo.parser.ast.fragment.tableref.TableReferences;
import fm.liu.timo.parser.ast.stmt.dml.DMLQueryStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectUnionStatement;
import fm.liu.timo.parser.recognizer.mysql.MySQLToken;
import fm.liu.timo.parser.recognizer.mysql.lexer.MySQLLexer;
import fm.liu.timo.parser.util.Pair; |
private List<Pair<Expression, String>> selectExprList() throws SQLSyntaxErrorException {
Expression expr = exprParser.expression();
String alias = as();
List<Pair<Expression, String>> list;
if (lexer.token() == PUNC_COMMA) {
list = new LinkedList<Pair<Expression, String>>();
list.add(new Pair<Expression, String>(expr, alias));
} else {
list = new ArrayList<Pair<Expression, String>>(1);
list.add(new Pair<Expression, String>(expr, alias));
return list;
}
for (; lexer.token() == PUNC_COMMA; list.add(new Pair<Expression, String>(expr, alias))) {
lexer.nextToken();
expr = exprParser.expression();
alias = as();
}
return list;
}
@Override
public DMLSelectStatement select() throws SQLSyntaxErrorException {
match(KW_SELECT);
DMLSelectStatement.SelectOption option = selectOption();
List<Pair<Expression, String>> exprList = selectExprList();
TableReferences tables = null;
Expression where = null;
GroupBy group = null;
Expression having = null; | // Path: src/main/parser/fm/liu/timo/parser/ast/fragment/GroupBy.java
// public class GroupBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
// private boolean withRollup = false;
//
// public boolean isWithRollup() {
// return withRollup;
// }
//
// /**
// * @return never null
// */
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public GroupBy(Expression expr, SortOrder order, boolean withRollup) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// this.withRollup = withRollup;
// }
//
// /**
// * performance tip: linked list is used
// */
// public GroupBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// public GroupBy setWithRollup() {
// withRollup = true;
// return this;
// }
//
// public GroupBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
//
// Path: src/main/parser/fm/liu/timo/parser/ast/fragment/OrderBy.java
// public class OrderBy implements ASTNode {
// /** might be {@link LinkedList} */
// private final List<Pair<Expression, SortOrder>> orderByList;
//
// public List<Pair<Expression, SortOrder>> getOrderByList() {
// return orderByList;
// }
//
// /**
// * performance tip: linked list is used
// */
// public OrderBy() {
// this.orderByList = new LinkedList<Pair<Expression, SortOrder>>();
// }
//
// /**
// * performance tip: expect to have only 1 order item
// */
// public OrderBy(Expression expr, SortOrder order) {
// this.orderByList = new ArrayList<Pair<Expression, SortOrder>>(1);
// this.orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// }
//
// public OrderBy(List<Pair<Expression, SortOrder>> orderByList) {
// if (orderByList == null)
// throw new IllegalArgumentException("order list is null");
// this.orderByList = orderByList;
// }
//
// public OrderBy addOrderByItem(Expression expr, SortOrder order) {
// orderByList.add(new Pair<Expression, SortOrder>(expr, order));
// return this;
// }
//
// @Override
// public void accept(Visitor visitor) {
// visitor.visit(this);
// }
// }
// Path: src/main/parser/fm/liu/timo/parser/recognizer/mysql/syntax/MySQLDMLSelectParser.java
import static fm.liu.timo.parser.recognizer.mysql.MySQLToken.*;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import fm.liu.timo.parser.ast.expression.Expression;
import fm.liu.timo.parser.ast.fragment.GroupBy;
import fm.liu.timo.parser.ast.fragment.Limit;
import fm.liu.timo.parser.ast.fragment.OrderBy;
import fm.liu.timo.parser.ast.fragment.tableref.Dual;
import fm.liu.timo.parser.ast.fragment.tableref.TableReference;
import fm.liu.timo.parser.ast.fragment.tableref.TableReferences;
import fm.liu.timo.parser.ast.stmt.dml.DMLQueryStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectStatement;
import fm.liu.timo.parser.ast.stmt.dml.DMLSelectUnionStatement;
import fm.liu.timo.parser.recognizer.mysql.MySQLToken;
import fm.liu.timo.parser.recognizer.mysql.lexer.MySQLLexer;
import fm.liu.timo.parser.util.Pair;
private List<Pair<Expression, String>> selectExprList() throws SQLSyntaxErrorException {
Expression expr = exprParser.expression();
String alias = as();
List<Pair<Expression, String>> list;
if (lexer.token() == PUNC_COMMA) {
list = new LinkedList<Pair<Expression, String>>();
list.add(new Pair<Expression, String>(expr, alias));
} else {
list = new ArrayList<Pair<Expression, String>>(1);
list.add(new Pair<Expression, String>(expr, alias));
return list;
}
for (; lexer.token() == PUNC_COMMA; list.add(new Pair<Expression, String>(expr, alias))) {
lexer.nextToken();
expr = exprParser.expression();
alias = as();
}
return list;
}
@Override
public DMLSelectStatement select() throws SQLSyntaxErrorException {
match(KW_SELECT);
DMLSelectStatement.SelectOption option = selectOption();
List<Pair<Expression, String>> exprList = selectExprList();
TableReferences tables = null;
Expression where = null;
GroupBy group = null;
Expression having = null; | OrderBy order = null; |
flownclouds/Timo | src/main/java/fm/liu/timo/manager/handler/HandoverHandler.java | // Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public static final int DATASOURCE = 1;
//
// Path: src/main/java/fm/liu/timo/manager/ManagerConnection.java
// public class ManagerConnection extends FrontendConnection {
// private static final long AUTH_TIMEOUT = 15 * 1000L;
//
// public ManagerConnection(SocketChannel channel, NIOProcessor processor) {
// super(channel, processor);
// }
//
// @Override
// public boolean isIdleTimeout() {
// if (isAuthenticated) {
// return super.isIdleTimeout();
// } else {
// return TimeUtil.currentTimeMillis() > variables.getLastActiveTime() + AUTH_TIMEOUT;
// }
// }
//
// @Override
// public void close(String reason) {
// if (super.closed.compareAndSet(false, true)) {
// processor.remove(this);
// super.cleanup();
// }
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public final class ManagerParseHandover {
//
// public static final int OTHER = -1;
// public static final int DATASOURCE = 1;
//
// public static int parse(String stmt, int offset) {
// int i = offset;
// for (; i < stmt.length(); i++) {
// switch (stmt.charAt(i)) {
// case ' ':
// continue;
// case '/':
// case '#':
// i = ParseUtil.comment(stmt, i);
// continue;
// case '@':
// return switch2Check(stmt, i);
// default:
// return OTHER;
// }
// }
// return OTHER;
// }
//
// public static Pair<String[], Integer> getPair(String stmt) {
// int offset = stmt.indexOf("@@");
// String s = stmt.substring(offset + 12).trim();
// int p1 = s.lastIndexOf(':');
// if (p1 == -1) {
// String[] src = SplitUtil.split(s, ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src, null);
// } else {
// String[] src = SplitUtil.split(s, ':', true);
// String[] src1 = SplitUtil.split(src[0], ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src1, Integer.valueOf(src[1]));
// }
// }
//
// // DATASOURCE
// static int switch2Check(String stmt, int offset) {
// if (stmt.length() > ++offset && stmt.charAt(offset) == '@') {
// if (stmt.length() > offset + 10) {
// char c1 = stmt.charAt(++offset);
// char c2 = stmt.charAt(++offset);
// char c3 = stmt.charAt(++offset);
// char c4 = stmt.charAt(++offset);
// char c5 = stmt.charAt(++offset);
// char c6 = stmt.charAt(++offset);
// char c7 = stmt.charAt(++offset);
// char c8 = stmt.charAt(++offset);
// char c9 = stmt.charAt(++offset);
// char c10 = stmt.charAt(++offset);
// if ((c1 == 'D' || c1 == 'd') && (c2 == 'A' || c2 == 'a') && (c3 == 'T' || c3 == 't')
// && (c4 == 'A' || c4 == 'a') && (c5 == 'S' || c5 == 's')
// && (c6 == 'O' || c6 == 'o') && (c7 == 'U' || c7 == 'u')
// && (c8 == 'R' || c8 == 'r') && (c9 == 'C' || c9 == 'c')
// && (c10 == 'E' || c10 == 'e')) {
// if (stmt.length() > ++offset && stmt.charAt(offset) != ' ') {
// return OTHER;
// }
// return DATASOURCE;
// }
// }
// }
// return OTHER;
// }
//
// }
| import static fm.liu.timo.manager.parser.ManagerParseHandover.DATASOURCE;
import fm.liu.timo.manager.ManagerConnection;
import fm.liu.timo.manager.parser.ManagerParseHandover;
import fm.liu.timo.manager.response.ResponseUtil;
import fm.liu.timo.manager.response.HandoverDatasource; | /*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.manager.handler;
/**
* @author xianmao.hexm
*/
public final class HandoverHandler {
public static void handler(String stmt, ManagerConnection c, int offset) { | // Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public static final int DATASOURCE = 1;
//
// Path: src/main/java/fm/liu/timo/manager/ManagerConnection.java
// public class ManagerConnection extends FrontendConnection {
// private static final long AUTH_TIMEOUT = 15 * 1000L;
//
// public ManagerConnection(SocketChannel channel, NIOProcessor processor) {
// super(channel, processor);
// }
//
// @Override
// public boolean isIdleTimeout() {
// if (isAuthenticated) {
// return super.isIdleTimeout();
// } else {
// return TimeUtil.currentTimeMillis() > variables.getLastActiveTime() + AUTH_TIMEOUT;
// }
// }
//
// @Override
// public void close(String reason) {
// if (super.closed.compareAndSet(false, true)) {
// processor.remove(this);
// super.cleanup();
// }
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public final class ManagerParseHandover {
//
// public static final int OTHER = -1;
// public static final int DATASOURCE = 1;
//
// public static int parse(String stmt, int offset) {
// int i = offset;
// for (; i < stmt.length(); i++) {
// switch (stmt.charAt(i)) {
// case ' ':
// continue;
// case '/':
// case '#':
// i = ParseUtil.comment(stmt, i);
// continue;
// case '@':
// return switch2Check(stmt, i);
// default:
// return OTHER;
// }
// }
// return OTHER;
// }
//
// public static Pair<String[], Integer> getPair(String stmt) {
// int offset = stmt.indexOf("@@");
// String s = stmt.substring(offset + 12).trim();
// int p1 = s.lastIndexOf(':');
// if (p1 == -1) {
// String[] src = SplitUtil.split(s, ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src, null);
// } else {
// String[] src = SplitUtil.split(s, ':', true);
// String[] src1 = SplitUtil.split(src[0], ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src1, Integer.valueOf(src[1]));
// }
// }
//
// // DATASOURCE
// static int switch2Check(String stmt, int offset) {
// if (stmt.length() > ++offset && stmt.charAt(offset) == '@') {
// if (stmt.length() > offset + 10) {
// char c1 = stmt.charAt(++offset);
// char c2 = stmt.charAt(++offset);
// char c3 = stmt.charAt(++offset);
// char c4 = stmt.charAt(++offset);
// char c5 = stmt.charAt(++offset);
// char c6 = stmt.charAt(++offset);
// char c7 = stmt.charAt(++offset);
// char c8 = stmt.charAt(++offset);
// char c9 = stmt.charAt(++offset);
// char c10 = stmt.charAt(++offset);
// if ((c1 == 'D' || c1 == 'd') && (c2 == 'A' || c2 == 'a') && (c3 == 'T' || c3 == 't')
// && (c4 == 'A' || c4 == 'a') && (c5 == 'S' || c5 == 's')
// && (c6 == 'O' || c6 == 'o') && (c7 == 'U' || c7 == 'u')
// && (c8 == 'R' || c8 == 'r') && (c9 == 'C' || c9 == 'c')
// && (c10 == 'E' || c10 == 'e')) {
// if (stmt.length() > ++offset && stmt.charAt(offset) != ' ') {
// return OTHER;
// }
// return DATASOURCE;
// }
// }
// }
// return OTHER;
// }
//
// }
// Path: src/main/java/fm/liu/timo/manager/handler/HandoverHandler.java
import static fm.liu.timo.manager.parser.ManagerParseHandover.DATASOURCE;
import fm.liu.timo.manager.ManagerConnection;
import fm.liu.timo.manager.parser.ManagerParseHandover;
import fm.liu.timo.manager.response.ResponseUtil;
import fm.liu.timo.manager.response.HandoverDatasource;
/*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.manager.handler;
/**
* @author xianmao.hexm
*/
public final class HandoverHandler {
public static void handler(String stmt, ManagerConnection c, int offset) { | switch (ManagerParseHandover.parse(stmt, offset)) { |
flownclouds/Timo | src/main/java/fm/liu/timo/manager/handler/HandoverHandler.java | // Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public static final int DATASOURCE = 1;
//
// Path: src/main/java/fm/liu/timo/manager/ManagerConnection.java
// public class ManagerConnection extends FrontendConnection {
// private static final long AUTH_TIMEOUT = 15 * 1000L;
//
// public ManagerConnection(SocketChannel channel, NIOProcessor processor) {
// super(channel, processor);
// }
//
// @Override
// public boolean isIdleTimeout() {
// if (isAuthenticated) {
// return super.isIdleTimeout();
// } else {
// return TimeUtil.currentTimeMillis() > variables.getLastActiveTime() + AUTH_TIMEOUT;
// }
// }
//
// @Override
// public void close(String reason) {
// if (super.closed.compareAndSet(false, true)) {
// processor.remove(this);
// super.cleanup();
// }
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public final class ManagerParseHandover {
//
// public static final int OTHER = -1;
// public static final int DATASOURCE = 1;
//
// public static int parse(String stmt, int offset) {
// int i = offset;
// for (; i < stmt.length(); i++) {
// switch (stmt.charAt(i)) {
// case ' ':
// continue;
// case '/':
// case '#':
// i = ParseUtil.comment(stmt, i);
// continue;
// case '@':
// return switch2Check(stmt, i);
// default:
// return OTHER;
// }
// }
// return OTHER;
// }
//
// public static Pair<String[], Integer> getPair(String stmt) {
// int offset = stmt.indexOf("@@");
// String s = stmt.substring(offset + 12).trim();
// int p1 = s.lastIndexOf(':');
// if (p1 == -1) {
// String[] src = SplitUtil.split(s, ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src, null);
// } else {
// String[] src = SplitUtil.split(s, ':', true);
// String[] src1 = SplitUtil.split(src[0], ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src1, Integer.valueOf(src[1]));
// }
// }
//
// // DATASOURCE
// static int switch2Check(String stmt, int offset) {
// if (stmt.length() > ++offset && stmt.charAt(offset) == '@') {
// if (stmt.length() > offset + 10) {
// char c1 = stmt.charAt(++offset);
// char c2 = stmt.charAt(++offset);
// char c3 = stmt.charAt(++offset);
// char c4 = stmt.charAt(++offset);
// char c5 = stmt.charAt(++offset);
// char c6 = stmt.charAt(++offset);
// char c7 = stmt.charAt(++offset);
// char c8 = stmt.charAt(++offset);
// char c9 = stmt.charAt(++offset);
// char c10 = stmt.charAt(++offset);
// if ((c1 == 'D' || c1 == 'd') && (c2 == 'A' || c2 == 'a') && (c3 == 'T' || c3 == 't')
// && (c4 == 'A' || c4 == 'a') && (c5 == 'S' || c5 == 's')
// && (c6 == 'O' || c6 == 'o') && (c7 == 'U' || c7 == 'u')
// && (c8 == 'R' || c8 == 'r') && (c9 == 'C' || c9 == 'c')
// && (c10 == 'E' || c10 == 'e')) {
// if (stmt.length() > ++offset && stmt.charAt(offset) != ' ') {
// return OTHER;
// }
// return DATASOURCE;
// }
// }
// }
// return OTHER;
// }
//
// }
| import static fm.liu.timo.manager.parser.ManagerParseHandover.DATASOURCE;
import fm.liu.timo.manager.ManagerConnection;
import fm.liu.timo.manager.parser.ManagerParseHandover;
import fm.liu.timo.manager.response.ResponseUtil;
import fm.liu.timo.manager.response.HandoverDatasource; | /*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.manager.handler;
/**
* @author xianmao.hexm
*/
public final class HandoverHandler {
public static void handler(String stmt, ManagerConnection c, int offset) {
switch (ManagerParseHandover.parse(stmt, offset)) { | // Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public static final int DATASOURCE = 1;
//
// Path: src/main/java/fm/liu/timo/manager/ManagerConnection.java
// public class ManagerConnection extends FrontendConnection {
// private static final long AUTH_TIMEOUT = 15 * 1000L;
//
// public ManagerConnection(SocketChannel channel, NIOProcessor processor) {
// super(channel, processor);
// }
//
// @Override
// public boolean isIdleTimeout() {
// if (isAuthenticated) {
// return super.isIdleTimeout();
// } else {
// return TimeUtil.currentTimeMillis() > variables.getLastActiveTime() + AUTH_TIMEOUT;
// }
// }
//
// @Override
// public void close(String reason) {
// if (super.closed.compareAndSet(false, true)) {
// processor.remove(this);
// super.cleanup();
// }
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/manager/parser/ManagerParseHandover.java
// public final class ManagerParseHandover {
//
// public static final int OTHER = -1;
// public static final int DATASOURCE = 1;
//
// public static int parse(String stmt, int offset) {
// int i = offset;
// for (; i < stmt.length(); i++) {
// switch (stmt.charAt(i)) {
// case ' ':
// continue;
// case '/':
// case '#':
// i = ParseUtil.comment(stmt, i);
// continue;
// case '@':
// return switch2Check(stmt, i);
// default:
// return OTHER;
// }
// }
// return OTHER;
// }
//
// public static Pair<String[], Integer> getPair(String stmt) {
// int offset = stmt.indexOf("@@");
// String s = stmt.substring(offset + 12).trim();
// int p1 = s.lastIndexOf(':');
// if (p1 == -1) {
// String[] src = SplitUtil.split(s, ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src, null);
// } else {
// String[] src = SplitUtil.split(s, ':', true);
// String[] src1 = SplitUtil.split(src[0], ',', '$', '-', '[', ']');
// return new Pair<String[], Integer>(src1, Integer.valueOf(src[1]));
// }
// }
//
// // DATASOURCE
// static int switch2Check(String stmt, int offset) {
// if (stmt.length() > ++offset && stmt.charAt(offset) == '@') {
// if (stmt.length() > offset + 10) {
// char c1 = stmt.charAt(++offset);
// char c2 = stmt.charAt(++offset);
// char c3 = stmt.charAt(++offset);
// char c4 = stmt.charAt(++offset);
// char c5 = stmt.charAt(++offset);
// char c6 = stmt.charAt(++offset);
// char c7 = stmt.charAt(++offset);
// char c8 = stmt.charAt(++offset);
// char c9 = stmt.charAt(++offset);
// char c10 = stmt.charAt(++offset);
// if ((c1 == 'D' || c1 == 'd') && (c2 == 'A' || c2 == 'a') && (c3 == 'T' || c3 == 't')
// && (c4 == 'A' || c4 == 'a') && (c5 == 'S' || c5 == 's')
// && (c6 == 'O' || c6 == 'o') && (c7 == 'U' || c7 == 'u')
// && (c8 == 'R' || c8 == 'r') && (c9 == 'C' || c9 == 'c')
// && (c10 == 'E' || c10 == 'e')) {
// if (stmt.length() > ++offset && stmt.charAt(offset) != ' ') {
// return OTHER;
// }
// return DATASOURCE;
// }
// }
// }
// return OTHER;
// }
//
// }
// Path: src/main/java/fm/liu/timo/manager/handler/HandoverHandler.java
import static fm.liu.timo.manager.parser.ManagerParseHandover.DATASOURCE;
import fm.liu.timo.manager.ManagerConnection;
import fm.liu.timo.manager.parser.ManagerParseHandover;
import fm.liu.timo.manager.response.ResponseUtil;
import fm.liu.timo.manager.response.HandoverDatasource;
/*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.manager.handler;
/**
* @author xianmao.hexm
*/
public final class HandoverHandler {
public static void handler(String stmt, ManagerConnection c, int offset) {
switch (ManagerParseHandover.parse(stmt, offset)) { | case DATASOURCE: |
flownclouds/Timo | src/main/java/fm/liu/timo/manager/ManagerQueryHandler.java | // Path: src/main/java/fm/liu/timo/manager/handler/HandoverHandler.java
// public final class HandoverHandler {
//
// public static void handler(String stmt, ManagerConnection c, int offset) {
// switch (ManagerParseHandover.parse(stmt, offset)) {
// case DATASOURCE:
// HandoverDatasource.response(stmt, c);
// break;
// default:
// ResponseUtil.error(c);
// }
// }
//
// }
| import org.pmw.tinylog.Logger;
import fm.liu.timo.manager.handler.DescHandler;
import fm.liu.timo.manager.handler.ReloadHandler;
import fm.liu.timo.manager.handler.RollbackHandler;
import fm.liu.timo.manager.handler.SelectHandler;
import fm.liu.timo.manager.handler.ShowHandler;
import fm.liu.timo.manager.handler.StopHandler;
import fm.liu.timo.manager.handler.HandoverHandler;
import fm.liu.timo.manager.parser.ManagerParse;
import fm.liu.timo.manager.response.KillConnection;
import fm.liu.timo.manager.response.Offline;
import fm.liu.timo.manager.response.Online;
import fm.liu.timo.manager.response.ResponseUtil;
import fm.liu.timo.mysql.packet.OkPacket;
import fm.liu.timo.net.handler.FrontendQueryHandler; | /*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.manager;
/**
* @author xianmao.hexm
*/
public class ManagerQueryHandler implements FrontendQueryHandler {
private final ManagerConnection source;
public ManagerQueryHandler(ManagerConnection source) {
this.source = source;
}
@Override
public void query(String sql) {
ManagerConnection c = this.source;
if (Logger.isDebugEnabled()) {
Logger.debug("SQL:'{}' from {}", sql, c);
}
int rs = ManagerParse.parse(sql);
switch (rs & 0xff) {
case ManagerParse.DESC:
DescHandler.handle(sql, c, rs);
break;
case ManagerParse.SELECT:
SelectHandler.handle(sql, c, rs >>> 8);
break;
case ManagerParse.SET:
c.write(c.writeToBuffer(OkPacket.OK, c.allocate()));
break;
case ManagerParse.SHOW:
ShowHandler.handle(sql, c, rs >>> 8);
break;
case ManagerParse.HANDOVER: | // Path: src/main/java/fm/liu/timo/manager/handler/HandoverHandler.java
// public final class HandoverHandler {
//
// public static void handler(String stmt, ManagerConnection c, int offset) {
// switch (ManagerParseHandover.parse(stmt, offset)) {
// case DATASOURCE:
// HandoverDatasource.response(stmt, c);
// break;
// default:
// ResponseUtil.error(c);
// }
// }
//
// }
// Path: src/main/java/fm/liu/timo/manager/ManagerQueryHandler.java
import org.pmw.tinylog.Logger;
import fm.liu.timo.manager.handler.DescHandler;
import fm.liu.timo.manager.handler.ReloadHandler;
import fm.liu.timo.manager.handler.RollbackHandler;
import fm.liu.timo.manager.handler.SelectHandler;
import fm.liu.timo.manager.handler.ShowHandler;
import fm.liu.timo.manager.handler.StopHandler;
import fm.liu.timo.manager.handler.HandoverHandler;
import fm.liu.timo.manager.parser.ManagerParse;
import fm.liu.timo.manager.response.KillConnection;
import fm.liu.timo.manager.response.Offline;
import fm.liu.timo.manager.response.Online;
import fm.liu.timo.manager.response.ResponseUtil;
import fm.liu.timo.mysql.packet.OkPacket;
import fm.liu.timo.net.handler.FrontendQueryHandler;
/*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.manager;
/**
* @author xianmao.hexm
*/
public class ManagerQueryHandler implements FrontendQueryHandler {
private final ManagerConnection source;
public ManagerQueryHandler(ManagerConnection source) {
this.source = source;
}
@Override
public void query(String sql) {
ManagerConnection c = this.source;
if (Logger.isDebugEnabled()) {
Logger.debug("SQL:'{}' from {}", sql, c);
}
int rs = ManagerParse.parse(sql);
switch (rs & 0xff) {
case ManagerParse.DESC:
DescHandler.handle(sql, c, rs);
break;
case ManagerParse.SELECT:
SelectHandler.handle(sql, c, rs >>> 8);
break;
case ManagerParse.SET:
c.write(c.writeToBuffer(OkPacket.OK, c.allocate()));
break;
case ManagerParse.SHOW:
ShowHandler.handle(sql, c, rs >>> 8);
break;
case ManagerParse.HANDOVER: | HandoverHandler.handler(sql, c, rs >>> 8); |
flownclouds/Timo | src/main/java/fm/liu/timo/server/handler/SelectHandler.java | // Path: src/main/java/fm/liu/timo/server/response/SelectIdentity.java
// public class SelectIdentity {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
//
// static {
// byte packetId = 0;
// header.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c, String stmt, int aliasIndex,
// final String orgName) {
// String alias = ParseUtil.parseAlias(stmt, aliasIndex);
// if (alias == null) {
// alias = orgName;
// }
//
// ByteBuffer buffer = c.allocate();
//
// // write header
// buffer = header.write(buffer, c);
//
// // write fields
// byte packetId = header.packetId;
// FieldPacket field = PacketUtil.getField(alias, orgName, Fields.FIELD_TYPE_LONGLONG);
// field.packetId = ++packetId;
// buffer = field.write(buffer, c);
//
// // write eof
// EOFPacket eof = new EOFPacket();
// eof.packetId = ++packetId;
// buffer = eof.write(buffer, c);
//
// // write rows
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(LongUtil.toBytes(c.getLastInsertId()));
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
//
// // write last eof
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
//
// // post write
// c.write(buffer);
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/server/response/SelectVersion.java
// public class SelectVersion {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
// private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
// private static final EOFPacket eof = new EOFPacket();
//
// static {
// int i = 0;
// byte packetId = 0;
// header.packetId = ++packetId;
// fields[i] = PacketUtil.getField("VERSION()", Fields.FIELD_TYPE_VAR_STRING);
// fields[i++].packetId = ++packetId;
// eof.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c) {
// ByteBuffer buffer = c.allocate();
// buffer = header.write(buffer, c);
// for (FieldPacket field : fields) {
// buffer = field.write(buffer, c);
// }
// buffer = eof.write(buffer, c);
// byte packetId = eof.packetId;
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(Versions.SERVER_VERSION);
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
// c.write(buffer);
// }
//
// }
| import fm.liu.timo.parser.util.ParseUtil;
import fm.liu.timo.server.ServerConnection;
import fm.liu.timo.server.parser.ServerParse;
import fm.liu.timo.server.parser.ServerParseSelect;
import fm.liu.timo.server.response.SelectDatabase;
import fm.liu.timo.server.response.SelectIdentity;
import fm.liu.timo.server.response.SelectLastInsertId;
import fm.liu.timo.server.response.SelectUser;
import fm.liu.timo.server.response.SelectVersion;
import fm.liu.timo.server.response.SelectVersionComment; | /*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.server.handler;
/**
* @author xianmao.hexm
*/
public final class SelectHandler {
public static void handle(String stmt, ServerConnection c, int offs) {
int offset = offs;
switch (ServerParseSelect.parse(stmt, offs)) {
case ServerParseSelect.VERSION_COMMENT:
SelectVersionComment.response(c);
break;
case ServerParseSelect.DATABASE:
SelectDatabase.response(c);
break;
case ServerParseSelect.USER:
SelectUser.response(c);
break;
case ServerParseSelect.VERSION: | // Path: src/main/java/fm/liu/timo/server/response/SelectIdentity.java
// public class SelectIdentity {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
//
// static {
// byte packetId = 0;
// header.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c, String stmt, int aliasIndex,
// final String orgName) {
// String alias = ParseUtil.parseAlias(stmt, aliasIndex);
// if (alias == null) {
// alias = orgName;
// }
//
// ByteBuffer buffer = c.allocate();
//
// // write header
// buffer = header.write(buffer, c);
//
// // write fields
// byte packetId = header.packetId;
// FieldPacket field = PacketUtil.getField(alias, orgName, Fields.FIELD_TYPE_LONGLONG);
// field.packetId = ++packetId;
// buffer = field.write(buffer, c);
//
// // write eof
// EOFPacket eof = new EOFPacket();
// eof.packetId = ++packetId;
// buffer = eof.write(buffer, c);
//
// // write rows
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(LongUtil.toBytes(c.getLastInsertId()));
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
//
// // write last eof
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
//
// // post write
// c.write(buffer);
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/server/response/SelectVersion.java
// public class SelectVersion {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
// private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
// private static final EOFPacket eof = new EOFPacket();
//
// static {
// int i = 0;
// byte packetId = 0;
// header.packetId = ++packetId;
// fields[i] = PacketUtil.getField("VERSION()", Fields.FIELD_TYPE_VAR_STRING);
// fields[i++].packetId = ++packetId;
// eof.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c) {
// ByteBuffer buffer = c.allocate();
// buffer = header.write(buffer, c);
// for (FieldPacket field : fields) {
// buffer = field.write(buffer, c);
// }
// buffer = eof.write(buffer, c);
// byte packetId = eof.packetId;
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(Versions.SERVER_VERSION);
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
// c.write(buffer);
// }
//
// }
// Path: src/main/java/fm/liu/timo/server/handler/SelectHandler.java
import fm.liu.timo.parser.util.ParseUtil;
import fm.liu.timo.server.ServerConnection;
import fm.liu.timo.server.parser.ServerParse;
import fm.liu.timo.server.parser.ServerParseSelect;
import fm.liu.timo.server.response.SelectDatabase;
import fm.liu.timo.server.response.SelectIdentity;
import fm.liu.timo.server.response.SelectLastInsertId;
import fm.liu.timo.server.response.SelectUser;
import fm.liu.timo.server.response.SelectVersion;
import fm.liu.timo.server.response.SelectVersionComment;
/*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package fm.liu.timo.server.handler;
/**
* @author xianmao.hexm
*/
public final class SelectHandler {
public static void handle(String stmt, ServerConnection c, int offs) {
int offset = offs;
switch (ServerParseSelect.parse(stmt, offs)) {
case ServerParseSelect.VERSION_COMMENT:
SelectVersionComment.response(c);
break;
case ServerParseSelect.DATABASE:
SelectDatabase.response(c);
break;
case ServerParseSelect.USER:
SelectUser.response(c);
break;
case ServerParseSelect.VERSION: | SelectVersion.response(c); |
flownclouds/Timo | src/main/java/fm/liu/timo/server/handler/SelectHandler.java | // Path: src/main/java/fm/liu/timo/server/response/SelectIdentity.java
// public class SelectIdentity {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
//
// static {
// byte packetId = 0;
// header.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c, String stmt, int aliasIndex,
// final String orgName) {
// String alias = ParseUtil.parseAlias(stmt, aliasIndex);
// if (alias == null) {
// alias = orgName;
// }
//
// ByteBuffer buffer = c.allocate();
//
// // write header
// buffer = header.write(buffer, c);
//
// // write fields
// byte packetId = header.packetId;
// FieldPacket field = PacketUtil.getField(alias, orgName, Fields.FIELD_TYPE_LONGLONG);
// field.packetId = ++packetId;
// buffer = field.write(buffer, c);
//
// // write eof
// EOFPacket eof = new EOFPacket();
// eof.packetId = ++packetId;
// buffer = eof.write(buffer, c);
//
// // write rows
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(LongUtil.toBytes(c.getLastInsertId()));
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
//
// // write last eof
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
//
// // post write
// c.write(buffer);
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/server/response/SelectVersion.java
// public class SelectVersion {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
// private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
// private static final EOFPacket eof = new EOFPacket();
//
// static {
// int i = 0;
// byte packetId = 0;
// header.packetId = ++packetId;
// fields[i] = PacketUtil.getField("VERSION()", Fields.FIELD_TYPE_VAR_STRING);
// fields[i++].packetId = ++packetId;
// eof.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c) {
// ByteBuffer buffer = c.allocate();
// buffer = header.write(buffer, c);
// for (FieldPacket field : fields) {
// buffer = field.write(buffer, c);
// }
// buffer = eof.write(buffer, c);
// byte packetId = eof.packetId;
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(Versions.SERVER_VERSION);
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
// c.write(buffer);
// }
//
// }
| import fm.liu.timo.parser.util.ParseUtil;
import fm.liu.timo.server.ServerConnection;
import fm.liu.timo.server.parser.ServerParse;
import fm.liu.timo.server.parser.ServerParseSelect;
import fm.liu.timo.server.response.SelectDatabase;
import fm.liu.timo.server.response.SelectIdentity;
import fm.liu.timo.server.response.SelectLastInsertId;
import fm.liu.timo.server.response.SelectUser;
import fm.liu.timo.server.response.SelectVersion;
import fm.liu.timo.server.response.SelectVersionComment; | offset = ParseUtil.comment(stmt, offset);
continue;
case 'L':
case 'l':
break loop;
}
}
offset = ServerParseSelect.indexAfterLastInsertIdFunc(stmt, offset);
offset = ServerParseSelect.skipAs(stmt, offset);
SelectLastInsertId.response(c, stmt, offset);
break;
case ServerParseSelect.IDENTITY:
// offset = ParseUtil.move(stmt, 0, "select".length());
loop: for (; offset < stmt.length(); ++offset) {
switch (stmt.charAt(offset)) {
case ' ':
continue;
case '/':
case '#':
offset = ParseUtil.comment(stmt, offset);
continue;
case '@':
break loop;
}
}
int indexOfAtAt = offset;
offset += 2;
offset = ServerParseSelect.indexAfterIdentity(stmt, offset);
String orgName = stmt.substring(indexOfAtAt, offset);
offset = ServerParseSelect.skipAs(stmt, offset); | // Path: src/main/java/fm/liu/timo/server/response/SelectIdentity.java
// public class SelectIdentity {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
//
// static {
// byte packetId = 0;
// header.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c, String stmt, int aliasIndex,
// final String orgName) {
// String alias = ParseUtil.parseAlias(stmt, aliasIndex);
// if (alias == null) {
// alias = orgName;
// }
//
// ByteBuffer buffer = c.allocate();
//
// // write header
// buffer = header.write(buffer, c);
//
// // write fields
// byte packetId = header.packetId;
// FieldPacket field = PacketUtil.getField(alias, orgName, Fields.FIELD_TYPE_LONGLONG);
// field.packetId = ++packetId;
// buffer = field.write(buffer, c);
//
// // write eof
// EOFPacket eof = new EOFPacket();
// eof.packetId = ++packetId;
// buffer = eof.write(buffer, c);
//
// // write rows
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(LongUtil.toBytes(c.getLastInsertId()));
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
//
// // write last eof
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
//
// // post write
// c.write(buffer);
// }
//
// }
//
// Path: src/main/java/fm/liu/timo/server/response/SelectVersion.java
// public class SelectVersion {
//
// private static final int FIELD_COUNT = 1;
// private static final ResultSetHeaderPacket header = PacketUtil.getHeader(FIELD_COUNT);
// private static final FieldPacket[] fields = new FieldPacket[FIELD_COUNT];
// private static final EOFPacket eof = new EOFPacket();
//
// static {
// int i = 0;
// byte packetId = 0;
// header.packetId = ++packetId;
// fields[i] = PacketUtil.getField("VERSION()", Fields.FIELD_TYPE_VAR_STRING);
// fields[i++].packetId = ++packetId;
// eof.packetId = ++packetId;
// }
//
// public static void response(ServerConnection c) {
// ByteBuffer buffer = c.allocate();
// buffer = header.write(buffer, c);
// for (FieldPacket field : fields) {
// buffer = field.write(buffer, c);
// }
// buffer = eof.write(buffer, c);
// byte packetId = eof.packetId;
// RowDataPacket row = new RowDataPacket(FIELD_COUNT);
// row.add(Versions.SERVER_VERSION);
// row.packetId = ++packetId;
// buffer = row.write(buffer, c);
// EOFPacket lastEof = new EOFPacket();
// lastEof.packetId = ++packetId;
// buffer = lastEof.write(buffer, c);
// c.write(buffer);
// }
//
// }
// Path: src/main/java/fm/liu/timo/server/handler/SelectHandler.java
import fm.liu.timo.parser.util.ParseUtil;
import fm.liu.timo.server.ServerConnection;
import fm.liu.timo.server.parser.ServerParse;
import fm.liu.timo.server.parser.ServerParseSelect;
import fm.liu.timo.server.response.SelectDatabase;
import fm.liu.timo.server.response.SelectIdentity;
import fm.liu.timo.server.response.SelectLastInsertId;
import fm.liu.timo.server.response.SelectUser;
import fm.liu.timo.server.response.SelectVersion;
import fm.liu.timo.server.response.SelectVersionComment;
offset = ParseUtil.comment(stmt, offset);
continue;
case 'L':
case 'l':
break loop;
}
}
offset = ServerParseSelect.indexAfterLastInsertIdFunc(stmt, offset);
offset = ServerParseSelect.skipAs(stmt, offset);
SelectLastInsertId.response(c, stmt, offset);
break;
case ServerParseSelect.IDENTITY:
// offset = ParseUtil.move(stmt, 0, "select".length());
loop: for (; offset < stmt.length(); ++offset) {
switch (stmt.charAt(offset)) {
case ' ':
continue;
case '/':
case '#':
offset = ParseUtil.comment(stmt, offset);
continue;
case '@':
break loop;
}
}
int indexOfAtAt = offset;
offset += 2;
offset = ServerParseSelect.indexAfterIdentity(stmt, offset);
String orgName = stmt.substring(indexOfAtAt, offset);
offset = ServerParseSelect.skipAs(stmt, offset); | SelectIdentity.response(c, stmt, offset, orgName); |
jporras66/cryptocard | cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/Ibm3624Offset.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/DesKeyType.java
// public enum DesKeyType {
//
// SIMPLE(0), DOUBLE(1), TRIPLE(2) ;
// @SuppressWarnings("unused")
// private int value;
//
// private DesKeyType (int value) {
// this.value = value;
// }
// }
| import com.indarsoft.cryptocard.symmetrickey.Pvk;
import com.indarsoft.cryptocard.types.DesKeyType;
import com.indarsoft.utl.Ascii;
import com.indarsoft.utl.Binary;
import com.indarsoft.utl.Des;
| package com.indarsoft.cryptocard.customerverify;
/**
* Performs IBM3624 offset calculations.
*
* @author fjavier.porras@gmail.com
*
*/
public class Ibm3624Offset {
private static final int BLK16 = 16 ; // (16 * 8 = 128 bits )
private static final int BLK08 = 8 ; // (8 * 8 = 64 bits )
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/DesKeyType.java
// public enum DesKeyType {
//
// SIMPLE(0), DOUBLE(1), TRIPLE(2) ;
// @SuppressWarnings("unused")
// private int value;
//
// private DesKeyType (int value) {
// this.value = value;
// }
// }
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/Ibm3624Offset.java
import com.indarsoft.cryptocard.symmetrickey.Pvk;
import com.indarsoft.cryptocard.types.DesKeyType;
import com.indarsoft.utl.Ascii;
import com.indarsoft.utl.Binary;
import com.indarsoft.utl.Des;
package com.indarsoft.cryptocard.customerverify;
/**
* Performs IBM3624 offset calculations.
*
* @author fjavier.porras@gmail.com
*
*/
public class Ibm3624Offset {
private static final int BLK16 = 16 ; // (16 * 8 = 128 bits )
private static final int BLK08 = 8 ; // (8 * 8 = 64 bits )
| private Pvk pvk ;
|
jporras66/cryptocard | cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/Ibm3624Offset.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/DesKeyType.java
// public enum DesKeyType {
//
// SIMPLE(0), DOUBLE(1), TRIPLE(2) ;
// @SuppressWarnings("unused")
// private int value;
//
// private DesKeyType (int value) {
// this.value = value;
// }
// }
| import com.indarsoft.cryptocard.symmetrickey.Pvk;
import com.indarsoft.cryptocard.types.DesKeyType;
import com.indarsoft.utl.Ascii;
import com.indarsoft.utl.Binary;
import com.indarsoft.utl.Des;
| * Natural Pin calculation.
* <pre>
* - Validate Pin Validation Data
* - DES or Tdes of Pin Validation data (depending of Pvk length)
* - Take N-bytes (N=pin length/2) and decimalize this data
* - Natural Pin --{@literal>} Return previous result as string
* </pre>
* @param pinValidationData input pin validation data
* @param pinLength pin length
* @return natural pin generated
* @throws Exception if a exception arrives
*/
public String calculateNaturalPin ( String pinValidationData , int pinLength ) throws Exception {
byte[] blkA = new byte[BLK16];
byte[] blkB ;
//
for (int i=0; i < pinValidationData.length() ; i++){
blkA[i] = (byte) Character.getNumericValue( pinValidationData.charAt(i) ) ;
}
isvalidPinValidationData(pinValidationData);
/*
* Compress the builded block to 64 bits
*/
blkB = Binary.compressBlock( blkA ) ;
/* Encrypt the blkB */
byte [] blkEncrypted = new byte[ BLK08 ];
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/DesKeyType.java
// public enum DesKeyType {
//
// SIMPLE(0), DOUBLE(1), TRIPLE(2) ;
// @SuppressWarnings("unused")
// private int value;
//
// private DesKeyType (int value) {
// this.value = value;
// }
// }
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/Ibm3624Offset.java
import com.indarsoft.cryptocard.symmetrickey.Pvk;
import com.indarsoft.cryptocard.types.DesKeyType;
import com.indarsoft.utl.Ascii;
import com.indarsoft.utl.Binary;
import com.indarsoft.utl.Des;
* Natural Pin calculation.
* <pre>
* - Validate Pin Validation Data
* - DES or Tdes of Pin Validation data (depending of Pvk length)
* - Take N-bytes (N=pin length/2) and decimalize this data
* - Natural Pin --{@literal>} Return previous result as string
* </pre>
* @param pinValidationData input pin validation data
* @param pinLength pin length
* @return natural pin generated
* @throws Exception if a exception arrives
*/
public String calculateNaturalPin ( String pinValidationData , int pinLength ) throws Exception {
byte[] blkA = new byte[BLK16];
byte[] blkB ;
//
for (int i=0; i < pinValidationData.length() ; i++){
blkA[i] = (byte) Character.getNumericValue( pinValidationData.charAt(i) ) ;
}
isvalidPinValidationData(pinValidationData);
/*
* Compress the builded block to 64 bits
*/
blkB = Binary.compressBlock( blkA ) ;
/* Encrypt the blkB */
byte [] blkEncrypted = new byte[ BLK08 ];
| if ( pvk.getKeyType() == DesKeyType.SIMPLE ){
|
jporras66/cryptocard | cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKey.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/DesKeyType.java
// public enum DesKeyType {
//
// SIMPLE(0), DOUBLE(1), TRIPLE(2) ;
// @SuppressWarnings("unused")
// private int value;
//
// private DesKeyType (int value) {
// this.value = value;
// }
// }
| import com.indarsoft.cryptocard.types.DesKeyType;
import com.indarsoft.utl.Ascii;
import com.indarsoft.utl.Binary;
import com.indarsoft.utl.Des;
| package com.indarsoft.cryptocard.symmetrickey;
/**
* Deskey
*
* @author fjavier.porras@gmail.com
*
*/
public class DesKey {
private static final int SIMPLE = 8 ;
private static final int DOUBLE = 16 ;
private static final int TRIPLE = 24 ;
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/DesKeyType.java
// public enum DesKeyType {
//
// SIMPLE(0), DOUBLE(1), TRIPLE(2) ;
// @SuppressWarnings("unused")
// private int value;
//
// private DesKeyType (int value) {
// this.value = value;
// }
// }
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKey.java
import com.indarsoft.cryptocard.types.DesKeyType;
import com.indarsoft.utl.Ascii;
import com.indarsoft.utl.Binary;
import com.indarsoft.utl.Des;
package com.indarsoft.cryptocard.symmetrickey;
/**
* Deskey
*
* @author fjavier.porras@gmail.com
*
*/
public class DesKey {
private static final int SIMPLE = 8 ;
private static final int DOUBLE = 16 ;
private static final int TRIPLE = 24 ;
| private DesKeyType keyType ;
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkVisaTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
| package com.indarsoft.cryptocard.symmetrickey;
public class ZpkVisaTest {
public String doubleKeyStr = "0170F175468FB5E60213233243526273" ;
public String doubleKeyCheckValue = "58D4C6";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkDouble() {
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkVisaTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
package com.indarsoft.cryptocard.symmetrickey;
public class ZpkVisaTest {
public String doubleKeyStr = "0170F175468FB5E60213233243526273" ;
public String doubleKeyCheckValue = "58D4C6";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkDouble() {
| Zpk a = null ;
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkVisaTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
| package com.indarsoft.cryptocard.symmetrickey;
public class ZpkVisaTest {
public String doubleKeyStr = "0170F175468FB5E60213233243526273" ;
public String doubleKeyCheckValue = "58D4C6";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkDouble() {
Zpk a = null ;
try{
a = new Zpk(doubleKeyStr) ;
}
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkVisaTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
package com.indarsoft.cryptocard.symmetrickey;
public class ZpkVisaTest {
public String doubleKeyStr = "0170F175468FB5E60213233243526273" ;
public String doubleKeyCheckValue = "58D4C6";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkDouble() {
Zpk a = null ;
try{
a = new Zpk(doubleKeyStr) ;
}
| catch ( DesKeyException e ){
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/PvkTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Pvk;
| package com.indarsoft.cryptocard.symmetrickey;
public class PvkTest {
public String simpleKeyStr = "0123456789ABCDEF" ;
public String doubleKeyStr = "F1FD8AC2EFCE3BC8F1FD8AC2EFCE3BC8" ;
public String simpleKeyCheckValue = "D5D44F";
public String doubleKeyCheckValue = "13F5CC";
@Test
public void testPvkCheckValueDouble() {
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/PvkTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Pvk;
package com.indarsoft.cryptocard.symmetrickey;
public class PvkTest {
public String simpleKeyStr = "0123456789ABCDEF" ;
public String doubleKeyStr = "F1FD8AC2EFCE3BC8F1FD8AC2EFCE3BC8" ;
public String simpleKeyCheckValue = "D5D44F";
public String doubleKeyCheckValue = "13F5CC";
@Test
public void testPvkCheckValueDouble() {
| Pvk a = null ;
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/PvkTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Pvk;
| package com.indarsoft.cryptocard.symmetrickey;
public class PvkTest {
public String simpleKeyStr = "0123456789ABCDEF" ;
public String doubleKeyStr = "F1FD8AC2EFCE3BC8F1FD8AC2EFCE3BC8" ;
public String simpleKeyCheckValue = "D5D44F";
public String doubleKeyCheckValue = "13F5CC";
@Test
public void testPvkCheckValueDouble() {
Pvk a = null ;
try{
a = new Pvk(doubleKeyStr, 1 ) ;
}
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Pvk.java
// public class Pvk extends DesKey {
//
// private int pvki ;
// /**
// * PVK constructor
// * @param aKey DES key double length.
// * @param pvki pvki
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey , int pvki ) throws DesKeyException {
//
// super(aKey );
// if ( ! validatePvki ( pvki ) ) throw new DesKeyException("Wrong Key - pvki must be Decimal between 1 and six !!") ;
// /*
// * Do not enforce this, because PVK is also used for IBM3264offset method
// */
// //if ( aKey.length() != 32 ) throw new DesKeyException("Wrong Key - DOUBLE deskey Must be 32 long Hexadecimal data!!");
// this.pvki = pvki ;
// }
// /**
// * PVK constructor with default pvki = 1.
// * @param aKey DES key double length
// * @throws DesKeyException if a exception arrives
// */
// public Pvk (String aKey ) throws DesKeyException {
//
// this (aKey, 1 );
// }
//
// public int getPvki () {
// return this.pvki ;
// }
//
// private static Boolean validatePvki ( int pvki ){
//
// if ( pvki < 1 || pvki > 6 ){
// return false ;
// }
// return true ;
// }
//
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/PvkTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Pvk;
package com.indarsoft.cryptocard.symmetrickey;
public class PvkTest {
public String simpleKeyStr = "0123456789ABCDEF" ;
public String doubleKeyStr = "F1FD8AC2EFCE3BC8F1FD8AC2EFCE3BC8" ;
public String simpleKeyCheckValue = "D5D44F";
public String doubleKeyCheckValue = "13F5CC";
@Test
public void testPvkCheckValueDouble() {
Pvk a = null ;
try{
a = new Pvk(doubleKeyStr, 1 ) ;
}
| catch ( DesKeyException e ){
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/card/LuhnTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.utl.CheckDigit;
| package com.indarsoft.cryptocard.card;
public class LuhnTest {
@Test
public void validate() {
String b = new String("5200000000000007");
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/card/LuhnTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.utl.CheckDigit;
package com.indarsoft.cryptocard.card;
public class LuhnTest {
@Test
public void validate() {
String b = new String("5200000000000007");
| boolean returnedValue = CheckDigit.validate ( b ) ;
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkMasterCardTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
| package com.indarsoft.cryptocard.symmetrickey;
public class ZpkMasterCardTest {
public String simpleKeyStr = "ABCDEF2222220101" ;
public String doubleKeyStr = "ABCDEF6666660101ABCDEF6666660202" ;
public String simpleKeyCheckValue = "76A6C0";
public String doubleKeyCheckValue = "5D8F82";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkSimple() {
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkMasterCardTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
package com.indarsoft.cryptocard.symmetrickey;
public class ZpkMasterCardTest {
public String simpleKeyStr = "ABCDEF2222220101" ;
public String doubleKeyStr = "ABCDEF6666660101ABCDEF6666660202" ;
public String simpleKeyCheckValue = "76A6C0";
public String doubleKeyCheckValue = "5D8F82";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkSimple() {
| Zpk a = null ;
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkMasterCardTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
| import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
| package com.indarsoft.cryptocard.symmetrickey;
public class ZpkMasterCardTest {
public String simpleKeyStr = "ABCDEF2222220101" ;
public String doubleKeyStr = "ABCDEF6666660101ABCDEF6666660202" ;
public String simpleKeyCheckValue = "76A6C0";
public String doubleKeyCheckValue = "5D8F82";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkSimple() {
Zpk a = null ;
try{
a = new Zpk(simpleKeyStr) ;
}
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/DesKeyException.java
// public class DesKeyException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -8029564933566258445L;
// private String msg ;
//
// public DesKeyException (String msg ) {
// super(msg);
// this.msg = msg ;
// }
//
// public DesKeyException() {
//
// super("Unhandled KeyException !!") ;
// }
//
// public String getMessage(){
// return msg ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/symmetrickey/Zpk.java
// public class Zpk extends DesKey {
//
// private int version ;
//
// public Zpk (String aKey ) throws DesKeyException {
//
// super(aKey );
// this.version = 1 ;
// }
//
// public Zpk (String aKey, int aVersion ) throws DesKeyException {
//
// super(aKey );
// this.version = aVersion ;
// }
//
// public int getVersion () {
// return this.version ;
// }
//
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/symmetrickey/ZpkMasterCardTest.java
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import com.indarsoft.cryptocard.symmetrickey.DesKeyException;
import com.indarsoft.cryptocard.symmetrickey.Zpk;
package com.indarsoft.cryptocard.symmetrickey;
public class ZpkMasterCardTest {
public String simpleKeyStr = "ABCDEF2222220101" ;
public String doubleKeyStr = "ABCDEF6666660101ABCDEF6666660202" ;
public String simpleKeyCheckValue = "76A6C0";
public String doubleKeyCheckValue = "5D8F82";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testZpkSimple() {
Zpk a = null ;
try{
a = new Zpk(simpleKeyStr) ;
}
| catch ( DesKeyException e ){
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/utl/PinValidationDataTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/CustomerVerifyException.java
// public class CustomerVerifyException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = -7559475613700140437L;
//
// public CustomerVerifyException (String msg ) {
// super(msg);
// }
//
// public CustomerVerifyException() {
// super("Unhandled Exception !!") ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/PinValidationData.java
// public class PinValidationData {
//
// /**
// * Build a "customized" PIN validation data block conforming Thales 7000, from an input Pan Number.
// * <pre>
// * Refer to Thales 7000 manual - 9.4 IBM PIN Offset (command code value 'DE' )
// * - Computes Account Number : Takes the 12 right-most digits of the account number, excluding check digit.
// * - Inserts the last 5 digits of the account number (previous data) in the position (pos).
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param index position to insert the last 5 digits of the account number
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build7000(String panNumber, int index ) throws CustomerVerifyException {
// /*
// * accountNumber : The 12 right-most digits of the account number, excluding the
// * check digit.
// */
// int length = panNumber.length();
// String accountNumber = panNumber.substring(length - 1 - 12 , length - 1);
// if ( accountNumber.length() != 12 ) throw new CustomerVerifyException("build7000: accountNumber must be 12 right-most digits of the pan number");
// if ( index < 1 | index > 12 ) throw new CustomerVerifyException("build7000: index must be between 1 and 12");
// /*
// * Build Pin Validation Data
// */
// String last5digits = accountNumber.substring( accountNumber.length() - 5 ) ;
// String pinvaldat = accountNumber.substring(0, index - 1 ) + last5digits + accountNumber.substring( index ) ;
// return pinvaldat ;
// }
// /**
// * Build a "customized" PIN validation data block conforming Thales 8000, from an input Pan Number.
// * <pre>
// * Refer to Thales HSM 8000 Host Command Reference Manual - Generate an IBM PIN Offset (command code value 'DE' )
// * - Takes characters from Pan Number starting at position sp and ending at ep ( 1 {@literal<}= sp {@literal<} ep {@literal<}= 15 )
// * - Add pad character until a 16 characters length is completed.
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param sp start position from Pan Number
// * @param ep end position from Pan Number
// * @param pad padding character
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build8000(String panNumber, int sp , int ep, char pad ) throws CustomerVerifyException {
//
// if ( sp < 1 | ep > 15 | sp >= ep ) throw new CustomerVerifyException("build8000: sp-start ep-end ( 1 <= sp < ep <= 15 ) "+sp+"-"+ep);
// if ( !Ascii.isNumericHex( pad)) throw new CustomerVerifyException("build8000: pad character must be hexadecimal "+pad);
//
// /*
// * Build Pin Validation Data
// */
// String pinvaldat = panNumber.substring(sp-1, ep ) ;
// for (int i=pinvaldat.length(); i<16;i++) pinvaldat = pinvaldat + pad ;
// return pinvaldat ;
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.customerverify.CustomerVerifyException;
import com.indarsoft.cryptocard.utl.PinValidationData;
| package com.indarsoft.cryptocard.utl;
public class PinValidationDataTest {
public static String panNumber = "9704151300007029";
public static String pinValidationData = "4151300007000702";
public static String pinValidationData2 = "970415130000702F";
String returnedValue = "";
@Test
public void build7000() {
/**
* Insert last5digits of account number in position 12 of account number
*
*/
try {
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/CustomerVerifyException.java
// public class CustomerVerifyException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = -7559475613700140437L;
//
// public CustomerVerifyException (String msg ) {
// super(msg);
// }
//
// public CustomerVerifyException() {
// super("Unhandled Exception !!") ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/PinValidationData.java
// public class PinValidationData {
//
// /**
// * Build a "customized" PIN validation data block conforming Thales 7000, from an input Pan Number.
// * <pre>
// * Refer to Thales 7000 manual - 9.4 IBM PIN Offset (command code value 'DE' )
// * - Computes Account Number : Takes the 12 right-most digits of the account number, excluding check digit.
// * - Inserts the last 5 digits of the account number (previous data) in the position (pos).
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param index position to insert the last 5 digits of the account number
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build7000(String panNumber, int index ) throws CustomerVerifyException {
// /*
// * accountNumber : The 12 right-most digits of the account number, excluding the
// * check digit.
// */
// int length = panNumber.length();
// String accountNumber = panNumber.substring(length - 1 - 12 , length - 1);
// if ( accountNumber.length() != 12 ) throw new CustomerVerifyException("build7000: accountNumber must be 12 right-most digits of the pan number");
// if ( index < 1 | index > 12 ) throw new CustomerVerifyException("build7000: index must be between 1 and 12");
// /*
// * Build Pin Validation Data
// */
// String last5digits = accountNumber.substring( accountNumber.length() - 5 ) ;
// String pinvaldat = accountNumber.substring(0, index - 1 ) + last5digits + accountNumber.substring( index ) ;
// return pinvaldat ;
// }
// /**
// * Build a "customized" PIN validation data block conforming Thales 8000, from an input Pan Number.
// * <pre>
// * Refer to Thales HSM 8000 Host Command Reference Manual - Generate an IBM PIN Offset (command code value 'DE' )
// * - Takes characters from Pan Number starting at position sp and ending at ep ( 1 {@literal<}= sp {@literal<} ep {@literal<}= 15 )
// * - Add pad character until a 16 characters length is completed.
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param sp start position from Pan Number
// * @param ep end position from Pan Number
// * @param pad padding character
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build8000(String panNumber, int sp , int ep, char pad ) throws CustomerVerifyException {
//
// if ( sp < 1 | ep > 15 | sp >= ep ) throw new CustomerVerifyException("build8000: sp-start ep-end ( 1 <= sp < ep <= 15 ) "+sp+"-"+ep);
// if ( !Ascii.isNumericHex( pad)) throw new CustomerVerifyException("build8000: pad character must be hexadecimal "+pad);
//
// /*
// * Build Pin Validation Data
// */
// String pinvaldat = panNumber.substring(sp-1, ep ) ;
// for (int i=pinvaldat.length(); i<16;i++) pinvaldat = pinvaldat + pad ;
// return pinvaldat ;
// }
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/utl/PinValidationDataTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.customerverify.CustomerVerifyException;
import com.indarsoft.cryptocard.utl.PinValidationData;
package com.indarsoft.cryptocard.utl;
public class PinValidationDataTest {
public static String panNumber = "9704151300007029";
public static String pinValidationData = "4151300007000702";
public static String pinValidationData2 = "970415130000702F";
String returnedValue = "";
@Test
public void build7000() {
/**
* Insert last5digits of account number in position 12 of account number
*
*/
try {
| returnedValue = PinValidationData.build7000(panNumber, 12);
|
jporras66/cryptocard | cryptocard/src/test/java/com/indarsoft/cryptocard/utl/PinValidationDataTest.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/CustomerVerifyException.java
// public class CustomerVerifyException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = -7559475613700140437L;
//
// public CustomerVerifyException (String msg ) {
// super(msg);
// }
//
// public CustomerVerifyException() {
// super("Unhandled Exception !!") ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/PinValidationData.java
// public class PinValidationData {
//
// /**
// * Build a "customized" PIN validation data block conforming Thales 7000, from an input Pan Number.
// * <pre>
// * Refer to Thales 7000 manual - 9.4 IBM PIN Offset (command code value 'DE' )
// * - Computes Account Number : Takes the 12 right-most digits of the account number, excluding check digit.
// * - Inserts the last 5 digits of the account number (previous data) in the position (pos).
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param index position to insert the last 5 digits of the account number
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build7000(String panNumber, int index ) throws CustomerVerifyException {
// /*
// * accountNumber : The 12 right-most digits of the account number, excluding the
// * check digit.
// */
// int length = panNumber.length();
// String accountNumber = panNumber.substring(length - 1 - 12 , length - 1);
// if ( accountNumber.length() != 12 ) throw new CustomerVerifyException("build7000: accountNumber must be 12 right-most digits of the pan number");
// if ( index < 1 | index > 12 ) throw new CustomerVerifyException("build7000: index must be between 1 and 12");
// /*
// * Build Pin Validation Data
// */
// String last5digits = accountNumber.substring( accountNumber.length() - 5 ) ;
// String pinvaldat = accountNumber.substring(0, index - 1 ) + last5digits + accountNumber.substring( index ) ;
// return pinvaldat ;
// }
// /**
// * Build a "customized" PIN validation data block conforming Thales 8000, from an input Pan Number.
// * <pre>
// * Refer to Thales HSM 8000 Host Command Reference Manual - Generate an IBM PIN Offset (command code value 'DE' )
// * - Takes characters from Pan Number starting at position sp and ending at ep ( 1 {@literal<}= sp {@literal<} ep {@literal<}= 15 )
// * - Add pad character until a 16 characters length is completed.
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param sp start position from Pan Number
// * @param ep end position from Pan Number
// * @param pad padding character
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build8000(String panNumber, int sp , int ep, char pad ) throws CustomerVerifyException {
//
// if ( sp < 1 | ep > 15 | sp >= ep ) throw new CustomerVerifyException("build8000: sp-start ep-end ( 1 <= sp < ep <= 15 ) "+sp+"-"+ep);
// if ( !Ascii.isNumericHex( pad)) throw new CustomerVerifyException("build8000: pad character must be hexadecimal "+pad);
//
// /*
// * Build Pin Validation Data
// */
// String pinvaldat = panNumber.substring(sp-1, ep ) ;
// for (int i=pinvaldat.length(); i<16;i++) pinvaldat = pinvaldat + pad ;
// return pinvaldat ;
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.customerverify.CustomerVerifyException;
import com.indarsoft.cryptocard.utl.PinValidationData;
| package com.indarsoft.cryptocard.utl;
public class PinValidationDataTest {
public static String panNumber = "9704151300007029";
public static String pinValidationData = "4151300007000702";
public static String pinValidationData2 = "970415130000702F";
String returnedValue = "";
@Test
public void build7000() {
/**
* Insert last5digits of account number in position 12 of account number
*
*/
try {
returnedValue = PinValidationData.build7000(panNumber, 12);
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/customerverify/CustomerVerifyException.java
// public class CustomerVerifyException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = -7559475613700140437L;
//
// public CustomerVerifyException (String msg ) {
// super(msg);
// }
//
// public CustomerVerifyException() {
// super("Unhandled Exception !!") ;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/PinValidationData.java
// public class PinValidationData {
//
// /**
// * Build a "customized" PIN validation data block conforming Thales 7000, from an input Pan Number.
// * <pre>
// * Refer to Thales 7000 manual - 9.4 IBM PIN Offset (command code value 'DE' )
// * - Computes Account Number : Takes the 12 right-most digits of the account number, excluding check digit.
// * - Inserts the last 5 digits of the account number (previous data) in the position (pos).
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param index position to insert the last 5 digits of the account number
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build7000(String panNumber, int index ) throws CustomerVerifyException {
// /*
// * accountNumber : The 12 right-most digits of the account number, excluding the
// * check digit.
// */
// int length = panNumber.length();
// String accountNumber = panNumber.substring(length - 1 - 12 , length - 1);
// if ( accountNumber.length() != 12 ) throw new CustomerVerifyException("build7000: accountNumber must be 12 right-most digits of the pan number");
// if ( index < 1 | index > 12 ) throw new CustomerVerifyException("build7000: index must be between 1 and 12");
// /*
// * Build Pin Validation Data
// */
// String last5digits = accountNumber.substring( accountNumber.length() - 5 ) ;
// String pinvaldat = accountNumber.substring(0, index - 1 ) + last5digits + accountNumber.substring( index ) ;
// return pinvaldat ;
// }
// /**
// * Build a "customized" PIN validation data block conforming Thales 8000, from an input Pan Number.
// * <pre>
// * Refer to Thales HSM 8000 Host Command Reference Manual - Generate an IBM PIN Offset (command code value 'DE' )
// * - Takes characters from Pan Number starting at position sp and ending at ep ( 1 {@literal<}= sp {@literal<} ep {@literal<}= 15 )
// * - Add pad character until a 16 characters length is completed.
// * - Returns this data
// * </pre>
// * @param panNumber Pan Number from which to build Pin Validation Data
// * @param sp start position from Pan Number
// * @param ep end position from Pan Number
// * @param pad padding character
// * @return Pin Validation Data
// * @exception CustomerVerifyException if a exception arrives
// */
// public static String build8000(String panNumber, int sp , int ep, char pad ) throws CustomerVerifyException {
//
// if ( sp < 1 | ep > 15 | sp >= ep ) throw new CustomerVerifyException("build8000: sp-start ep-end ( 1 <= sp < ep <= 15 ) "+sp+"-"+ep);
// if ( !Ascii.isNumericHex( pad)) throw new CustomerVerifyException("build8000: pad character must be hexadecimal "+pad);
//
// /*
// * Build Pin Validation Data
// */
// String pinvaldat = panNumber.substring(sp-1, ep ) ;
// for (int i=pinvaldat.length(); i<16;i++) pinvaldat = pinvaldat + pad ;
// return pinvaldat ;
// }
// }
// Path: cryptocard/src/test/java/com/indarsoft/cryptocard/utl/PinValidationDataTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.indarsoft.cryptocard.customerverify.CustomerVerifyException;
import com.indarsoft.cryptocard.utl.PinValidationData;
package com.indarsoft.cryptocard.utl;
public class PinValidationDataTest {
public static String panNumber = "9704151300007029";
public static String pinValidationData = "4151300007000702";
public static String pinValidationData2 = "970415130000702F";
String returnedValue = "";
@Test
public void build7000() {
/**
* Insert last5digits of account number in position 12 of account number
*
*/
try {
returnedValue = PinValidationData.build7000(panNumber, 12);
| } catch (CustomerVerifyException e) {
|
jporras66/cryptocard | cryptocard/src/main/java/com/indarsoft/cryptocard/card/Card.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinBlockFormatType.java
// public enum PinBlockFormatType {
//
// //ISOFORMAT0(0), ISOFORMAT3(3), IBM3624(4) ;
// ISOFORMAT0(0), ISOFORMAT3(3);
// @SuppressWarnings("unused")
// private int value;
//
// private PinBlockFormatType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinValidationType.java
// public enum PinValidationType {
// VISA_PVV(0), IBM_3624_OFFSET(1) ;
// @SuppressWarnings("unused")
// private int value;
//
// private PinValidationType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
| import com.indarsoft.cryptocard.types.PinBlockFormatType;
import com.indarsoft.cryptocard.types.PinValidationType;
import com.indarsoft.cryptocard.utl.CheckDigit;
| package com.indarsoft.cryptocard.card;
/**
* Card
*
* @author fjavier.porras@gmail.com
*
*/
public class Card {
/**
* A valid pan number must have 12 to 19 decimal digits.
*/
private String panNumber;
/**
* Expiration Date holds year and month when the card1 will be expired.
*/
private String expirationDate;
/**
* Valid expiration date formats are "YYMM"-default and "MMYY"
*/
private String expirationDateFormat = "YYMM";
private String serviceCode;
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinBlockFormatType.java
// public enum PinBlockFormatType {
//
// //ISOFORMAT0(0), ISOFORMAT3(3), IBM3624(4) ;
// ISOFORMAT0(0), ISOFORMAT3(3);
// @SuppressWarnings("unused")
// private int value;
//
// private PinBlockFormatType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinValidationType.java
// public enum PinValidationType {
// VISA_PVV(0), IBM_3624_OFFSET(1) ;
// @SuppressWarnings("unused")
// private int value;
//
// private PinValidationType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/card/Card.java
import com.indarsoft.cryptocard.types.PinBlockFormatType;
import com.indarsoft.cryptocard.types.PinValidationType;
import com.indarsoft.cryptocard.utl.CheckDigit;
package com.indarsoft.cryptocard.card;
/**
* Card
*
* @author fjavier.porras@gmail.com
*
*/
public class Card {
/**
* A valid pan number must have 12 to 19 decimal digits.
*/
private String panNumber;
/**
* Expiration Date holds year and month when the card1 will be expired.
*/
private String expirationDate;
/**
* Valid expiration date formats are "YYMM"-default and "MMYY"
*/
private String expirationDateFormat = "YYMM";
private String serviceCode;
| private PinBlockFormatType pinblockFormatType;
|
jporras66/cryptocard | cryptocard/src/main/java/com/indarsoft/cryptocard/card/Card.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinBlockFormatType.java
// public enum PinBlockFormatType {
//
// //ISOFORMAT0(0), ISOFORMAT3(3), IBM3624(4) ;
// ISOFORMAT0(0), ISOFORMAT3(3);
// @SuppressWarnings("unused")
// private int value;
//
// private PinBlockFormatType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinValidationType.java
// public enum PinValidationType {
// VISA_PVV(0), IBM_3624_OFFSET(1) ;
// @SuppressWarnings("unused")
// private int value;
//
// private PinValidationType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
| import com.indarsoft.cryptocard.types.PinBlockFormatType;
import com.indarsoft.cryptocard.types.PinValidationType;
import com.indarsoft.cryptocard.utl.CheckDigit;
| package com.indarsoft.cryptocard.card;
/**
* Card
*
* @author fjavier.porras@gmail.com
*
*/
public class Card {
/**
* A valid pan number must have 12 to 19 decimal digits.
*/
private String panNumber;
/**
* Expiration Date holds year and month when the card1 will be expired.
*/
private String expirationDate;
/**
* Valid expiration date formats are "YYMM"-default and "MMYY"
*/
private String expirationDateFormat = "YYMM";
private String serviceCode;
private PinBlockFormatType pinblockFormatType;
/**
* V --{@literal>} VISA
* M --{@literal>} MASTERCARD
* O --{@literal>} OTHER
*/
private char cardBrand;
private int pvki;
private String pvv;
private String offset;
/**
* In our Pin implementation, it must be Decimal between 4 to 6 digits.
* <pre>
* For verification purposes in interchange transactions, the maximum PIN length is six digits.
* An issuer can elect to support longer PINs up to ibmoff maximum of 12 digits as
* specified in ISO 9564. However, ATM acquirers are not obligated to
* support PINs of more than six digits.
* </pre>
*/
private String pin;
private int pinLength;
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinBlockFormatType.java
// public enum PinBlockFormatType {
//
// //ISOFORMAT0(0), ISOFORMAT3(3), IBM3624(4) ;
// ISOFORMAT0(0), ISOFORMAT3(3);
// @SuppressWarnings("unused")
// private int value;
//
// private PinBlockFormatType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinValidationType.java
// public enum PinValidationType {
// VISA_PVV(0), IBM_3624_OFFSET(1) ;
// @SuppressWarnings("unused")
// private int value;
//
// private PinValidationType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/card/Card.java
import com.indarsoft.cryptocard.types.PinBlockFormatType;
import com.indarsoft.cryptocard.types.PinValidationType;
import com.indarsoft.cryptocard.utl.CheckDigit;
package com.indarsoft.cryptocard.card;
/**
* Card
*
* @author fjavier.porras@gmail.com
*
*/
public class Card {
/**
* A valid pan number must have 12 to 19 decimal digits.
*/
private String panNumber;
/**
* Expiration Date holds year and month when the card1 will be expired.
*/
private String expirationDate;
/**
* Valid expiration date formats are "YYMM"-default and "MMYY"
*/
private String expirationDateFormat = "YYMM";
private String serviceCode;
private PinBlockFormatType pinblockFormatType;
/**
* V --{@literal>} VISA
* M --{@literal>} MASTERCARD
* O --{@literal>} OTHER
*/
private char cardBrand;
private int pvki;
private String pvv;
private String offset;
/**
* In our Pin implementation, it must be Decimal between 4 to 6 digits.
* <pre>
* For verification purposes in interchange transactions, the maximum PIN length is six digits.
* An issuer can elect to support longer PINs up to ibmoff maximum of 12 digits as
* specified in ISO 9564. However, ATM acquirers are not obligated to
* support PINs of more than six digits.
* </pre>
*/
private String pin;
private int pinLength;
| private PinValidationType pinValidationType;
|
jporras66/cryptocard | cryptocard/src/main/java/com/indarsoft/cryptocard/card/Card.java | // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinBlockFormatType.java
// public enum PinBlockFormatType {
//
// //ISOFORMAT0(0), ISOFORMAT3(3), IBM3624(4) ;
// ISOFORMAT0(0), ISOFORMAT3(3);
// @SuppressWarnings("unused")
// private int value;
//
// private PinBlockFormatType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinValidationType.java
// public enum PinValidationType {
// VISA_PVV(0), IBM_3624_OFFSET(1) ;
// @SuppressWarnings("unused")
// private int value;
//
// private PinValidationType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
| import com.indarsoft.cryptocard.types.PinBlockFormatType;
import com.indarsoft.cryptocard.types.PinValidationType;
import com.indarsoft.cryptocard.utl.CheckDigit;
| byte aByte = 0x00;
if (st.length() != length) {
return false;
}
for (int i = 0; i < st.length(); i++) {
aByte = (byte) Character.getNumericValue(st.charAt(i));
if (aByte > 0x09) {
return false;
}
}
return true;
}
/**
* Validation for ibmoff Pan Number.
* <ul>
* <li> Pan number must be between 12 and 19 decimal characters
* <li> check digit must be OK (Luhn Algorithm)
* <li> In other case an CardException is generated
* </ul>
* @param panNumber input string value
* @exception CardException if a exception arrives
* @return boolean
*/
private boolean isvalidPanNumber(String panNumber) throws CardException{
int panNumberLength = panNumber.length();
if (panNumberLength < 12 || panNumberLength > 19) throw new CardException("panNumberEx1");
if (!validateisNumericAndLength(panNumber, panNumberLength)) throw new CardException("panNumberEx1");
| // Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinBlockFormatType.java
// public enum PinBlockFormatType {
//
// //ISOFORMAT0(0), ISOFORMAT3(3), IBM3624(4) ;
// ISOFORMAT0(0), ISOFORMAT3(3);
// @SuppressWarnings("unused")
// private int value;
//
// private PinBlockFormatType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/types/PinValidationType.java
// public enum PinValidationType {
// VISA_PVV(0), IBM_3624_OFFSET(1) ;
// @SuppressWarnings("unused")
// private int value;
//
// private PinValidationType (int value) {
// this.value = value;
// }
// }
//
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/utl/CheckDigit.java
// public class CheckDigit {
//
// public static boolean validate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// return luhn.isValid ( panNUmber ) ;
//
// }
//
// public static String calculate ( String panNUmber){
//
// LuhnCheckDigit luhn = new LuhnCheckDigit();
// String checkdigit;
// try {
// checkdigit = luhn.calculate( panNUmber );
// } catch (CheckDigitException e) {
// checkdigit = "CheckDigit.calculate : "+ e.getMessage() ;
// System.out.println(checkdigit);
// }
// return checkdigit ;
//
// }
//
// }
// Path: cryptocard/src/main/java/com/indarsoft/cryptocard/card/Card.java
import com.indarsoft.cryptocard.types.PinBlockFormatType;
import com.indarsoft.cryptocard.types.PinValidationType;
import com.indarsoft.cryptocard.utl.CheckDigit;
byte aByte = 0x00;
if (st.length() != length) {
return false;
}
for (int i = 0; i < st.length(); i++) {
aByte = (byte) Character.getNumericValue(st.charAt(i));
if (aByte > 0x09) {
return false;
}
}
return true;
}
/**
* Validation for ibmoff Pan Number.
* <ul>
* <li> Pan number must be between 12 and 19 decimal characters
* <li> check digit must be OK (Luhn Algorithm)
* <li> In other case an CardException is generated
* </ul>
* @param panNumber input string value
* @exception CardException if a exception arrives
* @return boolean
*/
private boolean isvalidPanNumber(String panNumber) throws CardException{
int panNumberLength = panNumber.length();
if (panNumberLength < 12 || panNumberLength > 19) throw new CardException("panNumberEx1");
if (!validateisNumericAndLength(panNumber, panNumberLength)) throw new CardException("panNumberEx1");
| boolean returnedValue = CheckDigit.validate(panNumber);
|
ikantech/IkantechSupport | src/com/ikantech/support/util/YiAsyncImageLoader.java | // Path: src/com/ikantech/support/listener/YiImageLoaderListener.java
// public interface YiImageLoaderListener
// {
// void onImageLoaded(String url, Bitmap bitmap);
// }
| import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import com.ikantech.support.cache.YiStoreCache;
import com.ikantech.support.listener.YiImageLoaderListener; | package com.ikantech.support.util;
public class YiAsyncImageLoader
{
private final static int HTTP_STATE_OK = 200;
private final static int BUFFER_SIZE = 1024 * 4;
private final static int DEFAULT_TIMEOUT = 30 * 1000;
private static YiStoreCache mImageCache = new YiStoreCache(16);
private YiAsyncImageLoader()
{
}
public static Bitmap loadBitmapFromeStoreSync(String key)
{
return mImageCache.get(key);
}
public static void removeMemoryCache(String key)
{
mImageCache.removeMemoryCache(key);
}
public static void loadBitmapFromStore(final String key, | // Path: src/com/ikantech/support/listener/YiImageLoaderListener.java
// public interface YiImageLoaderListener
// {
// void onImageLoaded(String url, Bitmap bitmap);
// }
// Path: src/com/ikantech/support/util/YiAsyncImageLoader.java
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import com.ikantech.support.cache.YiStoreCache;
import com.ikantech.support.listener.YiImageLoaderListener;
package com.ikantech.support.util;
public class YiAsyncImageLoader
{
private final static int HTTP_STATE_OK = 200;
private final static int BUFFER_SIZE = 1024 * 4;
private final static int DEFAULT_TIMEOUT = 30 * 1000;
private static YiStoreCache mImageCache = new YiStoreCache(16);
private YiAsyncImageLoader()
{
}
public static Bitmap loadBitmapFromeStoreSync(String key)
{
return mImageCache.get(key);
}
public static void removeMemoryCache(String key)
{
mImageCache.removeMemoryCache(key);
}
public static void loadBitmapFromStore(final String key, | final YiImageLoaderListener listener) |
ikantech/IkantechSupport | src/com/ikantech/support/cache/InAbsCache.java | // Path: src/com/ikantech/support/util/YiLRUMap.java
// @SuppressWarnings("serial")
// public class YiLRUMap<K, V> extends LinkedHashMap<K, V>
// {
// private int mCapacity;
//
// public YiLRUMap(int initialCapacity)
// {
// super(initialCapacity, 0.75F, true);
// mCapacity = initialCapacity;
// }
//
// @Override
// protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest)
// {
// return size() > mCapacity;
// }
// }
| import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import com.ikantech.support.util.YiLRUMap; | package com.ikantech.support.cache;
public abstract class InAbsCache<K, V>
{
protected static final int DEFAULT_CACHE_SIZE = 32;
private HashMap<K, V> mHardCache;
/**
* 当mHardCache的key大于Cache Size的时候,会根据LRU算法把最近没有被使用的key放入到这个缓存中。
* T使用了SoftReference,当内存空间不足时,此cache中的T会被垃圾回收掉
*/
private ConcurrentHashMap<K, SoftReference<V>> mSoftCache;
private int mCacheSize;
@SuppressWarnings("serial")
public InAbsCache(int cacheSize)
{
if (cacheSize < 1)
{
cacheSize = DEFAULT_CACHE_SIZE;
}
mCacheSize = cacheSize;
mSoftCache = new ConcurrentHashMap<K, SoftReference<V>>(mCacheSize / 2);
| // Path: src/com/ikantech/support/util/YiLRUMap.java
// @SuppressWarnings("serial")
// public class YiLRUMap<K, V> extends LinkedHashMap<K, V>
// {
// private int mCapacity;
//
// public YiLRUMap(int initialCapacity)
// {
// super(initialCapacity, 0.75F, true);
// mCapacity = initialCapacity;
// }
//
// @Override
// protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest)
// {
// return size() > mCapacity;
// }
// }
// Path: src/com/ikantech/support/cache/InAbsCache.java
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import com.ikantech.support.util.YiLRUMap;
package com.ikantech.support.cache;
public abstract class InAbsCache<K, V>
{
protected static final int DEFAULT_CACHE_SIZE = 32;
private HashMap<K, V> mHardCache;
/**
* 当mHardCache的key大于Cache Size的时候,会根据LRU算法把最近没有被使用的key放入到这个缓存中。
* T使用了SoftReference,当内存空间不足时,此cache中的T会被垃圾回收掉
*/
private ConcurrentHashMap<K, SoftReference<V>> mSoftCache;
private int mCacheSize;
@SuppressWarnings("serial")
public InAbsCache(int cacheSize)
{
if (cacheSize < 1)
{
cacheSize = DEFAULT_CACHE_SIZE;
}
mCacheSize = cacheSize;
mSoftCache = new ConcurrentHashMap<K, SoftReference<V>>(mCacheSize / 2);
| mHardCache = new YiLRUMap<K, V>(mCacheSize) |
ikantech/IkantechSupport | src/com/ikantech/support/proxy/YiDialogProxy.java | // Path: src/com/ikantech/support/util/YiDeviceUtils.java
// public class YiDeviceUtils
// {
// private YiDeviceUtils()
// {
//
// }
//
// public static DisplayMetrics getDisplayMetrics(Context context)
// {
// return context.getResources().getDisplayMetrics();
// }
//
// public static int dip2px(Context context, float dip) {
// float scale = context.getResources().getDisplayMetrics().density;
// return (int)(dip * scale + 0.5f);
// }
//
// public static int px2dip(Context context, float px) {
// float scale = context.getResources().getDisplayMetrics().density;
// return (int)(px / scale + 0.5f);
// }
//
// public static int getApiLevel()
// {
// return android.os.Build.VERSION.SDK_INT;
// }
//
// public static boolean isCompatible(int apiLevel)
// {
// return android.os.Build.VERSION.SDK_INT >= apiLevel;
// }
//
// public static String getCpuAbi()
// {
// if (isCompatible(4))
// {
// Field field;
// try
// {
// field = android.os.Build.class.getField("CPU_ABI");
// return field.get(null).toString();
// }
// catch (Exception e)
// {
// YiLog.getInstance().w(e,
// "Announce to be android 1.6 but no CPU ABI field");
// }
//
// }
// return "armeabi";
// }
//
// public final static int getNumCores()
// {
// // Private Class to display only CPU devices in the directory listing
// class CpuFilter implements FileFilter
// {
// @Override
// public boolean accept(File pathname)
// {
// // Check if filename is "cpu", followed by a single digit number
// if (Pattern.matches("cpu[0-9]", pathname.getName()))
// {
// return true;
// }
// return false;
// }
// }
// try
// {
// // Get directory containing CPU info
// File dir = new File("/sys/devices/system/cpu/");
// // Filter to only list the devices we care about
// File[] files = dir.listFiles(new CpuFilter());
// // Return the number of cores (virtual CPU devices)
// return files.length;
// }
// catch (Exception e)
// {
// return Runtime.getRuntime().availableProcessors();
// }
// }
//
// public static boolean isInstalledOnSdCard(Context context)
// {
// // check for API level 8 and higher
// if (isCompatible(8))
// {
// PackageManager pm = context.getPackageManager();
// try
// {
// PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
// ApplicationInfo ai = pi.applicationInfo;
// return (ai.flags & 0x00040000 /*
// * ApplicationInfo.
// * FLAG_EXTERNAL_STORAGE
// */) == 0x00040000 /*
// * ApplicationInfo.
// * FLAG_EXTERNAL_STORAGE
// */;
// }
// catch (NameNotFoundException e)
// {
// // ignore
// }
// }
//
// // check for API level 7 - check files dir
// try
// {
// String filesDir = context.getFilesDir().getAbsolutePath();
// if (filesDir.startsWith("/data/"))
// {
// return false;
// }
// else if (filesDir.contains(Environment
// .getExternalStorageDirectory().getPath()))
// {
// return true;
// }
// }
// catch (Throwable e)
// {
// // ignore
// }
//
// return false;
// }
// }
| import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.ikantech.support.R;
import com.ikantech.support.util.YiDeviceUtils; | mProgressDialogMsg.setVisibility(View.GONE);
}
public void showProgressDialogMsg()
{
initProgressDialog();
mProgressDialogMsg.setVisibility(View.VISIBLE);
}
public void setProgressDialogCancelable(boolean flag)
{
initProgressDialog();
mProgressDialog.setCancelable(flag);
}
public void setProgressDialogCanceledOnTouchOutside(boolean cancel)
{
initProgressDialog();
mProgressDialog.setCanceledOnTouchOutside(cancel);
}
public void showProgressDialog()
{
mHandler.sendEmptyMessage(MSG_SHOW_PROGRESS_DIALOG);
}
protected void _showProgressDialog()
{
initProgressDialog();
mProgressDialog.show(); | // Path: src/com/ikantech/support/util/YiDeviceUtils.java
// public class YiDeviceUtils
// {
// private YiDeviceUtils()
// {
//
// }
//
// public static DisplayMetrics getDisplayMetrics(Context context)
// {
// return context.getResources().getDisplayMetrics();
// }
//
// public static int dip2px(Context context, float dip) {
// float scale = context.getResources().getDisplayMetrics().density;
// return (int)(dip * scale + 0.5f);
// }
//
// public static int px2dip(Context context, float px) {
// float scale = context.getResources().getDisplayMetrics().density;
// return (int)(px / scale + 0.5f);
// }
//
// public static int getApiLevel()
// {
// return android.os.Build.VERSION.SDK_INT;
// }
//
// public static boolean isCompatible(int apiLevel)
// {
// return android.os.Build.VERSION.SDK_INT >= apiLevel;
// }
//
// public static String getCpuAbi()
// {
// if (isCompatible(4))
// {
// Field field;
// try
// {
// field = android.os.Build.class.getField("CPU_ABI");
// return field.get(null).toString();
// }
// catch (Exception e)
// {
// YiLog.getInstance().w(e,
// "Announce to be android 1.6 but no CPU ABI field");
// }
//
// }
// return "armeabi";
// }
//
// public final static int getNumCores()
// {
// // Private Class to display only CPU devices in the directory listing
// class CpuFilter implements FileFilter
// {
// @Override
// public boolean accept(File pathname)
// {
// // Check if filename is "cpu", followed by a single digit number
// if (Pattern.matches("cpu[0-9]", pathname.getName()))
// {
// return true;
// }
// return false;
// }
// }
// try
// {
// // Get directory containing CPU info
// File dir = new File("/sys/devices/system/cpu/");
// // Filter to only list the devices we care about
// File[] files = dir.listFiles(new CpuFilter());
// // Return the number of cores (virtual CPU devices)
// return files.length;
// }
// catch (Exception e)
// {
// return Runtime.getRuntime().availableProcessors();
// }
// }
//
// public static boolean isInstalledOnSdCard(Context context)
// {
// // check for API level 8 and higher
// if (isCompatible(8))
// {
// PackageManager pm = context.getPackageManager();
// try
// {
// PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
// ApplicationInfo ai = pi.applicationInfo;
// return (ai.flags & 0x00040000 /*
// * ApplicationInfo.
// * FLAG_EXTERNAL_STORAGE
// */) == 0x00040000 /*
// * ApplicationInfo.
// * FLAG_EXTERNAL_STORAGE
// */;
// }
// catch (NameNotFoundException e)
// {
// // ignore
// }
// }
//
// // check for API level 7 - check files dir
// try
// {
// String filesDir = context.getFilesDir().getAbsolutePath();
// if (filesDir.startsWith("/data/"))
// {
// return false;
// }
// else if (filesDir.contains(Environment
// .getExternalStorageDirectory().getPath()))
// {
// return true;
// }
// }
// catch (Throwable e)
// {
// // ignore
// }
//
// return false;
// }
// }
// Path: src/com/ikantech/support/proxy/YiDialogProxy.java
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.ikantech.support.R;
import com.ikantech.support.util.YiDeviceUtils;
mProgressDialogMsg.setVisibility(View.GONE);
}
public void showProgressDialogMsg()
{
initProgressDialog();
mProgressDialogMsg.setVisibility(View.VISIBLE);
}
public void setProgressDialogCancelable(boolean flag)
{
initProgressDialog();
mProgressDialog.setCancelable(flag);
}
public void setProgressDialogCanceledOnTouchOutside(boolean cancel)
{
initProgressDialog();
mProgressDialog.setCanceledOnTouchOutside(cancel);
}
public void showProgressDialog()
{
mHandler.sendEmptyMessage(MSG_SHOW_PROGRESS_DIALOG);
}
protected void _showProgressDialog()
{
initProgressDialog();
mProgressDialog.show(); | DisplayMetrics dm = YiDeviceUtils |
versionone/VersionOne.Integration.Jenkins | src/main/java/com/versionone/jenkins/JenkinsBuildInfo.java | // Path: src/main/java/com/versionone/integration/ciCommon/BuildInfo.java
// public interface BuildInfo {
//
// String getProjectName();
// long getBuildId();
// Date getStartTime();
// long getElapsedTime();
//
// /**
// * Defines success of build.
// *
// * @return true if build is successful; otherwise - false.
// */
// boolean isSuccessful();
//
// /**
// * Defines whether build was manualy forced.
// *
// * @return true if build was forced; otherwise - false.
// */
// boolean isForced();
//
// /**
// * Check whether build have any VCS changes.
// *
// * @return
// */
// boolean hasChanges();
//
// /**
// * Gets list of VCS changes included in the build.
// *
// * @return Iterable of VCS changes.
// */
// Iterable<VcsModification> getChanges();
//
// /**
// * @return url of build results web page.
// */
// String getUrl();
//
// /**
// * @return name of build. (may be equals to {@link #getBuildId()})
// */
// String getBuildName();
// }
//
// Path: src/main/java/com/versionone/integration/ciCommon/VcsModification.java
// public interface VcsModification {
//
// String getUserName();
//
// String getComment();
//
// /**
// * Get modification date.
// *
// * @return Date and time the modification occur. Or null.
// */
// Date getDate();
//
// String getId();
// }
| import hudson.model.Action;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Hudson;
import hudson.scm.ChangeLogSet;
import java.io.PrintStream;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import com.versionone.integration.ciCommon.BuildInfo;
import com.versionone.integration.ciCommon.VcsModification; |
public Date getStartTime() {
return build.getTimestamp().getTime();
}
public long getElapsedTime() {
return elapsedTime;
}
public boolean isSuccessful() {
return build.getResult() == Result.SUCCESS;
}
public boolean isForced() {
for (Action action : build.getActions()) {
if (action instanceof CauseAction) {
for (Object cause : ((CauseAction) action).getCauses()) {
if (cause instanceof Cause.UserCause) {
return true;
}
}
}
}
return false;
}
public boolean hasChanges() {
return !build.getChangeSet().isEmptySet();
}
| // Path: src/main/java/com/versionone/integration/ciCommon/BuildInfo.java
// public interface BuildInfo {
//
// String getProjectName();
// long getBuildId();
// Date getStartTime();
// long getElapsedTime();
//
// /**
// * Defines success of build.
// *
// * @return true if build is successful; otherwise - false.
// */
// boolean isSuccessful();
//
// /**
// * Defines whether build was manualy forced.
// *
// * @return true if build was forced; otherwise - false.
// */
// boolean isForced();
//
// /**
// * Check whether build have any VCS changes.
// *
// * @return
// */
// boolean hasChanges();
//
// /**
// * Gets list of VCS changes included in the build.
// *
// * @return Iterable of VCS changes.
// */
// Iterable<VcsModification> getChanges();
//
// /**
// * @return url of build results web page.
// */
// String getUrl();
//
// /**
// * @return name of build. (may be equals to {@link #getBuildId()})
// */
// String getBuildName();
// }
//
// Path: src/main/java/com/versionone/integration/ciCommon/VcsModification.java
// public interface VcsModification {
//
// String getUserName();
//
// String getComment();
//
// /**
// * Get modification date.
// *
// * @return Date and time the modification occur. Or null.
// */
// Date getDate();
//
// String getId();
// }
// Path: src/main/java/com/versionone/jenkins/JenkinsBuildInfo.java
import hudson.model.Action;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Hudson;
import hudson.scm.ChangeLogSet;
import java.io.PrintStream;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import com.versionone.integration.ciCommon.BuildInfo;
import com.versionone.integration.ciCommon.VcsModification;
public Date getStartTime() {
return build.getTimestamp().getTime();
}
public long getElapsedTime() {
return elapsedTime;
}
public boolean isSuccessful() {
return build.getResult() == Result.SUCCESS;
}
public boolean isForced() {
for (Action action : build.getActions()) {
if (action instanceof CauseAction) {
for (Object cause : ((CauseAction) action).getCauses()) {
if (cause instanceof Cause.UserCause) {
return true;
}
}
}
}
return false;
}
public boolean hasChanges() {
return !build.getChangeSet().isEmptySet();
}
| public Iterable<VcsModification> getChanges() { |
versionone/VersionOne.Integration.Jenkins | src/test/java/com/versionone/hudson/SvnModificationTest.java | // Path: src/main/java/com/versionone/jenkins/SvnModification.java
// public class SvnModification implements VcsModification {
//
// private final SubversionChangeLogSet.LogEntry entry;
//
// public SvnModification(SubversionChangeLogSet.LogEntry logEntry) {
// entry = logEntry;
// }
//
// public String getUserName() {
// return entry.getAuthor().getFullName();
// }
//
// public String getComment() {
// return entry.getMsg();
// }
//
// /**
// * @return date of commit or null if date cannot be parsed.
// */
// public Date getDate() {
// String dateWithoutMicrosecond = removeMicrosecondFromDate(entry.getDate());
// try {
// final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
// df.setTimeZone(TimeZone.getTimeZone("GMT"));
// return df.parse(dateWithoutMicrosecond);
// } catch (ParseException e) {
// return null;
// }
// }
//
// private String removeMicrosecondFromDate(String date) {
// String[] dateParts = date.split("\\.");
// if (dateParts.length != 2 || dateParts[1].length() != 7) {
// return date;
// }
// String millisecond = dateParts[1].substring(0, 3);
// return dateParts[0] + "." + millisecond + "Z";
// }
//
// public String getId() {
// return String.valueOf(entry.getRevision());
// }
// }
| import hudson.scm.SubversionChangeLogSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.Assert;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import com.versionone.jenkins.SvnModification; | package com.versionone.hudson;
public class SvnModificationTest {
private Mockery mockery = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
@Test
public void getDate() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+4"));
final String gmtDate = "2012-01-12T08:43:41.359375Z";//SVN plugin returns date in GMT
final String localDateWithoutMicrosecond = "2012-01-12T12:43:41.359Z"; | // Path: src/main/java/com/versionone/jenkins/SvnModification.java
// public class SvnModification implements VcsModification {
//
// private final SubversionChangeLogSet.LogEntry entry;
//
// public SvnModification(SubversionChangeLogSet.LogEntry logEntry) {
// entry = logEntry;
// }
//
// public String getUserName() {
// return entry.getAuthor().getFullName();
// }
//
// public String getComment() {
// return entry.getMsg();
// }
//
// /**
// * @return date of commit or null if date cannot be parsed.
// */
// public Date getDate() {
// String dateWithoutMicrosecond = removeMicrosecondFromDate(entry.getDate());
// try {
// final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
// df.setTimeZone(TimeZone.getTimeZone("GMT"));
// return df.parse(dateWithoutMicrosecond);
// } catch (ParseException e) {
// return null;
// }
// }
//
// private String removeMicrosecondFromDate(String date) {
// String[] dateParts = date.split("\\.");
// if (dateParts.length != 2 || dateParts[1].length() != 7) {
// return date;
// }
// String millisecond = dateParts[1].substring(0, 3);
// return dateParts[0] + "." + millisecond + "Z";
// }
//
// public String getId() {
// return String.valueOf(entry.getRevision());
// }
// }
// Path: src/test/java/com/versionone/hudson/SvnModificationTest.java
import hudson.scm.SubversionChangeLogSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.Assert;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import com.versionone.jenkins.SvnModification;
package com.versionone.hudson;
public class SvnModificationTest {
private Mockery mockery = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
@Test
public void getDate() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+4"));
final String gmtDate = "2012-01-12T08:43:41.359375Z";//SVN plugin returns date in GMT
final String localDateWithoutMicrosecond = "2012-01-12T12:43:41.359Z"; | SvnModification modification = CreateSvnModification(gmtDate); |
versionone/VersionOne.Integration.Jenkins | src/main/java/com/versionone/integration/ciCommon/V1Worker.java | // Path: src/main/java/com/versionone/jenkins/MessagesRes.java
// public class MessagesRes {
//
// private final static ResourceBundleHolder holder = ResourceBundleHolder.get(MessagesRes.class);
//
// public static String VersionOne_Notifier() {
// return holder.format("VersionOne.Notifier");
// }
//
// public static Localizable _VersionOne_Notifier() {
// return new Localizable(holder, "VersionOne.Notifier");
// }
//
// public static String connectionValid() {
// return holder.format("connectionValid");
// }
//
// public static String connectionFailedPath() {
// return holder.format("connectionFailedPath");
// }
//
// public static String connectionFailedUsername() {
// return holder.format("connectionFailedUsername");
// }
//
// public static String connectionFailedRefField(Object string) {
// return holder.format("connectionFailedRefField", string);
// }
//
// public static String connectionFailedProxyUrlMalformed() {
// return holder.format("connectionFailedProxyUrlMalformed");
// }
//
// public static String connectionFailedAccessToken() {
// return holder.format("connectionFailedAccessToken");
// }
//
// public static String cannotBeEmpty() {
// return holder.format("cannotBeEmpty");
// }
//
// public static String pathWrong() {
// return holder.format("pathWrong");
// }
//
// public static String pattternWrong() {
// return holder.format("patternWrong");
// }
//
// public static String processSuccess() {
// return holder.format("processedSuccessfully");
// }
//
// public static String connectionIsNotCorrect() {
// return holder.format("connectionIsNotCorrect");
// }
//
// public static String buildRunAlreadyExist() {
// return holder.format("buildRunAlreadyExist");
// }
//
// public static String buildProjectNotFound() {
// return holder.format("buildProjectNotFound");
// }
//
// public static String workitemClosedCannotAttachData(String workitemId) {
// return holder.format("workitemClosedCannotAttachData", workitemId);
// }
// }
| import java.io.PrintStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.versionone.DB;
import com.versionone.apiclient.exceptions.APIException;
import com.versionone.apiclient.exceptions.ConnectionException;
import com.versionone.apiclient.exceptions.OidException;
import com.versionone.apiclient.filters.*;
import com.versionone.apiclient.interfaces.IAttributeDefinition;
import com.versionone.jenkins.MessagesRes;
import com.versionone.apiclient.exceptions.V1Exception;
import com.versionone.apiclient.interfaces.IAssetType;
import com.versionone.apiclient.interfaces.IServices;
import com.versionone.apiclient.services.QueryResult;
import com.versionone.apiclient.*;
import java.net.MalformedURLException; | }
}
private String buildChangeSetName(VcsModification change) {
StringBuilder name = new StringBuilder();
name.append('\'');
name.append(change.getUserName());
if (change.getDate() != null) {
name.append("\' on \'");
name.append(new DB.DateTime(change.getDate()));
}
name.append('\'');
return name.toString();
}
private void associateWithBuildRun(Asset buildRun, Collection<Asset> changeSets, Set<Asset> workitems) throws V1Exception, MalformedURLException {
IAttributeDefinition buildRunChangeSetsAttrDef = buildRun.getAssetType().getAttributeDefinition("ChangeSets");
for (Asset changeSet : changeSets) {
IAttributeDefinition changeSetNameAttrDef = changeSet.getAssetType().getAttributeDefinition("Name");
IAttributeDefinition changeSetPrimaryWorkitemsAttrDef = changeSet.getAssetType().getAttributeDefinition("PrimaryWorkitems");
buildRun.addAttributeValue(buildRunChangeSetsAttrDef, changeSet.getOid());
logger.println("VersionOne: Added changeset " + changeSet.getAttribute(changeSetNameAttrDef).getValue());
for (Asset workitem : workitems) {
IAttributeDefinition workItemIsClosedAttrDef = workitem.getAssetType().getAttributeDefinition("IsClosed");
IAttributeDefinition workItemCompletedInBuildRunsAttrDef = workitem.getAssetType().getAttributeDefinition("CompletedInBuildRuns");
if (Boolean.parseBoolean(workitem.getAttribute(workItemIsClosedAttrDef).getValue().toString())) { | // Path: src/main/java/com/versionone/jenkins/MessagesRes.java
// public class MessagesRes {
//
// private final static ResourceBundleHolder holder = ResourceBundleHolder.get(MessagesRes.class);
//
// public static String VersionOne_Notifier() {
// return holder.format("VersionOne.Notifier");
// }
//
// public static Localizable _VersionOne_Notifier() {
// return new Localizable(holder, "VersionOne.Notifier");
// }
//
// public static String connectionValid() {
// return holder.format("connectionValid");
// }
//
// public static String connectionFailedPath() {
// return holder.format("connectionFailedPath");
// }
//
// public static String connectionFailedUsername() {
// return holder.format("connectionFailedUsername");
// }
//
// public static String connectionFailedRefField(Object string) {
// return holder.format("connectionFailedRefField", string);
// }
//
// public static String connectionFailedProxyUrlMalformed() {
// return holder.format("connectionFailedProxyUrlMalformed");
// }
//
// public static String connectionFailedAccessToken() {
// return holder.format("connectionFailedAccessToken");
// }
//
// public static String cannotBeEmpty() {
// return holder.format("cannotBeEmpty");
// }
//
// public static String pathWrong() {
// return holder.format("pathWrong");
// }
//
// public static String pattternWrong() {
// return holder.format("patternWrong");
// }
//
// public static String processSuccess() {
// return holder.format("processedSuccessfully");
// }
//
// public static String connectionIsNotCorrect() {
// return holder.format("connectionIsNotCorrect");
// }
//
// public static String buildRunAlreadyExist() {
// return holder.format("buildRunAlreadyExist");
// }
//
// public static String buildProjectNotFound() {
// return holder.format("buildProjectNotFound");
// }
//
// public static String workitemClosedCannotAttachData(String workitemId) {
// return holder.format("workitemClosedCannotAttachData", workitemId);
// }
// }
// Path: src/main/java/com/versionone/integration/ciCommon/V1Worker.java
import java.io.PrintStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.versionone.DB;
import com.versionone.apiclient.exceptions.APIException;
import com.versionone.apiclient.exceptions.ConnectionException;
import com.versionone.apiclient.exceptions.OidException;
import com.versionone.apiclient.filters.*;
import com.versionone.apiclient.interfaces.IAttributeDefinition;
import com.versionone.jenkins.MessagesRes;
import com.versionone.apiclient.exceptions.V1Exception;
import com.versionone.apiclient.interfaces.IAssetType;
import com.versionone.apiclient.interfaces.IServices;
import com.versionone.apiclient.services.QueryResult;
import com.versionone.apiclient.*;
import java.net.MalformedURLException;
}
}
private String buildChangeSetName(VcsModification change) {
StringBuilder name = new StringBuilder();
name.append('\'');
name.append(change.getUserName());
if (change.getDate() != null) {
name.append("\' on \'");
name.append(new DB.DateTime(change.getDate()));
}
name.append('\'');
return name.toString();
}
private void associateWithBuildRun(Asset buildRun, Collection<Asset> changeSets, Set<Asset> workitems) throws V1Exception, MalformedURLException {
IAttributeDefinition buildRunChangeSetsAttrDef = buildRun.getAssetType().getAttributeDefinition("ChangeSets");
for (Asset changeSet : changeSets) {
IAttributeDefinition changeSetNameAttrDef = changeSet.getAssetType().getAttributeDefinition("Name");
IAttributeDefinition changeSetPrimaryWorkitemsAttrDef = changeSet.getAssetType().getAttributeDefinition("PrimaryWorkitems");
buildRun.addAttributeValue(buildRunChangeSetsAttrDef, changeSet.getOid());
logger.println("VersionOne: Added changeset " + changeSet.getAttribute(changeSetNameAttrDef).getValue());
for (Asset workitem : workitems) {
IAttributeDefinition workItemIsClosedAttrDef = workitem.getAssetType().getAttributeDefinition("IsClosed");
IAttributeDefinition workItemCompletedInBuildRunsAttrDef = workitem.getAssetType().getAttributeDefinition("CompletedInBuildRuns");
if (Boolean.parseBoolean(workitem.getAttribute(workItemIsClosedAttrDef).getValue().toString())) { | logger.println("VersionOne: " + MessagesRes.workitemClosedCannotAttachData(getWorkitemDisplayString(workitem))); |
versionone/VersionOne.Integration.Jenkins | src/main/java/com/versionone/jenkins/VcsModificationWrapperFactory.java | // Path: src/main/java/com/versionone/integration/ciCommon/VcsModification.java
// public interface VcsModification {
//
// String getUserName();
//
// String getComment();
//
// /**
// * Get modification date.
// *
// * @return Date and time the modification occur. Or null.
// */
// Date getDate();
//
// String getId();
// }
| import hudson.scm.ChangeLogSet;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import com.versionone.integration.ciCommon.VcsModification; | "com.versionone.jenkins.GitModification");
fillSupportedMappings();
}
private void fillSupportedMappings() {
for(Map.Entry<String, String> entry : classNameMappings.entrySet()) {
try {
Class logEntryClass = Class.forName(entry.getKey());
Class wrapperClass = Class.forName(entry.getValue());
mappings.put(logEntryClass, wrapperClass);
} catch(ClassNotFoundException e) {
// do nothing, it is an unsupported VCS changeset type
e.printStackTrace();
}
}
}
public static VcsModificationWrapperFactory getInstance() {
if(instance == null) {
instance = new VcsModificationWrapperFactory();
}
return instance;
}
public boolean isSupported(ChangeLogSet.Entry modification) {
return modification != null && mappings.containsKey(modification.getClass());
}
| // Path: src/main/java/com/versionone/integration/ciCommon/VcsModification.java
// public interface VcsModification {
//
// String getUserName();
//
// String getComment();
//
// /**
// * Get modification date.
// *
// * @return Date and time the modification occur. Or null.
// */
// Date getDate();
//
// String getId();
// }
// Path: src/main/java/com/versionone/jenkins/VcsModificationWrapperFactory.java
import hudson.scm.ChangeLogSet;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import com.versionone.integration.ciCommon.VcsModification;
"com.versionone.jenkins.GitModification");
fillSupportedMappings();
}
private void fillSupportedMappings() {
for(Map.Entry<String, String> entry : classNameMappings.entrySet()) {
try {
Class logEntryClass = Class.forName(entry.getKey());
Class wrapperClass = Class.forName(entry.getValue());
mappings.put(logEntryClass, wrapperClass);
} catch(ClassNotFoundException e) {
// do nothing, it is an unsupported VCS changeset type
e.printStackTrace();
}
}
}
public static VcsModificationWrapperFactory getInstance() {
if(instance == null) {
instance = new VcsModificationWrapperFactory();
}
return instance;
}
public boolean isSupported(ChangeLogSet.Entry modification) {
return modification != null && mappings.containsKey(modification.getClass());
}
| public VcsModification createWrapper(ChangeLogSet.Entry modification) { |
versionone/VersionOne.Integration.Jenkins | src/test/java/com/versionone/hudson/GitModificationTest.java | // Path: src/main/java/com/versionone/jenkins/GitModification.java
// public class GitModification implements VcsModification {
// private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
// private GitChangeSet _entry;
//
// public GitModification(GitChangeSet entry) {
// _entry = entry;
// }
//
// public String getComment() {
// return _entry.getComment();
// }
//
// public Date getDate() {
// try {
// return fmt.parse(_entry.getDate());
// } catch (ParseException ex) {
// ex.printStackTrace();
// return Calendar.getInstance().getTime();
// }
// }
//
// public String getId() {
// return _entry.getId();
// }
//
// public String getUserName() {
// return _entry.getAuthorName();
// }
//
// }
| import hudson.plugins.git.GitChangeSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import junit.framework.Assert;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import com.versionone.jenkins.GitModification; | package com.versionone.hudson;
public class GitModificationTest {
private Mockery mockery = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.ENGLISH);
@Test
public void getDate() throws ParseException {
final String strDate = "1979-12-05 23:20:00 +0300";
| // Path: src/main/java/com/versionone/jenkins/GitModification.java
// public class GitModification implements VcsModification {
// private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
// private GitChangeSet _entry;
//
// public GitModification(GitChangeSet entry) {
// _entry = entry;
// }
//
// public String getComment() {
// return _entry.getComment();
// }
//
// public Date getDate() {
// try {
// return fmt.parse(_entry.getDate());
// } catch (ParseException ex) {
// ex.printStackTrace();
// return Calendar.getInstance().getTime();
// }
// }
//
// public String getId() {
// return _entry.getId();
// }
//
// public String getUserName() {
// return _entry.getAuthorName();
// }
//
// }
// Path: src/test/java/com/versionone/hudson/GitModificationTest.java
import hudson.plugins.git.GitChangeSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import junit.framework.Assert;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import com.versionone.jenkins.GitModification;
package com.versionone.hudson;
public class GitModificationTest {
private Mockery mockery = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.ENGLISH);
@Test
public void getDate() throws ParseException {
final String strDate = "1979-12-05 23:20:00 +0300";
| GitModification modification = CreateGitModification(strDate); |
maxant/genericconnector | demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
| import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
| /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
/**
* An example of how to use Bitronix.
*/
public class Main {
public static void main(String[] args) throws Exception {
System.setProperty("log4j.debug", "true");
//load up resources registered via bitronix
ResourceLoader rl = new ResourceLoader();
rl.init();
//warning: this instance must be thread safe and serializable. build the web service client on the fly!
| // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
// Path: demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
/**
* An example of how to use Bitronix.
*/
public class Main {
public static void main(String[] args) throws Exception {
System.setProperty("log4j.debug", "true");
//load up resources registered via bitronix
ResourceLoader rl = new ResourceLoader();
rl.init();
//warning: this instance must be thread safe and serializable. build the web service client on the fly!
| CommitRollbackCallback bookingCommitRollbackCallback = new CommitRollbackCallback() {
|
maxant/genericconnector | demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
| import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
| private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
getService().cancelTickets(txid);
}
@Override
public void commit(String txid) throws Exception {
getService().bookTickets(txid);
}
private BookingSystem getService() {
return new BookingSystemWebServiceService().getBookingSystemPort();
}
};
//warning: this instance must be thread safe and serializable. build the web service client on the fly!
CommitRollbackCallback letterCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
//compensate by cancelling the letter
LetterWriter service = new LetterWebServiceService().getLetterWriterPort(); //or take from a pool if you want to
service.cancelLetter(txid);
}
@Override
public void commit(String txid) throws Exception {
System.out.println("nothing to do, this service autocommits.");
}
};
{//once per microservice that you want to use - do this when app starts, so that recovery can function immediately
| // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
// Path: demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
getService().cancelTickets(txid);
}
@Override
public void commit(String txid) throws Exception {
getService().bookTickets(txid);
}
private BookingSystem getService() {
return new BookingSystemWebServiceService().getBookingSystemPort();
}
};
//warning: this instance must be thread safe and serializable. build the web service client on the fly!
CommitRollbackCallback letterCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
//compensate by cancelling the letter
LetterWriter service = new LetterWebServiceService().getLetterWriterPort(); //or take from a pool if you want to
service.cancelLetter(txid);
}
@Override
public void commit(String txid) throws Exception {
System.out.println("nothing to do, this service autocommits.");
}
};
{//once per microservice that you want to use - do this when app starts, so that recovery can function immediately
| TransactionConfigurator.setup("xa/bookingService", bookingCommitRollbackCallback);
|
maxant/genericconnector | demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
| import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
| CommitRollbackCallback letterCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
//compensate by cancelling the letter
LetterWriter service = new LetterWebServiceService().getLetterWriterPort(); //or take from a pool if you want to
service.cancelLetter(txid);
}
@Override
public void commit(String txid) throws Exception {
System.out.println("nothing to do, this service autocommits.");
}
};
{//once per microservice that you want to use - do this when app starts, so that recovery can function immediately
TransactionConfigurator.setup("xa/bookingService", bookingCommitRollbackCallback);
TransactionConfigurator.setup("xa/letterService", letterCommitRollbackCallback);
}
String username = "ant";
BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
tm.begin();
BitronixTransaction tx = tm.getCurrentTransaction();
try{//start of service implementation:
Context ctx = new BitronixContext();
String msResponse = null;
//call microservice #1
| // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
// Path: demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
CommitRollbackCallback letterCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
//compensate by cancelling the letter
LetterWriter service = new LetterWebServiceService().getLetterWriterPort(); //or take from a pool if you want to
service.cancelLetter(txid);
}
@Override
public void commit(String txid) throws Exception {
System.out.println("nothing to do, this service autocommits.");
}
};
{//once per microservice that you want to use - do this when app starts, so that recovery can function immediately
TransactionConfigurator.setup("xa/bookingService", bookingCommitRollbackCallback);
TransactionConfigurator.setup("xa/letterService", letterCommitRollbackCallback);
}
String username = "ant";
BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
tm.begin();
BitronixTransaction tx = tm.getCurrentTransaction();
try{//start of service implementation:
Context ctx = new BitronixContext();
String msResponse = null;
//call microservice #1
| BasicTransactionAssistanceFactory bookingMicroserviceFactory = (BasicTransactionAssistanceFactory) ctx.lookup("xa/bookingService");
|
maxant/genericconnector | demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
| import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
| private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
//compensate by cancelling the letter
LetterWriter service = new LetterWebServiceService().getLetterWriterPort(); //or take from a pool if you want to
service.cancelLetter(txid);
}
@Override
public void commit(String txid) throws Exception {
System.out.println("nothing to do, this service autocommits.");
}
};
{//once per microservice that you want to use - do this when app starts, so that recovery can function immediately
TransactionConfigurator.setup("xa/bookingService", bookingCommitRollbackCallback);
TransactionConfigurator.setup("xa/letterService", letterCommitRollbackCallback);
}
String username = "ant";
BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
tm.begin();
BitronixTransaction tx = tm.getCurrentTransaction();
try{//start of service implementation:
Context ctx = new BitronixContext();
String msResponse = null;
//call microservice #1
BasicTransactionAssistanceFactory bookingMicroserviceFactory = (BasicTransactionAssistanceFactory) ctx.lookup("xa/bookingService");
| // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
// Path: demo/genericconnector-demo-standalone-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Main.java
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.naming.Context;
import javax.sql.DataSource;
import bitronix.tm.BitronixTransaction;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.jndi.BitronixContext;
import bitronix.tm.resource.ResourceLoader;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
//compensate by cancelling the letter
LetterWriter service = new LetterWebServiceService().getLetterWriterPort(); //or take from a pool if you want to
service.cancelLetter(txid);
}
@Override
public void commit(String txid) throws Exception {
System.out.println("nothing to do, this service autocommits.");
}
};
{//once per microservice that you want to use - do this when app starts, so that recovery can function immediately
TransactionConfigurator.setup("xa/bookingService", bookingCommitRollbackCallback);
TransactionConfigurator.setup("xa/letterService", letterCommitRollbackCallback);
}
String username = "ant";
BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager();
tm.begin();
BitronixTransaction tx = tm.getCurrentTransaction();
try{//start of service implementation:
Context ctx = new BitronixContext();
String msResponse = null;
//call microservice #1
BasicTransactionAssistanceFactory bookingMicroserviceFactory = (BasicTransactionAssistanceFactory) ctx.lookup("xa/bookingService");
| try(TransactionAssistant transactionAssistant = bookingMicroserviceFactory.getTransactionAssistant()){
|
maxant/genericconnector | connector/genericconnector-impl/src/main/java/ch/maxant/generic_jca_adapter/ManagedTransactionAssistance.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
| import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.resource.NotSupportedException;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionEvent;
import javax.resource.spi.ConnectionEventListener;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.LocalTransaction;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionMetaData;
import javax.security.auth.Subject;
import javax.transaction.xa.XAResource;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
| /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter;
/**
* There is an assumption here that instances of this class are not thread safe
* in that they can only be used one at a time. EXECUTE-COMMIT or EXECUTE-ROLLBACK.
* The class contains logic to ensure this.
*/
public class ManagedTransactionAssistance implements ManagedConnection, Serializable {
private static final long serialVersionUID = 1L;
private final Logger log = Logger.getLogger(this.getClass().getName());
private PrintWriter logWriter;
private List<ConnectionEventListener> listeners = new ArrayList<ConnectionEventListener>();
private TransactionAssistant connection;
/** was the call to EXECUTE successful? (tristate, null means ready for new connection) */
private Boolean executeWasSuccessful;
/** the current transaction ID */
private String currentTxId;
| // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
// Path: connector/genericconnector-impl/src/main/java/ch/maxant/generic_jca_adapter/ManagedTransactionAssistance.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.resource.NotSupportedException;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionEvent;
import javax.resource.spi.ConnectionEventListener;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.LocalTransaction;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionMetaData;
import javax.security.auth.Subject;
import javax.transaction.xa.XAResource;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter;
/**
* There is an assumption here that instances of this class are not thread safe
* in that they can only be used one at a time. EXECUTE-COMMIT or EXECUTE-ROLLBACK.
* The class contains logic to ensure this.
*/
public class ManagedTransactionAssistance implements ManagedConnection, Serializable {
private static final long serialVersionUID = 1L;
private final Logger log = Logger.getLogger(this.getClass().getName());
private PrintWriter logWriter;
private List<ConnectionEventListener> listeners = new ArrayList<ConnectionEventListener>();
private TransactionAssistant connection;
/** was the call to EXECUTE successful? (tristate, null means ready for new connection) */
private Boolean executeWasSuccessful;
/** the current transaction ID */
private String currentTxId;
| private CommitRollbackRecoveryCallback commitRollbackRecoveryCallback;
|
maxant/genericconnector | connector/genericconnector-impl/src/main/java/ch/maxant/generic_jca_adapter/ManagedTransactionAssistanceFactory.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
| import javax.resource.spi.ResourceAdapter;
import javax.resource.spi.ResourceAdapterAssociation;
import javax.security.auth.Subject;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.resource.ResourceException;
import javax.resource.spi.ConfigProperty;
import javax.resource.spi.ConnectionDefinition;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
| log.log(Level.SEVERE, msg);
throw new RuntimeException(msg);
}else{
log.log(Level.INFO, "Transaction state for '" + id + "' will be written in new directory '" + recoveryStatePersistenceDirectoryFile.getAbsolutePath() + "'");
}
}else{
log.log(Level.INFO, "Transaction state for '" + id + "' will be written in existing directory '" + recoveryStatePersistenceDirectoryFile.getAbsolutePath() + "'");
}
}
}else{
log.log(Level.WARNING, "The '" + id + "' adapter will NOT track transaction state internally. The associated EIS MUST be able to return incomplete transactions and you MUST provide an implementation of CommitRollbackRecoveryCallback#getTransactionsInNeedOfRecovery()!");
}
initialised = true;
}
@Override
public Object createConnectionFactory() throws ResourceException {
lazyInit();
throw new ResourceException("This resource adapter doesn't support non-managed environments");
}
@Override
public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException {
lazyInit();
return new TransactionAssistanceFactoryImpl(this, cxManager);
}
@Override
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
lazyInit();
| // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
// Path: connector/genericconnector-impl/src/main/java/ch/maxant/generic_jca_adapter/ManagedTransactionAssistanceFactory.java
import javax.resource.spi.ResourceAdapter;
import javax.resource.spi.ResourceAdapterAssociation;
import javax.security.auth.Subject;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.resource.ResourceException;
import javax.resource.spi.ConfigProperty;
import javax.resource.spi.ConnectionDefinition;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
log.log(Level.SEVERE, msg);
throw new RuntimeException(msg);
}else{
log.log(Level.INFO, "Transaction state for '" + id + "' will be written in new directory '" + recoveryStatePersistenceDirectoryFile.getAbsolutePath() + "'");
}
}else{
log.log(Level.INFO, "Transaction state for '" + id + "' will be written in existing directory '" + recoveryStatePersistenceDirectoryFile.getAbsolutePath() + "'");
}
}
}else{
log.log(Level.WARNING, "The '" + id + "' adapter will NOT track transaction state internally. The associated EIS MUST be able to return incomplete transactions and you MUST provide an implementation of CommitRollbackRecoveryCallback#getTransactionsInNeedOfRecovery()!");
}
initialised = true;
}
@Override
public Object createConnectionFactory() throws ResourceException {
lazyInit();
throw new ResourceException("This resource adapter doesn't support non-managed environments");
}
@Override
public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException {
lazyInit();
return new TransactionAssistanceFactoryImpl(this, cxManager);
}
@Override
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
lazyInit();
| CommitRollbackRecoveryCallback callback = ((GenericResourceAdapter)this.resourceAdapter).getCommitRollbackRecoveryCallback(id);
|
maxant/genericconnector | demo/genericconnector-demo-springboot-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java | // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
| import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() {
{//setup microservice that we want to call within a transaction | // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
// Path: demo/genericconnector-demo-springboot-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() {
{//setup microservice that we want to call within a transaction | CommitRollbackCallback bookingCommitRollbackCallback = new CommitRollbackCallback() { |
maxant/genericconnector | demo/genericconnector-demo-springboot-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java | // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
| import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() {
{//setup microservice that we want to call within a transaction
CommitRollbackCallback bookingCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().cancelTickets(txid);
}
@Override
public void commit(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().bookTickets(txid);
}
}; | // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
// Path: demo/genericconnector-demo-springboot-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() {
{//setup microservice that we want to call within a transaction
CommitRollbackCallback bookingCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().cancelTickets(txid);
}
@Override
public void commit(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().bookTickets(txid);
}
}; | TransactionConfigurator.setup("xa/bookingService", bookingCommitRollbackCallback); |
maxant/genericconnector | connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/GenericResourceAdapterTest.java | // Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static class Transaction {
// private TransactionState transactionState = TransactionState.RUNNING;
// private ArrayList<XAResource> xaResources = new ArrayList<XAResource>();
// private Xid xid = new XidImpl("gtid".getBytes(), transactionNumber.getAndIncrement(), "bq".getBytes());
// private boolean shouldRollback;
// public List<Exception> exceptions = new ArrayList<Exception>();
//
// public TransactionState getTransactionState() {
// return transactionState;
// }
// public boolean isShouldRollback() {
// return shouldRollback;
// }
// public String getTxid() {
// return XidImpl.asString(xid);
// }
// public List<Exception> getExceptions() {
// return exceptions;
// }
// }
//
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static enum TransactionState {
// RUNNING, PREPARING, COMMITTING, ROLLINGBACK;
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
| import org.junit.Test;
import ch.maxant.generic_jca_adapter.MiniContainer.Transaction;
import ch.maxant.generic_jca_adapter.MiniContainer.TransactionState;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.BeforeClass; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter;
public class GenericResourceAdapterTest {
@BeforeClass
public static void init(){
for(File f : new File(System.getProperty("java.io.tmpdir")).listFiles()){
if(f.getName().startsWith("exec") && f.getName().endsWith(".txt")){
//perhaps its left over from a broken test - be nice to the person running this test :-)
f.delete();
}
}
}
@Test
public void testCannotRegisterTwice() {
GenericResourceAdapter adapter = new GenericResourceAdapter();
| // Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static class Transaction {
// private TransactionState transactionState = TransactionState.RUNNING;
// private ArrayList<XAResource> xaResources = new ArrayList<XAResource>();
// private Xid xid = new XidImpl("gtid".getBytes(), transactionNumber.getAndIncrement(), "bq".getBytes());
// private boolean shouldRollback;
// public List<Exception> exceptions = new ArrayList<Exception>();
//
// public TransactionState getTransactionState() {
// return transactionState;
// }
// public boolean isShouldRollback() {
// return shouldRollback;
// }
// public String getTxid() {
// return XidImpl.asString(xid);
// }
// public List<Exception> getExceptions() {
// return exceptions;
// }
// }
//
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static enum TransactionState {
// RUNNING, PREPARING, COMMITTING, ROLLINGBACK;
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/GenericResourceAdapterTest.java
import org.junit.Test;
import ch.maxant.generic_jca_adapter.MiniContainer.Transaction;
import ch.maxant.generic_jca_adapter.MiniContainer.TransactionState;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.BeforeClass;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter;
public class GenericResourceAdapterTest {
@BeforeClass
public static void init(){
for(File f : new File(System.getProperty("java.io.tmpdir")).listFiles()){
if(f.getName().startsWith("exec") && f.getName().endsWith(".txt")){
//perhaps its left over from a broken test - be nice to the person running this test :-)
f.delete();
}
}
}
@Test
public void testCannotRegisterTwice() {
GenericResourceAdapter adapter = new GenericResourceAdapter();
| CommitRollbackRecoveryCallback commitRollbackRecoveryCallback = new CommitRollbackRecoveryCallback(){ |
maxant/genericconnector | connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/GenericResourceAdapterTest.java | // Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static class Transaction {
// private TransactionState transactionState = TransactionState.RUNNING;
// private ArrayList<XAResource> xaResources = new ArrayList<XAResource>();
// private Xid xid = new XidImpl("gtid".getBytes(), transactionNumber.getAndIncrement(), "bq".getBytes());
// private boolean shouldRollback;
// public List<Exception> exceptions = new ArrayList<Exception>();
//
// public TransactionState getTransactionState() {
// return transactionState;
// }
// public boolean isShouldRollback() {
// return shouldRollback;
// }
// public String getTxid() {
// return XidImpl.asString(xid);
// }
// public List<Exception> getExceptions() {
// return exceptions;
// }
// }
//
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static enum TransactionState {
// RUNNING, PREPARING, COMMITTING, ROLLINGBACK;
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
| import org.junit.Test;
import ch.maxant.generic_jca_adapter.MiniContainer.Transaction;
import ch.maxant.generic_jca_adapter.MiniContainer.TransactionState;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.BeforeClass; |
//injection
TransactionAssistanceFactory bookingFactory = container.lookupAdapter();
//method start - no transaction!!
//business code
try{
bookingFactory.getTransactionAssistant();
fail("no exception");
}catch(IllegalStateException e){
assertEquals("please start a transaction before opening a connection", e.getMessage());
}
}
@Test
public void testInContainer_Commit() throws Exception {
MiniContainer container = new MiniContainer();
//injection
TransactionAssistanceFactory bookingFactory = container.lookupAdapter();
//setup commit/rollback caller
final AtomicInteger commitCalled = new AtomicInteger();
final AtomicInteger rollbackCalled = new AtomicInteger();
final AtomicInteger recoveryCalled = new AtomicInteger();
registerCallbacks(bookingFactory, commitCalled, rollbackCalled, recoveryCalled, null, false);
//method start | // Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static class Transaction {
// private TransactionState transactionState = TransactionState.RUNNING;
// private ArrayList<XAResource> xaResources = new ArrayList<XAResource>();
// private Xid xid = new XidImpl("gtid".getBytes(), transactionNumber.getAndIncrement(), "bq".getBytes());
// private boolean shouldRollback;
// public List<Exception> exceptions = new ArrayList<Exception>();
//
// public TransactionState getTransactionState() {
// return transactionState;
// }
// public boolean isShouldRollback() {
// return shouldRollback;
// }
// public String getTxid() {
// return XidImpl.asString(xid);
// }
// public List<Exception> getExceptions() {
// return exceptions;
// }
// }
//
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static enum TransactionState {
// RUNNING, PREPARING, COMMITTING, ROLLINGBACK;
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/GenericResourceAdapterTest.java
import org.junit.Test;
import ch.maxant.generic_jca_adapter.MiniContainer.Transaction;
import ch.maxant.generic_jca_adapter.MiniContainer.TransactionState;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.BeforeClass;
//injection
TransactionAssistanceFactory bookingFactory = container.lookupAdapter();
//method start - no transaction!!
//business code
try{
bookingFactory.getTransactionAssistant();
fail("no exception");
}catch(IllegalStateException e){
assertEquals("please start a transaction before opening a connection", e.getMessage());
}
}
@Test
public void testInContainer_Commit() throws Exception {
MiniContainer container = new MiniContainer();
//injection
TransactionAssistanceFactory bookingFactory = container.lookupAdapter();
//setup commit/rollback caller
final AtomicInteger commitCalled = new AtomicInteger();
final AtomicInteger rollbackCalled = new AtomicInteger();
final AtomicInteger recoveryCalled = new AtomicInteger();
registerCallbacks(bookingFactory, commitCalled, rollbackCalled, recoveryCalled, null, false);
//method start | final Transaction tx = container.startTransaction(); |
maxant/genericconnector | connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/GenericResourceAdapterTest.java | // Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static class Transaction {
// private TransactionState transactionState = TransactionState.RUNNING;
// private ArrayList<XAResource> xaResources = new ArrayList<XAResource>();
// private Xid xid = new XidImpl("gtid".getBytes(), transactionNumber.getAndIncrement(), "bq".getBytes());
// private boolean shouldRollback;
// public List<Exception> exceptions = new ArrayList<Exception>();
//
// public TransactionState getTransactionState() {
// return transactionState;
// }
// public boolean isShouldRollback() {
// return shouldRollback;
// }
// public String getTxid() {
// return XidImpl.asString(xid);
// }
// public List<Exception> getExceptions() {
// return exceptions;
// }
// }
//
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static enum TransactionState {
// RUNNING, PREPARING, COMMITTING, ROLLINGBACK;
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
| import org.junit.Test;
import ch.maxant.generic_jca_adapter.MiniContainer.Transaction;
import ch.maxant.generic_jca_adapter.MiniContainer.TransactionState;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.BeforeClass; | public void testInContainer_Commit() throws Exception {
MiniContainer container = new MiniContainer();
//injection
TransactionAssistanceFactory bookingFactory = container.lookupAdapter();
//setup commit/rollback caller
final AtomicInteger commitCalled = new AtomicInteger();
final AtomicInteger rollbackCalled = new AtomicInteger();
final AtomicInteger recoveryCalled = new AtomicInteger();
registerCallbacks(bookingFactory, commitCalled, rollbackCalled, recoveryCalled, null, false);
//method start
final Transaction tx = container.startTransaction();
//business code
TransactionAssistant bookingTransactionAssistant = bookingFactory.getTransactionAssistant();
String bookingResponse = bookingTransactionAssistant.executeInActiveTransaction(new ExecuteCallback<String>() {
@Override
public String execute(String txid) throws Exception {
return "1";
}
});
bookingTransactionAssistant.close();
//method exit
container.finishTransaction();
//assertions | // Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static class Transaction {
// private TransactionState transactionState = TransactionState.RUNNING;
// private ArrayList<XAResource> xaResources = new ArrayList<XAResource>();
// private Xid xid = new XidImpl("gtid".getBytes(), transactionNumber.getAndIncrement(), "bq".getBytes());
// private boolean shouldRollback;
// public List<Exception> exceptions = new ArrayList<Exception>();
//
// public TransactionState getTransactionState() {
// return transactionState;
// }
// public boolean isShouldRollback() {
// return shouldRollback;
// }
// public String getTxid() {
// return XidImpl.asString(xid);
// }
// public List<Exception> getExceptions() {
// return exceptions;
// }
// }
//
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/MiniContainer.java
// public static enum TransactionState {
// RUNNING, PREPARING, COMMITTING, ROLLINGBACK;
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistanceFactory.java
// public static interface CommitRollbackRecoveryCallback extends CommitRollbackCallback {
//
// /** The container will call this function during
// * recovery which should call the EIS and must return
// * transaction IDs which are known to be incomplete (not
// * yet committed or rolled back). Note that if the
// * Resource Adapter is configured to manage transaction
// * state internally, then this method will not
// * be called and can have an empty implementation. */
// String[] getTransactionsInNeedOfRecovery();
//
// /** Builder enabling use of Java 8 SAMs */
// public static class Builder {
// private CommitRollbackFunction commit;
// private CommitRollbackFunction rollback;
// private RecoveryFunction recovery;
// public Builder withCommit(CommitRollbackFunction commit){
// this.commit = commit;
// return this;
// }
// public Builder withRollback(CommitRollbackFunction rollback){
// this.rollback = rollback;
// return this;
// }
// public Builder withRecovery(RecoveryFunction recovery){
// this.recovery = recovery;
// return this;
// }
// public CommitRollbackRecoveryCallback build(){
// Objects.requireNonNull(commit, "Please call withCommit(...)");
// Objects.requireNonNull(rollback, "Please call withRollback(...)");
// //recovery is optional, since you can configure adapter to handle state internally
//
// return new CommitRollbackRecoveryCallback(){
// private static final long serialVersionUID = 1L;
// @Override
// public void commit(String txid) throws Exception {
// commit.apply(txid);
// }
// @Override
// public void rollback(String txid) throws Exception {
// rollback.apply(txid);
// }
// @Override
// public String[] getTransactionsInNeedOfRecovery() {
// if(recovery == null){
// return new String[0];
// }else{
// return recovery.getTransactionsInNeedOfRecovery();
// }
// }
// };
// }
//
// public static interface RecoveryFunction {
// String[] getTransactionsInNeedOfRecovery();
// }
//
// public static interface CommitRollbackFunction {
// void apply(String txid) throws Exception;
// }
// }
// }
// Path: connector/genericconnector-impl/src/test/java/ch/maxant/generic_jca_adapter/GenericResourceAdapterTest.java
import org.junit.Test;
import ch.maxant.generic_jca_adapter.MiniContainer.Transaction;
import ch.maxant.generic_jca_adapter.MiniContainer.TransactionState;
import ch.maxant.generic_jca_adapter.TransactionAssistanceFactory.CommitRollbackRecoveryCallback;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.BeforeClass;
public void testInContainer_Commit() throws Exception {
MiniContainer container = new MiniContainer();
//injection
TransactionAssistanceFactory bookingFactory = container.lookupAdapter();
//setup commit/rollback caller
final AtomicInteger commitCalled = new AtomicInteger();
final AtomicInteger rollbackCalled = new AtomicInteger();
final AtomicInteger recoveryCalled = new AtomicInteger();
registerCallbacks(bookingFactory, commitCalled, rollbackCalled, recoveryCalled, null, false);
//method start
final Transaction tx = container.startTransaction();
//business code
TransactionAssistant bookingTransactionAssistant = bookingFactory.getTransactionAssistant();
String bookingResponse = bookingTransactionAssistant.executeInActiveTransaction(new ExecuteCallback<String>() {
@Override
public String execute(String txid) throws Exception {
return "1";
}
});
bookingTransactionAssistant.close();
//method exit
container.finishTransaction();
//assertions | assertEquals(TransactionState.COMMITTING, tx.getTransactionState()); |
maxant/genericconnector | demo/genericconnector-demo-springboot-common/src/main/java/ch/maxant/generic_jca_adapter/demo/AppService.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
| import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
based on https://raw.githubusercontent.com/spring-projects/spring-boot/master/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/AccountService.java
*/
package ch.maxant.generic_jca_adapter.demo;
@Service
@Transactional
public class AppService {
@Autowired
private AppRepository appRepository;
@Autowired @Qualifier("xa/bookingService") | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
// Path: demo/genericconnector-demo-springboot-common/src/main/java/ch/maxant/generic_jca_adapter/demo/AppService.java
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
based on https://raw.githubusercontent.com/spring-projects/spring-boot/master/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/AccountService.java
*/
package ch.maxant.generic_jca_adapter.demo;
@Service
@Transactional
public class AppService {
@Autowired
private AppRepository appRepository;
@Autowired @Qualifier("xa/bookingService") | BasicTransactionAssistanceFactory bookingServiceFactory; |
maxant/genericconnector | demo/genericconnector-demo-springboot-common/src/main/java/ch/maxant/generic_jca_adapter/demo/AppService.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
| import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
based on https://raw.githubusercontent.com/spring-projects/spring-boot/master/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/AccountService.java
*/
package ch.maxant.generic_jca_adapter.demo;
@Service
@Transactional
public class AppService {
@Autowired
private AppRepository appRepository;
@Autowired @Qualifier("xa/bookingService")
BasicTransactionAssistanceFactory bookingServiceFactory;
@Autowired @Qualifier("xa/letterService")
BasicTransactionAssistanceFactory letterServiceFactory;
public String doSomethingWithAGlobalTransactionAndARemoteMicroservice(String username) throws Exception {
{//write to local database
Account acct = new Account();
acct.setName(username);
acct.setId(5000);
//TODO not working in Atomikos with Mysql:
// this.appRepository.save(acct);
}
String msResponse = null;
//call microservice #1 | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionAssistant.java
// public interface TransactionAssistant extends AutoCloseable {
//
// /** Submit some work (a function) to be bound into the
// * currently active transaction. */
// <O> O executeInActiveTransaction(ExecuteCallback<O> tc) throws Exception;
//
// /** Call before completing the transaction in order
// * to free up resources used by the app server. */
// @Override
// void close();
// }
// Path: demo/genericconnector-demo-springboot-common/src/main/java/ch/maxant/generic_jca_adapter/demo/AppService.java
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.TransactionAssistant;
import ch.maxant.jca_demo.bookingsystem.BookingSystem;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWriter;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
based on https://raw.githubusercontent.com/spring-projects/spring-boot/master/spring-boot-samples/spring-boot-sample-jta-bitronix/src/main/java/sample/bitronix/AccountService.java
*/
package ch.maxant.generic_jca_adapter.demo;
@Service
@Transactional
public class AppService {
@Autowired
private AppRepository appRepository;
@Autowired @Qualifier("xa/bookingService")
BasicTransactionAssistanceFactory bookingServiceFactory;
@Autowired @Qualifier("xa/letterService")
BasicTransactionAssistanceFactory letterServiceFactory;
public String doSomethingWithAGlobalTransactionAndARemoteMicroservice(String username) throws Exception {
{//write to local database
Account acct = new Account();
acct.setName(username);
acct.setId(5000);
//TODO not working in Atomikos with Mysql:
// this.appRepository.save(acct);
}
String msResponse = null;
//call microservice #1 | try(TransactionAssistant transactionAssistant = bookingServiceFactory.getTransactionAssistant()){ |
maxant/genericconnector | demo/genericconnector-demo-springboot-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Config.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
| import javax.naming.Context;
import javax.naming.NamingException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import bitronix.tm.jndi.BitronixContext;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
@Configuration
public class Config {
@Bean(name="xa/bookingService") | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
// Path: demo/genericconnector-demo-springboot-bitronix/src/main/java/ch/maxant/generic_jca_adapter/demo/Config.java
import javax.naming.Context;
import javax.naming.NamingException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import bitronix.tm.jndi.BitronixContext;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
@Configuration
public class Config {
@Bean(name="xa/bookingService") | public BasicTransactionAssistanceFactory bookingSystemFactory() throws NamingException { |
maxant/genericconnector | demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java | // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
| import javax.naming.NamingException;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() throws NamingException {
{//setup microservices that we want to call within a transaction
| // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
// Path: demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java
import javax.naming.NamingException;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() throws NamingException {
{//setup microservices that we want to call within a transaction
| CommitRollbackCallback bookingCommitRollbackCallback = new CommitRollbackCallback() { |
maxant/genericconnector | demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java | // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
| import javax.naming.NamingException;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() throws NamingException {
{//setup microservices that we want to call within a transaction
CommitRollbackCallback bookingCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().cancelTickets(txid);
}
@Override
public void commit(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().bookTickets(txid);
}
}; | // Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/TransactionConfigurator.java
// public final class TransactionConfigurator {
//
// private TransactionConfigurator() {}
//
// private static Map<String, RecoverableMSResource> resources = new HashMap<String, RecoverableMSResource>();
//
// /** one time configuration required for setting up a microservice in a transactional environment. */
// public static void setup(String jndiName, final CommitRollbackCallback commitRollbackCallback){
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// RecoverableMSResource resource = new RecoverableMSResource(ms);
// resources.put(jndiName, resource);
// utsi.registerResource(resource);
// }
//
// /** when your application shutsdown, you should unregister all services that were setup using {@link #setup(String, CommitRollbackHandler)}
// * or {@link #setup(String, CommitRollbackHandler, long, File)} */
// public static void unregisterMicroserviceResourceFactory(String name) {
// UserTransactionServiceImp utsi = new UserTransactionServiceImp();
// utsi.removeResource(resources.remove(name));
// }
//
// /** @return the {@link CommitRollbackCallback} registered during setup, or null, if none found (eg never registered, or unregistered). */
// static CommitRollbackCallback getCommitRollbackCallback(String jndiName){
// RecoverableMSResource rr = resources.get(jndiName);
// if(rr != null){
// return rr.getMicroserviceResource().getUnderlyingConnection();
// }
// return null;
// }
//
// }
//
// Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/CommitRollbackCallback.java
// public interface CommitRollbackCallback extends Serializable {
//
// /** The container will call this function
// * to commit a transaction that was successful.
// * The implementation of this method should
// * call the EIS in order to commit
// * the transaction. */
// void commit(String txid) throws Exception;
//
// /** The container will call this function
// * to rollback an unsuccessful transaction.
// * The implementation of this method should
// * call the EIS in order to rollback
// * the transaction. */
// void rollback(String txid) throws Exception;
//
// }
// Path: demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/BaseMain.java
import javax.naming.NamingException;
import ch.maxant.generic_jca_adapter.TransactionConfigurator;
import ch.maxant.generic_jca_adapter.CommitRollbackCallback;
import ch.maxant.jca_demo.bookingsystem.BookingSystemWebServiceService;
import ch.maxant.jca_demo.letterwriter.LetterWebServiceService;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
public abstract class BaseMain {
protected static void setupCommitRollbackHandlerForMicroserviceWhichIsCalled() throws NamingException {
{//setup microservices that we want to call within a transaction
CommitRollbackCallback bookingCommitRollbackCallback = new CommitRollbackCallback() {
private static final long serialVersionUID = 1L;
@Override
public void rollback(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().cancelTickets(txid);
}
@Override
public void commit(String txid) throws Exception {
new BookingSystemWebServiceService().getBookingSystemPort().bookTickets(txid);
}
}; | TransactionConfigurator.setup("xa/bookingService", bookingCommitRollbackCallback); |
maxant/genericconnector | demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/Config.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactoryImpl.java
// public class BasicTransactionAssistanceFactoryImpl implements BasicTransactionAssistanceFactory {
//
// private String jndiName;
//
// /**
// * @param jndiName the name of the resource that this factory represents, eg the name of the microservice which this factory is in charge of
// * committing, rolling back and recovering.
// */
// public BasicTransactionAssistanceFactoryImpl(String jndiName) {
// this.jndiName = jndiName;
// }
//
// /** before calling this method, please ensure you have called {@link TransactionConfigurator#setup(String, CommitRollbackCallback)} */
// @Override
// public TransactionAssistant getTransactionAssistant() throws ResourceException {
// //enlist a new resource into the transaction. it will be delisted, when its closed.
// final CommitRollbackCallback commitRollbackCallback = TransactionConfigurator.getCommitRollbackCallback(jndiName);
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// UserTransactionManager utm = getTM();
// try {
// if(utm.getStatus() == Status.STATUS_NO_TRANSACTION){
// throw new ResourceException("no transaction found. please start one before getting the transaction assistant. status was: " + utm.getStatus());
// }
// Transaction tx = utm.getTransaction();
// tx.enlistResource(ms);
// return new AtomikosTransactionAssistantImpl(ms);
// } catch (Exception e) {
// throw new ResourceException("Unable to get transaction status", e);
// }
// }
//
// protected UserTransactionManager getTM() {
// return new UserTransactionManager();
// }
//
// }
| import javax.naming.NamingException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactoryImpl; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
@Configuration
public class Config {
@Bean(name="xa/bookingService") | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactoryImpl.java
// public class BasicTransactionAssistanceFactoryImpl implements BasicTransactionAssistanceFactory {
//
// private String jndiName;
//
// /**
// * @param jndiName the name of the resource that this factory represents, eg the name of the microservice which this factory is in charge of
// * committing, rolling back and recovering.
// */
// public BasicTransactionAssistanceFactoryImpl(String jndiName) {
// this.jndiName = jndiName;
// }
//
// /** before calling this method, please ensure you have called {@link TransactionConfigurator#setup(String, CommitRollbackCallback)} */
// @Override
// public TransactionAssistant getTransactionAssistant() throws ResourceException {
// //enlist a new resource into the transaction. it will be delisted, when its closed.
// final CommitRollbackCallback commitRollbackCallback = TransactionConfigurator.getCommitRollbackCallback(jndiName);
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// UserTransactionManager utm = getTM();
// try {
// if(utm.getStatus() == Status.STATUS_NO_TRANSACTION){
// throw new ResourceException("no transaction found. please start one before getting the transaction assistant. status was: " + utm.getStatus());
// }
// Transaction tx = utm.getTransaction();
// tx.enlistResource(ms);
// return new AtomikosTransactionAssistantImpl(ms);
// } catch (Exception e) {
// throw new ResourceException("Unable to get transaction status", e);
// }
// }
//
// protected UserTransactionManager getTM() {
// return new UserTransactionManager();
// }
//
// }
// Path: demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/Config.java
import javax.naming.NamingException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactoryImpl;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
@Configuration
public class Config {
@Bean(name="xa/bookingService") | public BasicTransactionAssistanceFactory bookingServiceFactory() throws NamingException { |
maxant/genericconnector | demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/Config.java | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactoryImpl.java
// public class BasicTransactionAssistanceFactoryImpl implements BasicTransactionAssistanceFactory {
//
// private String jndiName;
//
// /**
// * @param jndiName the name of the resource that this factory represents, eg the name of the microservice which this factory is in charge of
// * committing, rolling back and recovering.
// */
// public BasicTransactionAssistanceFactoryImpl(String jndiName) {
// this.jndiName = jndiName;
// }
//
// /** before calling this method, please ensure you have called {@link TransactionConfigurator#setup(String, CommitRollbackCallback)} */
// @Override
// public TransactionAssistant getTransactionAssistant() throws ResourceException {
// //enlist a new resource into the transaction. it will be delisted, when its closed.
// final CommitRollbackCallback commitRollbackCallback = TransactionConfigurator.getCommitRollbackCallback(jndiName);
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// UserTransactionManager utm = getTM();
// try {
// if(utm.getStatus() == Status.STATUS_NO_TRANSACTION){
// throw new ResourceException("no transaction found. please start one before getting the transaction assistant. status was: " + utm.getStatus());
// }
// Transaction tx = utm.getTransaction();
// tx.enlistResource(ms);
// return new AtomikosTransactionAssistantImpl(ms);
// } catch (Exception e) {
// throw new ResourceException("Unable to get transaction status", e);
// }
// }
//
// protected UserTransactionManager getTM() {
// return new UserTransactionManager();
// }
//
// }
| import javax.naming.NamingException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactoryImpl; | /*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
@Configuration
public class Config {
@Bean(name="xa/bookingService")
public BasicTransactionAssistanceFactory bookingServiceFactory() throws NamingException { | // Path: connector/genericconnector-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactory.java
// public interface BasicTransactionAssistanceFactory {
//
// /**
// * Get transaction assistant from factory so that a callback can be
// * bound into the transaction as well as recovery which is controlled
// * by the app server's transaction manager.
// * @exception ResourceException Thrown if an assistant can't be obtained
// */
// TransactionAssistant getTransactionAssistant() throws ResourceException;
//
// }
//
// Path: connector/genericconnector-atomikos-api/src/main/java/ch/maxant/generic_jca_adapter/BasicTransactionAssistanceFactoryImpl.java
// public class BasicTransactionAssistanceFactoryImpl implements BasicTransactionAssistanceFactory {
//
// private String jndiName;
//
// /**
// * @param jndiName the name of the resource that this factory represents, eg the name of the microservice which this factory is in charge of
// * committing, rolling back and recovering.
// */
// public BasicTransactionAssistanceFactoryImpl(String jndiName) {
// this.jndiName = jndiName;
// }
//
// /** before calling this method, please ensure you have called {@link TransactionConfigurator#setup(String, CommitRollbackCallback)} */
// @Override
// public TransactionAssistant getTransactionAssistant() throws ResourceException {
// //enlist a new resource into the transaction. it will be delisted, when its closed.
// final CommitRollbackCallback commitRollbackCallback = TransactionConfigurator.getCommitRollbackCallback(jndiName);
// MicroserviceXAResource ms = new MicroserviceXAResource(jndiName, commitRollbackCallback);
// UserTransactionManager utm = getTM();
// try {
// if(utm.getStatus() == Status.STATUS_NO_TRANSACTION){
// throw new ResourceException("no transaction found. please start one before getting the transaction assistant. status was: " + utm.getStatus());
// }
// Transaction tx = utm.getTransaction();
// tx.enlistResource(ms);
// return new AtomikosTransactionAssistantImpl(ms);
// } catch (Exception e) {
// throw new ResourceException("Unable to get transaction status", e);
// }
// }
//
// protected UserTransactionManager getTM() {
// return new UserTransactionManager();
// }
//
// }
// Path: demo/genericconnector-demo-springboot-atomikos/src/main/java/ch/maxant/generic_jca_adapter/demo/Config.java
import javax.naming.NamingException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactory;
import ch.maxant.generic_jca_adapter.BasicTransactionAssistanceFactoryImpl;
/*
Copyright 2015 Ant Kutschera
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ch.maxant.generic_jca_adapter.demo;
@Configuration
public class Config {
@Bean(name="xa/bookingService")
public BasicTransactionAssistanceFactory bookingServiceFactory() throws NamingException { | BasicTransactionAssistanceFactory microserviceFactory = new BasicTransactionAssistanceFactoryImpl("xa/bookingService"); |
Rogach/jopenvoronoi | jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Edge.java | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double sq(double a) {
// return a*a;
// }
| import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.sq; | this.sign = other.sign;
this.face = other.face;
this.k = other.k;
this.null_face = other.null_face;
this.has_null_face = other.has_null_face;
this.type = other.type;
this.valid = other.valid;
x[0] = other.x[0];
x[1] = other.x[1];
x[2] = other.x[2];
x[3] = other.x[3];
x[4] = other.x[4];
x[5] = other.x[5];
x[6] = other.x[6];
x[7] = other.x[7];
y[0] = other.y[0];
y[1] = other.y[1];
y[2] = other.y[2];
y[3] = other.y[3];
y[4] = other.y[4];
y[5] = other.y[5];
y[6] = other.y[6];
y[7] = other.y[7];
}
/// \brief return point on edge at given offset-distance t
///
/// the eight-parameter formula for a point on the edge is:
/// x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
public Point point(double t) { | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double sq(double a) {
// return a*a;
// }
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Edge.java
import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.sq;
this.sign = other.sign;
this.face = other.face;
this.k = other.k;
this.null_face = other.null_face;
this.has_null_face = other.has_null_face;
this.type = other.type;
this.valid = other.valid;
x[0] = other.x[0];
x[1] = other.x[1];
x[2] = other.x[2];
x[3] = other.x[3];
x[4] = other.x[4];
x[5] = other.x[5];
x[6] = other.x[6];
x[7] = other.x[7];
y[0] = other.y[0];
y[1] = other.y[1];
y[2] = other.y[2];
y[3] = other.y[3];
y[4] = other.y[4];
y[5] = other.y[5];
y[6] = other.y[6];
y[7] = other.y[7];
}
/// \brief return point on edge at given offset-distance t
///
/// the eight-parameter formula for a point on the edge is:
/// x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
public Point point(double t) { | double discr1 = chop( sq(x[4]+x[5]*t) - sq(x[6]+x[7]*t), 1e-14 ); |
Rogach/jopenvoronoi | jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Edge.java | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double sq(double a) {
// return a*a;
// }
| import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.sq; | this.sign = other.sign;
this.face = other.face;
this.k = other.k;
this.null_face = other.null_face;
this.has_null_face = other.has_null_face;
this.type = other.type;
this.valid = other.valid;
x[0] = other.x[0];
x[1] = other.x[1];
x[2] = other.x[2];
x[3] = other.x[3];
x[4] = other.x[4];
x[5] = other.x[5];
x[6] = other.x[6];
x[7] = other.x[7];
y[0] = other.y[0];
y[1] = other.y[1];
y[2] = other.y[2];
y[3] = other.y[3];
y[4] = other.y[4];
y[5] = other.y[5];
y[6] = other.y[6];
y[7] = other.y[7];
}
/// \brief return point on edge at given offset-distance t
///
/// the eight-parameter formula for a point on the edge is:
/// x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
public Point point(double t) { | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double sq(double a) {
// return a*a;
// }
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Edge.java
import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.sq;
this.sign = other.sign;
this.face = other.face;
this.k = other.k;
this.null_face = other.null_face;
this.has_null_face = other.has_null_face;
this.type = other.type;
this.valid = other.valid;
x[0] = other.x[0];
x[1] = other.x[1];
x[2] = other.x[2];
x[3] = other.x[3];
x[4] = other.x[4];
x[5] = other.x[5];
x[6] = other.x[6];
x[7] = other.x[7];
y[0] = other.y[0];
y[1] = other.y[1];
y[2] = other.y[2];
y[3] = other.y[3];
y[4] = other.y[4];
y[5] = other.y[5];
y[6] = other.y[6];
y[7] = other.y[7];
}
/// \brief return point on edge at given offset-distance t
///
/// the eight-parameter formula for a point on the edge is:
/// x = x1 - x2 - x3*t +/- x4 * sqrt( square(x5+x6*t) - square(x7+x8*t) )
public Point point(double t) { | double discr1 = chop( sq(x[4]+x[5]*t) - sq(x[6]+x[7]*t), 1e-14 ); |
Rogach/jopenvoronoi | jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/QLLSolver.java | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static List<Double> quadratic_roots(double a, double b, double c) {
// List<Double> roots = new ArrayList<>();
// if ((a == 0) && (b == 0)) {
// return roots;
// }
// if (a == 0) {
// roots.add( -c / b );
// return roots;
// }
// if (b == 0) {
// double sqr = -c / a;
// if (sqr > 0) {
// roots.add( Math.sqrt(sqr) );
// roots.add( -roots.get(0) );
// return roots;
// } else if (sqr == 0) {
// roots.add(0d);
// return roots;
// } else {
// //std::cout << " quadratic_roots() b == 0. no roots.\n";
// return roots;
// }
// }
// double disc = chop(b*b - 4*a*c); // discriminant, chop!
// if (disc > 0) {
// double q;
// if (b > 0)
// q = (b + Math.sqrt(disc)) / -2;
// else
// q = (b - Math.sqrt(disc)) / -2;
// roots.add( q / a );
// roots.add( c / q );
// return roots;
// } else if (disc == 0) {
// roots.add( -b / (2*a) );
// return roots;
// }
// //std::cout << " quadratic_roots() disc < 0. no roots. disc= " << disc << "\n";
// return roots;
// }
| import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.quadratic_roots; | // y and t in terms of x
// t and x in terms of y
qll_solver( lins, 0, 1, 2, quads.get(0), k3, slns);
qll_solver( lins, 2, 0, 1, quads.get(0), k3, slns);
qll_solver( lins, 1, 2, 0, quads.get(0), k3, slns);
return slns.size();
}
/// \brief qll solver
// l0 first linear eqn
// l1 second linear eqn
// xi,yi,ti indexes to shuffle around
// xk, yk, kk, rk = params of one ('last') quadratic site (point or arc)
// solns = output solution triplets (x,y,t) or (u,v,t)
// returns number of solutions found
private int qll_solver(List<Eq> lins, int xi, int yi, int ti,
Eq quad, double k3, List<Solution> solns) {
assert( lins.size() == 2 ) : " lins.size() == 2 ";
double ai = lins.get(0).get(xi); // first linear
double bi = lins.get(0).get(yi);
double ki = lins.get(0).get(ti);
double ci = lins.get(0).c;
double aj = lins.get(1).get(xi); // second linear
double bj = lins.get(1).get(yi);
double kj = lins.get(1).get(ti);
double cj = lins.get(1).c;
| // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static List<Double> quadratic_roots(double a, double b, double c) {
// List<Double> roots = new ArrayList<>();
// if ((a == 0) && (b == 0)) {
// return roots;
// }
// if (a == 0) {
// roots.add( -c / b );
// return roots;
// }
// if (b == 0) {
// double sqr = -c / a;
// if (sqr > 0) {
// roots.add( Math.sqrt(sqr) );
// roots.add( -roots.get(0) );
// return roots;
// } else if (sqr == 0) {
// roots.add(0d);
// return roots;
// } else {
// //std::cout << " quadratic_roots() b == 0. no roots.\n";
// return roots;
// }
// }
// double disc = chop(b*b - 4*a*c); // discriminant, chop!
// if (disc > 0) {
// double q;
// if (b > 0)
// q = (b + Math.sqrt(disc)) / -2;
// else
// q = (b - Math.sqrt(disc)) / -2;
// roots.add( q / a );
// roots.add( c / q );
// return roots;
// } else if (disc == 0) {
// roots.add( -b / (2*a) );
// return roots;
// }
// //std::cout << " quadratic_roots() disc < 0. no roots. disc= " << disc << "\n";
// return roots;
// }
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/QLLSolver.java
import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.quadratic_roots;
// y and t in terms of x
// t and x in terms of y
qll_solver( lins, 0, 1, 2, quads.get(0), k3, slns);
qll_solver( lins, 2, 0, 1, quads.get(0), k3, slns);
qll_solver( lins, 1, 2, 0, quads.get(0), k3, slns);
return slns.size();
}
/// \brief qll solver
// l0 first linear eqn
// l1 second linear eqn
// xi,yi,ti indexes to shuffle around
// xk, yk, kk, rk = params of one ('last') quadratic site (point or arc)
// solns = output solution triplets (x,y,t) or (u,v,t)
// returns number of solutions found
private int qll_solver(List<Eq> lins, int xi, int yi, int ti,
Eq quad, double k3, List<Solution> solns) {
assert( lins.size() == 2 ) : " lins.size() == 2 ";
double ai = lins.get(0).get(xi); // first linear
double bi = lins.get(0).get(yi);
double ki = lins.get(0).get(ti);
double ci = lins.get(0).c;
double aj = lins.get(1).get(xi); // second linear
double bj = lins.get(1).get(yi);
double kj = lins.get(1).get(ti);
double cj = lins.get(1).c;
| double d = chop( ai*bj - aj*bi ); // chop! (determinant for 2 linear eqns (?)) |
Rogach/jopenvoronoi | jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/QLLSolver.java | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static List<Double> quadratic_roots(double a, double b, double c) {
// List<Double> roots = new ArrayList<>();
// if ((a == 0) && (b == 0)) {
// return roots;
// }
// if (a == 0) {
// roots.add( -c / b );
// return roots;
// }
// if (b == 0) {
// double sqr = -c / a;
// if (sqr > 0) {
// roots.add( Math.sqrt(sqr) );
// roots.add( -roots.get(0) );
// return roots;
// } else if (sqr == 0) {
// roots.add(0d);
// return roots;
// } else {
// //std::cout << " quadratic_roots() b == 0. no roots.\n";
// return roots;
// }
// }
// double disc = chop(b*b - 4*a*c); // discriminant, chop!
// if (disc > 0) {
// double q;
// if (b > 0)
// q = (b + Math.sqrt(disc)) / -2;
// else
// q = (b - Math.sqrt(disc)) / -2;
// roots.add( q / a );
// roots.add( c / q );
// return roots;
// } else if (disc == 0) {
// roots.add( -b / (2*a) );
// return roots;
// }
// //std::cout << " quadratic_roots() disc < 0. no roots. disc= " << disc << "\n";
// return roots;
// }
| import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.quadratic_roots; | double[][] tsolns = new double[2][3];
for (int i=0; i<scount; i++) {
tsolns[i][xi] = isolns[i][0]; // u x
tsolns[i][yi] = isolns[i][1]; // v y
tsolns[i][ti] = isolns[i][2]; // t t chop!
solns.add(new Solution(new Point( tsolns[i][0], tsolns[i][1] ),
tsolns[i][2], k3 ) );
}
//std::cout << " k3="<<kk3<<" qqq_solve found " << scount << " roots\n";
return scount;
}
/// Solve a system of one quadratic equation, and two linear equations.
///
/// (1) a0 u^2 + b0 u + c0 v^2 + d0 v + e0 w^2 + f0 w + g0 = 0
/// (2) u = a1 w + b1
/// (3) v = a2 w + b2
/// solve (1) for w (can have 0, 1, or 2 roots)
/// then substitute into (2) and (3) to find (u, v, t)
private int qll_solve( double a0, double b0, double c0, double d0,
double e0, double f0, double g0,
double a1, double b1,
double a2, double b2,
double soln[][])
{
//std::cout << "qll_solver()\n";
// TODO: optimize using abs(a0) == abs(c0) == abs(d0) == 1
double a = chop( (a0*(a1*a1) + c0*(a2*a2) + e0) );
double b = chop( (2*a0*a1*b1 + 2*a2*b2*c0 + a1*b0 + a2*d0 + f0) );
double c = a0*(b1*b1) + c0*(b2*b2) + b0*b1 + b2*d0 + g0; | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static List<Double> quadratic_roots(double a, double b, double c) {
// List<Double> roots = new ArrayList<>();
// if ((a == 0) && (b == 0)) {
// return roots;
// }
// if (a == 0) {
// roots.add( -c / b );
// return roots;
// }
// if (b == 0) {
// double sqr = -c / a;
// if (sqr > 0) {
// roots.add( Math.sqrt(sqr) );
// roots.add( -roots.get(0) );
// return roots;
// } else if (sqr == 0) {
// roots.add(0d);
// return roots;
// } else {
// //std::cout << " quadratic_roots() b == 0. no roots.\n";
// return roots;
// }
// }
// double disc = chop(b*b - 4*a*c); // discriminant, chop!
// if (disc > 0) {
// double q;
// if (b > 0)
// q = (b + Math.sqrt(disc)) / -2;
// else
// q = (b - Math.sqrt(disc)) / -2;
// roots.add( q / a );
// roots.add( c / q );
// return roots;
// } else if (disc == 0) {
// roots.add( -b / (2*a) );
// return roots;
// }
// //std::cout << " quadratic_roots() disc < 0. no roots. disc= " << disc << "\n";
// return roots;
// }
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/QLLSolver.java
import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.chop;
import static org.rogach.jopenvoronoi.Numeric.quadratic_roots;
double[][] tsolns = new double[2][3];
for (int i=0; i<scount; i++) {
tsolns[i][xi] = isolns[i][0]; // u x
tsolns[i][yi] = isolns[i][1]; // v y
tsolns[i][ti] = isolns[i][2]; // t t chop!
solns.add(new Solution(new Point( tsolns[i][0], tsolns[i][1] ),
tsolns[i][2], k3 ) );
}
//std::cout << " k3="<<kk3<<" qqq_solve found " << scount << " roots\n";
return scount;
}
/// Solve a system of one quadratic equation, and two linear equations.
///
/// (1) a0 u^2 + b0 u + c0 v^2 + d0 v + e0 w^2 + f0 w + g0 = 0
/// (2) u = a1 w + b1
/// (3) v = a2 w + b2
/// solve (1) for w (can have 0, 1, or 2 roots)
/// then substitute into (2) and (3) to find (u, v, t)
private int qll_solve( double a0, double b0, double c0, double d0,
double e0, double f0, double g0,
double a1, double b1,
double a2, double b2,
double soln[][])
{
//std::cout << "qll_solver()\n";
// TODO: optimize using abs(a0) == abs(c0) == abs(d0) == 1
double a = chop( (a0*(a1*a1) + c0*(a2*a2) + e0) );
double b = chop( (2*a0*a1*b1 + 2*a2*b2*c0 + a1*b0 + a2*d0 + f0) );
double c = a0*(b1*b1) + c0*(b2*b2) + b0*b1 + b2*d0 + g0; | List<Double> roots = quadratic_roots(a, b, c); // solves a*w^2 + b*w + c = 0 |
Rogach/jopenvoronoi | jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/PPPSolver.java | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double sq(double a) {
// return a*a;
// }
| import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.sq; | package org.rogach.jopenvoronoi;
/// point-point-point Solver (based on Sugihara & Iri paper)
public class PPPSolver extends Solver {
public int solve( Site s1, double k1, Site s2, double k2, Site s3, double k3, List<Solution> slns ) {
assert(s1.isPoint() && s2.isPoint() && s3.isPoint()) : "s1.isPoint() && s2.isPoint() && s3.isPoint()";
Point pi = s1.position();
Point pj = s2.position();
Point pk = s3.position();
if ( pi.is_right(pj,pk) ) {
Point tmp = pi;
pi = pj;
pj = tmp;
}
assert( !pi.is_right(pj,pk) ) : " !pi.is_right(pj,pk) ";
// 2) point pk should have the largest angle. largest angle is opposite longest side.
double longest_side = pi.sub(pj).norm();
while ( (pj.sub(pk).norm() > longest_side) || ((pi.sub(pk).norm() > longest_side)) ) {
// cyclic rotation of points until pk is opposite the longest side pi-pj
Point tmp = pk;
pk = pj;
pj = pi;
pi = tmp;
longest_side = pi.sub(pj).norm();
}
assert( !pi.is_right(pj,pk) ) : " !pi.is_right(pj,pk) ";
assert( pi.sub(pj).norm() >= pj.sub(pk).norm() ) : " pi.sub(pj).norm() >= pj.sub(pk).norm() ";
assert( pi.sub(pj).norm() >= pk.sub(pi).norm() ) : " pi.sub(pj).norm() >= pk.sub(pi).norm() ";
| // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double sq(double a) {
// return a*a;
// }
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/PPPSolver.java
import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.sq;
package org.rogach.jopenvoronoi;
/// point-point-point Solver (based on Sugihara & Iri paper)
public class PPPSolver extends Solver {
public int solve( Site s1, double k1, Site s2, double k2, Site s3, double k3, List<Solution> slns ) {
assert(s1.isPoint() && s2.isPoint() && s3.isPoint()) : "s1.isPoint() && s2.isPoint() && s3.isPoint()";
Point pi = s1.position();
Point pj = s2.position();
Point pk = s3.position();
if ( pi.is_right(pj,pk) ) {
Point tmp = pi;
pi = pj;
pj = tmp;
}
assert( !pi.is_right(pj,pk) ) : " !pi.is_right(pj,pk) ";
// 2) point pk should have the largest angle. largest angle is opposite longest side.
double longest_side = pi.sub(pj).norm();
while ( (pj.sub(pk).norm() > longest_side) || ((pi.sub(pk).norm() > longest_side)) ) {
// cyclic rotation of points until pk is opposite the longest side pi-pj
Point tmp = pk;
pk = pj;
pj = pi;
pi = tmp;
longest_side = pi.sub(pj).norm();
}
assert( !pi.is_right(pj,pk) ) : " !pi.is_right(pj,pk) ";
assert( pi.sub(pj).norm() >= pj.sub(pk).norm() ) : " pi.sub(pj).norm() >= pj.sub(pk).norm() ";
assert( pi.sub(pj).norm() >= pk.sub(pi).norm() ) : " pi.sub(pj).norm() >= pk.sub(pi).norm() ";
| double J2 = (pi.y-pk.y)*(sq(pj.x-pk.x)+sq(pj.y-pk.y) )/2.0 - |
Rogach/jopenvoronoi | jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/LLLSolver.java | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double determinant(double a, double b, double c,
// double d, double e, double f,
// double g, double h, double i ) {
// return a*(e*i-h*f)-b*(d*i-g*f)+c*(d*h-g*e);
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
| import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.determinant;
import static org.rogach.jopenvoronoi.Numeric.chop; | package org.rogach.jopenvoronoi;
/// \brief line-line-line Solver
///
/// solves 3x3 system.
public class LLLSolver extends Solver {
// a1 x + b1 y + c1 + k1 t = 0
// a2 x + b2 y + c2 + k2 t = 0
// a3 x + b3 y + c3 + k3 t = 0
//
// or in matrix form
//
// ( a1 b1 k1 ) ( x ) ( c1 )
// ( a2 b2 k2 ) ( y ) = -( c2 ) Ax = b
// ( a3 b3 k3 ) ( t ) ( c3 )
//
// Cramers rule x_i = det(A_i)/det(A)
// where A_i is A with column i replaced by b
public int solve( Site s1, double k1,
Site s2, double k2,
Site s3, double k3, List<Solution> slns ) {
assert( s1.isLine() && s2.isLine() && s3.isLine() ) : " s1.isLine() && s2.isLine() && s3.isLine() ";
List<Eq> eq = new ArrayList<>(); // equation-parameters, in quad-precision
Site[] sites = new Site[] { s1, s2, s3 };
double[] kvals = new double[] { k1, k2, k3 };
for (int i=0;i<3;i++)
eq.add( sites[i].eqp( kvals[i] ) );
int i = 0, j=1, k=2; | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double determinant(double a, double b, double c,
// double d, double e, double f,
// double g, double h, double i ) {
// return a*(e*i-h*f)-b*(d*i-g*f)+c*(d*h-g*e);
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/LLLSolver.java
import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.determinant;
import static org.rogach.jopenvoronoi.Numeric.chop;
package org.rogach.jopenvoronoi;
/// \brief line-line-line Solver
///
/// solves 3x3 system.
public class LLLSolver extends Solver {
// a1 x + b1 y + c1 + k1 t = 0
// a2 x + b2 y + c2 + k2 t = 0
// a3 x + b3 y + c3 + k3 t = 0
//
// or in matrix form
//
// ( a1 b1 k1 ) ( x ) ( c1 )
// ( a2 b2 k2 ) ( y ) = -( c2 ) Ax = b
// ( a3 b3 k3 ) ( t ) ( c3 )
//
// Cramers rule x_i = det(A_i)/det(A)
// where A_i is A with column i replaced by b
public int solve( Site s1, double k1,
Site s2, double k2,
Site s3, double k3, List<Solution> slns ) {
assert( s1.isLine() && s2.isLine() && s3.isLine() ) : " s1.isLine() && s2.isLine() && s3.isLine() ";
List<Eq> eq = new ArrayList<>(); // equation-parameters, in quad-precision
Site[] sites = new Site[] { s1, s2, s3 };
double[] kvals = new double[] { k1, k2, k3 };
for (int i=0;i<3;i++)
eq.add( sites[i].eqp( kvals[i] ) );
int i = 0, j=1, k=2; | double d = chop( determinant( eq.get(i).a, eq.get(i).b, eq.get(i).k, |
Rogach/jopenvoronoi | jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/LLLSolver.java | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double determinant(double a, double b, double c,
// double d, double e, double f,
// double g, double h, double i ) {
// return a*(e*i-h*f)-b*(d*i-g*f)+c*(d*h-g*e);
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
| import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.determinant;
import static org.rogach.jopenvoronoi.Numeric.chop; | package org.rogach.jopenvoronoi;
/// \brief line-line-line Solver
///
/// solves 3x3 system.
public class LLLSolver extends Solver {
// a1 x + b1 y + c1 + k1 t = 0
// a2 x + b2 y + c2 + k2 t = 0
// a3 x + b3 y + c3 + k3 t = 0
//
// or in matrix form
//
// ( a1 b1 k1 ) ( x ) ( c1 )
// ( a2 b2 k2 ) ( y ) = -( c2 ) Ax = b
// ( a3 b3 k3 ) ( t ) ( c3 )
//
// Cramers rule x_i = det(A_i)/det(A)
// where A_i is A with column i replaced by b
public int solve( Site s1, double k1,
Site s2, double k2,
Site s3, double k3, List<Solution> slns ) {
assert( s1.isLine() && s2.isLine() && s3.isLine() ) : " s1.isLine() && s2.isLine() && s3.isLine() ";
List<Eq> eq = new ArrayList<>(); // equation-parameters, in quad-precision
Site[] sites = new Site[] { s1, s2, s3 };
double[] kvals = new double[] { k1, k2, k3 };
for (int i=0;i<3;i++)
eq.add( sites[i].eqp( kvals[i] ) );
int i = 0, j=1, k=2; | // Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double determinant(double a, double b, double c,
// double d, double e, double f,
// double g, double h, double i ) {
// return a*(e*i-h*f)-b*(d*i-g*f)+c*(d*h-g*e);
// }
//
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/Numeric.java
// public static double chop(double val, double tol) {
// double _epsilon = tol;
// if (Math.abs(val) < _epsilon)
// return 0;
// else
// return val;
// }
// Path: jopenvoronoi-main/src/main/java/org/rogach/jopenvoronoi/LLLSolver.java
import java.util.List;
import java.util.ArrayList;
import static org.rogach.jopenvoronoi.Numeric.determinant;
import static org.rogach.jopenvoronoi.Numeric.chop;
package org.rogach.jopenvoronoi;
/// \brief line-line-line Solver
///
/// solves 3x3 system.
public class LLLSolver extends Solver {
// a1 x + b1 y + c1 + k1 t = 0
// a2 x + b2 y + c2 + k2 t = 0
// a3 x + b3 y + c3 + k3 t = 0
//
// or in matrix form
//
// ( a1 b1 k1 ) ( x ) ( c1 )
// ( a2 b2 k2 ) ( y ) = -( c2 ) Ax = b
// ( a3 b3 k3 ) ( t ) ( c3 )
//
// Cramers rule x_i = det(A_i)/det(A)
// where A_i is A with column i replaced by b
public int solve( Site s1, double k1,
Site s2, double k2,
Site s3, double k3, List<Solution> slns ) {
assert( s1.isLine() && s2.isLine() && s3.isLine() ) : " s1.isLine() && s2.isLine() && s3.isLine() ";
List<Eq> eq = new ArrayList<>(); // equation-parameters, in quad-precision
Site[] sites = new Site[] { s1, s2, s3 };
double[] kvals = new double[] { k1, k2, k3 };
for (int i=0;i<3;i++)
eq.add( sites[i].eqp( kvals[i] ) );
int i = 0, j=1, k=2; | double d = chop( determinant( eq.get(i).a, eq.get(i).b, eq.get(i).k, |
ryanbhayward/hexgui | src/hexgui/gui/MessageDialogs.java | // Path: src/hexgui/gui/GuiUtil.java
// public static String insertLineBreaks(String message)
// {
// final int MAX_CHAR_PER_LINE = 72;
// int length = message.length();
// if (length < MAX_CHAR_PER_LINE)
// return message;
// StringBuilder buffer = new StringBuilder();
// int startLine = 0;
// int lastWhiteSpace = -1;
// for (int pos = 0; pos < length; ++pos)
// {
// char c = message.charAt(pos);
// if (pos - startLine > 72)
// {
// int endLine =
// (lastWhiteSpace > startLine ? lastWhiteSpace : pos);
// if (buffer.length() > 0)
// buffer.append("<br>");
// buffer.append(message.substring(startLine, endLine));
// startLine = endLine;
// }
// if (Character.isWhitespace(c))
// lastWhiteSpace = pos;
// }
// if (buffer.length() > 0)
// buffer.append("<br>");
// buffer.append(message.substring(startLine));
// return buffer.toString();
// }
| import java.awt.Component;
import java.util.TreeSet;
import java.util.Set;
import java.util.prefs.Preferences;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import static hexgui.gui.GuiUtil.insertLineBreaks;
import hexgui.util.Platform;
import hexgui.util.PrefUtil;
import hexgui.util.StringUtils; | }
private boolean checkDisabled(String disableKey)
{
if (disableKey == null)
return false;
Preferences prefs =
PrefUtil.createNode("net/sf/hexgui/gui/messagedialogs/disabled");
boolean permanentlyDisabled = prefs.getBoolean(disableKey, false);
if (permanentlyDisabled)
return true;
// Make sure this entry exists (right now these settings can only
// be directly edited in the backing store)
prefs.putBoolean(disableKey, permanentlyDisabled);
return m_disabled.contains(disableKey);
}
private Object show(String disableKey, Component parent, String title,
String mainMessage, String optionalMessage,
int messageType, int optionType, Object[] options,
Object defaultOption, int destructiveIndex)
{
if (optionalMessage == null)
optionalMessage = "";
boolean isMac = Platform.isMac();
Box box = Box.createVerticalBox();
String css = GuiUtil.getMessageCss();
JLabel label = | // Path: src/hexgui/gui/GuiUtil.java
// public static String insertLineBreaks(String message)
// {
// final int MAX_CHAR_PER_LINE = 72;
// int length = message.length();
// if (length < MAX_CHAR_PER_LINE)
// return message;
// StringBuilder buffer = new StringBuilder();
// int startLine = 0;
// int lastWhiteSpace = -1;
// for (int pos = 0; pos < length; ++pos)
// {
// char c = message.charAt(pos);
// if (pos - startLine > 72)
// {
// int endLine =
// (lastWhiteSpace > startLine ? lastWhiteSpace : pos);
// if (buffer.length() > 0)
// buffer.append("<br>");
// buffer.append(message.substring(startLine, endLine));
// startLine = endLine;
// }
// if (Character.isWhitespace(c))
// lastWhiteSpace = pos;
// }
// if (buffer.length() > 0)
// buffer.append("<br>");
// buffer.append(message.substring(startLine));
// return buffer.toString();
// }
// Path: src/hexgui/gui/MessageDialogs.java
import java.awt.Component;
import java.util.TreeSet;
import java.util.Set;
import java.util.prefs.Preferences;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import static hexgui.gui.GuiUtil.insertLineBreaks;
import hexgui.util.Platform;
import hexgui.util.PrefUtil;
import hexgui.util.StringUtils;
}
private boolean checkDisabled(String disableKey)
{
if (disableKey == null)
return false;
Preferences prefs =
PrefUtil.createNode("net/sf/hexgui/gui/messagedialogs/disabled");
boolean permanentlyDisabled = prefs.getBoolean(disableKey, false);
if (permanentlyDisabled)
return true;
// Make sure this entry exists (right now these settings can only
// be directly edited in the backing store)
prefs.putBoolean(disableKey, permanentlyDisabled);
return m_disabled.contains(disableKey);
}
private Object show(String disableKey, Component parent, String title,
String mainMessage, String optionalMessage,
int messageType, int optionType, Object[] options,
Object defaultOption, int destructiveIndex)
{
if (optionalMessage == null)
optionalMessage = "";
boolean isMac = Platform.isMac();
Box box = Box.createVerticalBox();
String css = GuiUtil.getMessageCss();
JLabel label = | new JLabel("<html>" + css + "<b>" + insertLineBreaks(mainMessage) |
sadikovi/spark-netflow | src/test/java/com/github/sadikovi/netflowlib/predicate/JavaColumnSuite.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ByteColumn extends Column {
// ByteColumn() { }
//
// ByteColumn(String name, int offset, byte min, byte max) {
// super(name, Byte.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ByteColumn(String name, int offset) {
// this(name, offset, (byte) 0, Byte.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private byte minValue;
// private byte maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
| import static org.hamcrest.CoreMatchers.containsString;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.github.sadikovi.netflowlib.predicate.Columns.ByteColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
public class JavaColumnSuite {
@Test
public void testColumnInit() {
// initialize byte column and check min, max | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ByteColumn extends Column {
// ByteColumn() { }
//
// ByteColumn(String name, int offset, byte min, byte max) {
// super(name, Byte.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ByteColumn(String name, int offset) {
// this(name, offset, (byte) 0, Byte.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private byte minValue;
// private byte maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
// Path: src/test/java/com/github/sadikovi/netflowlib/predicate/JavaColumnSuite.java
import static org.hamcrest.CoreMatchers.containsString;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.github.sadikovi.netflowlib.predicate.Columns.ByteColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
public class JavaColumnSuite {
@Test
public void testColumnInit() {
// initialize byte column and check min, max | ByteColumn col1 = new ByteColumn("name", 1); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV5.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
| import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV5 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index (known as Sif), size: 2 | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV5.java
import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV5 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index (known as Sif), size: 2 | public static final IntColumn FIELD_INPUT = new IntColumn("input", 28); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV5.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
| import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV5 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index (known as Sif), size: 2
public static final IntColumn FIELD_INPUT = new IntColumn("input", 28);
// Output interface index (known as Dif), size: 2
public static final IntColumn FIELD_OUTPUT = new IntColumn("output", 30);
// Packets sent in Duration, size: 4
public static final LongColumn FIELD_DPKTS = new LongColumn("packets", 32);
// Octets sent in Duration, size: 4
public static final LongColumn FIELD_DOCTETS = new LongColumn("octets", 36);
// SysUptime at start of flow, size: 4
public static final LongColumn FIELD_FIRST = new LongColumn("first", 40);
// and of last packet of flow, size: 4
public static final LongColumn FIELD_LAST = new LongColumn("last", 44);
// TCP/UDP source port number or equivalent, size: 2
public static final IntColumn FIELD_SRCPORT = new IntColumn("srcport", 48);
// TCP/UDP destination port number or equiv, size: 2
public static final IntColumn FIELD_DSTPORT = new IntColumn("dstport", 50);
// IP protocol, e.g., 6=TCP, 17=UDP, ..., size: 1 | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV5.java
import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV5 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index (known as Sif), size: 2
public static final IntColumn FIELD_INPUT = new IntColumn("input", 28);
// Output interface index (known as Dif), size: 2
public static final IntColumn FIELD_OUTPUT = new IntColumn("output", 30);
// Packets sent in Duration, size: 4
public static final LongColumn FIELD_DPKTS = new LongColumn("packets", 32);
// Octets sent in Duration, size: 4
public static final LongColumn FIELD_DOCTETS = new LongColumn("octets", 36);
// SysUptime at start of flow, size: 4
public static final LongColumn FIELD_FIRST = new LongColumn("first", 40);
// and of last packet of flow, size: 4
public static final LongColumn FIELD_LAST = new LongColumn("last", 44);
// TCP/UDP source port number or equivalent, size: 2
public static final IntColumn FIELD_SRCPORT = new IntColumn("srcport", 48);
// TCP/UDP destination port number or equiv, size: 2
public static final IntColumn FIELD_DSTPORT = new IntColumn("dstport", 50);
// IP protocol, e.g., 6=TCP, 17=UDP, ..., size: 1 | public static final ShortColumn FIELD_PROT = new ShortColumn("protocol", 52); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/predicate/Operators.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static abstract class Column implements Serializable, Statistics {
// Column() { }
//
// Column(String name, Class<?> type, int offset) {
// if (offset < 0) {
// throw new IllegalArgumentException("Wrong offset " + offset);
// }
//
// columnName = name;
// columnType = type;
// columnOffset = offset;
// }
//
// /** Get column name */
// public String getColumnName() {
// return columnName;
// }
//
// /** Get column type */
// public Class<?> getColumnType() {
// return columnType;
// }
//
// /** Get column offset in a record */
// public int getColumnOffset() {
// return columnOffset;
// }
//
// /** Read field from byte buffer and return value that confirms to column class */
// public abstract Object readField(WrappedByteBuf buffer);
//
// /** Update value inspector with value from buffer */
// public abstract void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi);
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(name=" + columnName + ", offset=" + columnOffset + ")";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
//
// Column that = (Column) obj;
//
// if (!columnType.equals(that.columnType)) return false;
// if (!columnName.equals(that.columnName)) return false;
// if (columnOffset != that.columnOffset) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = columnName.hashCode();
// result = 31 * result + columnType.hashCode();
// result = 31 * result + columnOffset;
// return result;
// }
//
// private String columnName = null;
// private Class<?> columnType = null;
// private int columnOffset = -1;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static interface Inspector {
//
// boolean accept(Visitor visitor);
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/statistics/Statistics.java
// public abstract interface Statistics {
// public Object getMin();
//
// public Object getMax();
// }
| import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import com.github.sadikovi.netflowlib.predicate.Columns.Column;
import com.github.sadikovi.netflowlib.predicate.Inspectors.Inspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector;
import com.github.sadikovi.netflowlib.statistics.Statistics; | @Override
public int hashCode() {
int result = child.hashCode();
result = 31 * result + getClass().hashCode();
return result;
}
private final FilterPredicate child;
}
//////////////////////////////////////////////////////////////
// Concrete implementation of unary logical predicate (Not)
//////////////////////////////////////////////////////////////
/** "Not" inversion operator */
public static final class Not extends UnaryLogicalPredicate {
Not(FilterPredicate child) {
super(child);
}
@Override
public FilterPredicate update(
PredicateTransform transformer,
HashMap<String, Statistics> statistics) {
Not copy = new Not(getChild().update(transformer, statistics));
return transformer.transform(copy);
}
@Override
public Inspector convert() { | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static abstract class Column implements Serializable, Statistics {
// Column() { }
//
// Column(String name, Class<?> type, int offset) {
// if (offset < 0) {
// throw new IllegalArgumentException("Wrong offset " + offset);
// }
//
// columnName = name;
// columnType = type;
// columnOffset = offset;
// }
//
// /** Get column name */
// public String getColumnName() {
// return columnName;
// }
//
// /** Get column type */
// public Class<?> getColumnType() {
// return columnType;
// }
//
// /** Get column offset in a record */
// public int getColumnOffset() {
// return columnOffset;
// }
//
// /** Read field from byte buffer and return value that confirms to column class */
// public abstract Object readField(WrappedByteBuf buffer);
//
// /** Update value inspector with value from buffer */
// public abstract void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi);
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(name=" + columnName + ", offset=" + columnOffset + ")";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null || getClass() != obj.getClass()) return false;
//
// Column that = (Column) obj;
//
// if (!columnType.equals(that.columnType)) return false;
// if (!columnName.equals(that.columnName)) return false;
// if (columnOffset != that.columnOffset) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = columnName.hashCode();
// result = 31 * result + columnType.hashCode();
// result = 31 * result + columnOffset;
// return result;
// }
//
// private String columnName = null;
// private Class<?> columnType = null;
// private int columnOffset = -1;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static interface Inspector {
//
// boolean accept(Visitor visitor);
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/statistics/Statistics.java
// public abstract interface Statistics {
// public Object getMin();
//
// public Object getMax();
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Operators.java
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import com.github.sadikovi.netflowlib.predicate.Columns.Column;
import com.github.sadikovi.netflowlib.predicate.Inspectors.Inspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector;
import com.github.sadikovi.netflowlib.statistics.Statistics;
@Override
public int hashCode() {
int result = child.hashCode();
result = 31 * result + getClass().hashCode();
return result;
}
private final FilterPredicate child;
}
//////////////////////////////////////////////////////////////
// Concrete implementation of unary logical predicate (Not)
//////////////////////////////////////////////////////////////
/** "Not" inversion operator */
public static final class Not extends UnaryLogicalPredicate {
Not(FilterPredicate child) {
super(child);
}
@Override
public FilterPredicate update(
PredicateTransform transformer,
HashMap<String, Statistics> statistics) {
Not copy = new Not(getChild().update(transformer, statistics));
return transformer.transform(copy);
}
@Override
public Inspector convert() { | return new NotInspector(getChild().convert()); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/predicate/Visitor.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
| import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
/**
* [[Visitor]] interface to traverse [[Inspector]] instances and resolve boolean expressions for
* each of them. Usually implemented by [[RecordMaterializer]] subclasses to resolve predicate
* for each record.
*/
public abstract interface Visitor {
boolean visit(ValueInspector inspector);
| // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Visitor.java
import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
/**
* [[Visitor]] interface to traverse [[Inspector]] instances and resolve boolean expressions for
* each of them. Usually implemented by [[RecordMaterializer]] subclasses to resolve predicate
* for each record.
*/
public abstract interface Visitor {
boolean visit(ValueInspector inspector);
| boolean visit(AndInspector inspector); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/predicate/Visitor.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
| import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
/**
* [[Visitor]] interface to traverse [[Inspector]] instances and resolve boolean expressions for
* each of them. Usually implemented by [[RecordMaterializer]] subclasses to resolve predicate
* for each record.
*/
public abstract interface Visitor {
boolean visit(ValueInspector inspector);
boolean visit(AndInspector inspector);
| // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Visitor.java
import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
/**
* [[Visitor]] interface to traverse [[Inspector]] instances and resolve boolean expressions for
* each of them. Usually implemented by [[RecordMaterializer]] subclasses to resolve predicate
* for each record.
*/
public abstract interface Visitor {
boolean visit(ValueInspector inspector);
boolean visit(AndInspector inspector);
| boolean visit(OrInspector inspector); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/predicate/Visitor.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
| import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
/**
* [[Visitor]] interface to traverse [[Inspector]] instances and resolve boolean expressions for
* each of them. Usually implemented by [[RecordMaterializer]] subclasses to resolve predicate
* for each record.
*/
public abstract interface Visitor {
boolean visit(ValueInspector inspector);
boolean visit(AndInspector inspector);
boolean visit(OrInspector inspector);
| // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class AndInspector extends BinaryLogical {
// public AndInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class NotInspector extends UnaryLogical {
// public NotInspector(Inspector child) {
// super(child);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static final class OrInspector extends BinaryLogical {
// public OrInspector(Inspector left, Inspector right) {
// super(left, right);
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Inspectors.java
// public static class ValueInspector implements Inspector, Serializable {
// public ValueInspector() { }
//
// public void update(boolean value) { throw new UnsupportedOperationException(); }
// public void update(byte value) { throw new UnsupportedOperationException(); }
// public void update(short value) { throw new UnsupportedOperationException(); }
// public void update(int value) { throw new UnsupportedOperationException(); }
// public void update(long value) { throw new UnsupportedOperationException(); }
//
// public final void reset() {
// known = false;
// result = false;
// }
//
// public final void setResult(boolean expression) {
// if (isKnown()) {
// throw new IllegalStateException("Inspector is already known, cannot set result");
// }
//
// result = expression;
// known = true;
// }
//
// public final boolean getResult() {
// if (!isKnown()) {
// throw new IllegalStateException("Inspector is not known, cannot return result");
// }
//
// return result;
// }
//
// public final boolean isKnown() {
// return known;
// }
//
// @Override
// public boolean accept(Visitor visitor) {
// return visitor.visit(this);
// }
//
// private boolean known = false;
// private boolean result = false;
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Visitor.java
import com.github.sadikovi.netflowlib.predicate.Inspectors.AndInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.NotInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.OrInspector;
import com.github.sadikovi.netflowlib.predicate.Inspectors.ValueInspector;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.predicate;
/**
* [[Visitor]] interface to traverse [[Inspector]] instances and resolve boolean expressions for
* each of them. Usually implemented by [[RecordMaterializer]] subclasses to resolve predicate
* for each record.
*/
public abstract interface Visitor {
boolean visit(ValueInspector inspector);
boolean visit(AndInspector inspector);
boolean visit(OrInspector inspector);
| boolean visit(NotInspector inspector); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV7.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
| import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV7 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index, size: 2 | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV7.java
import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV7 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index, size: 2 | public static final IntColumn FIELD_INPUT = new IntColumn("input", 28); |
sadikovi/spark-netflow | src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV7.java | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
| import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn; | /*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV7 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index, size: 2
public static final IntColumn FIELD_INPUT = new IntColumn("input", 28);
// Output interface index, size: 2
public static final IntColumn FIELD_OUTPUT = new IntColumn("output", 30);
// Packets sent in Duration, size: 4
public static final LongColumn FIELD_DPKTS = new LongColumn("packets", 32);
// Octets sent in Duration, size: 4
public static final LongColumn FIELD_DOCTETS = new LongColumn("octets", 36);
// SysUptime at start of flow, size: 4
public static final LongColumn FIELD_FIRST = new LongColumn("first", 40);
// and of last packet of flow, size: 4
public static final LongColumn FIELD_LAST = new LongColumn("last", 44);
// TCP/UDP source port number or equivalent, size: 2
public static final IntColumn FIELD_SRCPORT = new IntColumn("srcport", 48);
// TCP/UDP destination port number or equiv, size: 2
public static final IntColumn FIELD_DSTPORT = new IntColumn("dstport", 50);
// IP protocol, e.g., 6=TCP, 17=UDP, ..., size: 1 | // Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class IntColumn extends Column {
// IntColumn() { }
//
// IntColumn(String name, int offset, int min, int max) {
// super(name, Integer.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public IntColumn(String name, int offset) {
// this(name, offset, (int) 0, Integer.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedShort(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedShort(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private int minValue;
// private int maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class LongColumn extends Column {
// LongColumn() { }
//
// LongColumn(String name, int offset, long min, long max) {
// super(name, Long.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public LongColumn(String name, int offset) {
// this(name, offset, (long) 0, Long.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedInt(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedInt(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private long minValue;
// private long maxValue;
// }
//
// Path: src/main/java/com/github/sadikovi/netflowlib/predicate/Columns.java
// public static class ShortColumn extends Column {
// ShortColumn() { }
//
// ShortColumn(String name, int offset, short min, short max) {
// super(name, Short.class, offset);
// minValue = min;
// maxValue = max;
// }
//
// public ShortColumn(String name, int offset) {
// this(name, offset, (short) 0, Short.MAX_VALUE);
// }
//
// @Override
// public Object readField(WrappedByteBuf buffer) {
// return buffer.getUnsignedByte(getColumnOffset());
// }
//
// @Override
// public void updateValueInspector(WrappedByteBuf buffer, ValueInspector vi) {
// vi.update(buffer.getUnsignedByte(getColumnOffset()));
// }
//
// @Override
// public Object getMin() {
// return minValue;
// }
//
// @Override
// public Object getMax() {
// return maxValue;
// }
//
// private short minValue;
// private short maxValue;
// }
// Path: src/main/java/com/github/sadikovi/netflowlib/version/NetFlowV7.java
import com.github.sadikovi.netflowlib.predicate.Columns.IntColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.LongColumn;
import com.github.sadikovi.netflowlib.predicate.Columns.ShortColumn;
/*
* Copyright 2016 sadikovi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.sadikovi.netflowlib.version;
public class NetFlowV7 extends NetFlow {
// list of supported columns and size in bytes
// Current seconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_SECS = new LongColumn("unix_secs", 0);
// Residual nanoseconds since 0000 UTC 1970, size: 4
public static final LongColumn FIELD_UNIX_NSECS = new LongColumn("unix_nsecs", 4);
// Current time in millisecs since router booted, size: 4
public static final LongColumn FIELD_SYSUPTIME = new LongColumn("sys_uptime", 8);
// Exporter IP address, size: 4
public static final LongColumn FIELD_EXADDR = new LongColumn("export_ip", 12);
// Source IP Address, size: 4
public static final LongColumn FIELD_SRCADDR = new LongColumn("srcip", 16);
// Destination IP Address, size: 4
public static final LongColumn FIELD_DSTADDR = new LongColumn("dstip", 20);
// Next hop router's IP Address, size: 4
public static final LongColumn FIELD_NEXTHOP = new LongColumn("nexthop", 24);
// Input interface index, size: 2
public static final IntColumn FIELD_INPUT = new IntColumn("input", 28);
// Output interface index, size: 2
public static final IntColumn FIELD_OUTPUT = new IntColumn("output", 30);
// Packets sent in Duration, size: 4
public static final LongColumn FIELD_DPKTS = new LongColumn("packets", 32);
// Octets sent in Duration, size: 4
public static final LongColumn FIELD_DOCTETS = new LongColumn("octets", 36);
// SysUptime at start of flow, size: 4
public static final LongColumn FIELD_FIRST = new LongColumn("first", 40);
// and of last packet of flow, size: 4
public static final LongColumn FIELD_LAST = new LongColumn("last", 44);
// TCP/UDP source port number or equivalent, size: 2
public static final IntColumn FIELD_SRCPORT = new IntColumn("srcport", 48);
// TCP/UDP destination port number or equiv, size: 2
public static final IntColumn FIELD_DSTPORT = new IntColumn("dstport", 50);
// IP protocol, e.g., 6=TCP, 17=UDP, ..., size: 1 | public static final ShortColumn FIELD_PROT = new ShortColumn("protocol", 52); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/EmailConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EmailConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_email";
private static final String VALID = "peter.canvas+driver@blablacar.com";
private static final String NOT_VALID = "to@";
@Test
public void isValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/EmailConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EmailConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_email";
private static final String VALID = "peter.canvas+driver@blablacar.com";
private static final String NOT_VALID = "to@";
@Test
public void isValid() throws Exception { | assertEmpty("is valid with String", new EmailConstraint(VALID, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/EmailConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EmailConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_email";
private static final String VALID = "peter.canvas+driver@blablacar.com";
private static final String NOT_VALID = "to@";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new EmailConstraint(VALID, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText", new EmailConstraint(generateEditText(VALID), PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner", new EmailConstraint(generateSpinner(VALID), PROPERTY_NAME).validate());
}
@Test
public void isNotValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/EmailConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EmailConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_email";
private static final String VALID = "peter.canvas+driver@blablacar.com";
private static final String NOT_VALID = "to@";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new EmailConstraint(VALID, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText", new EmailConstraint(generateEditText(VALID), PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner", new EmailConstraint(generateSpinner(VALID), PROPERTY_NAME).validate());
}
@Test
public void isNotValid() throws Exception { | assertNotEmpty("is not valid with String", new EmailConstraint(NOT_VALID, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/BlankConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate the object value to be null or empty.
*/
public class BlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when value is not blank.
*/
public static final String ERROR_CODE_IS_NOT_BLANK = "ERROR_CODE_IS_NOT_BLANK";
protected String message = "This value should be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public BlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is blank.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/BlankConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate the object value to be null or empty.
*/
public class BlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when value is not blank.
*/
public static final String ERROR_CODE_IS_NOT_BLANK = "ERROR_CODE_IS_NOT_BLANK";
protected String message = "This value should be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public BlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is blank.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/BlankConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate the object value to be null or empty.
*/
public class BlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when value is not blank.
*/
public static final String ERROR_CODE_IS_NOT_BLANK = "ERROR_CODE_IS_NOT_BLANK";
protected String message = "This value should be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public BlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is blank.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/BlankConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate the object value to be null or empty.
*/
public class BlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when value is not blank.
*/
public static final String ERROR_CODE_IS_NOT_BLANK = "ERROR_CODE_IS_NOT_BLANK";
protected String message = "This value should be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public BlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is blank.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/NotEqualsConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate the object value to be not equals to the excepted one.
*/
public class NotEqualsConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when value is not equals to the excepted one.
*/
public static final String ERROR_CODE_EQUALS = "ERROR_CODE_EQUALS";
protected final String expectedValue;
protected String message = "This value should not be equal to %s.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param expectedValue the String value you except.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public NotEqualsConstraint(@NonNull Object object, @NonNull String expectedValue, @NonNull String propertyName) {
super(object, propertyName);
this.expectedValue = expectedValue;
}
/**
* Validate if the value is not equals to the expected one.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@Override
@NonNull | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/NotEqualsConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate the object value to be not equals to the excepted one.
*/
public class NotEqualsConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when value is not equals to the excepted one.
*/
public static final String ERROR_CODE_EQUALS = "ERROR_CODE_EQUALS";
protected final String expectedValue;
protected String message = "This value should not be equal to %s.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param expectedValue the String value you except.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public NotEqualsConstraint(@NonNull Object object, @NonNull String expectedValue, @NonNull String propertyName) {
super(object, propertyName);
this.expectedValue = expectedValue;
}
/**
* Validate if the value is not equals to the expected one.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@Override
@NonNull | public Set<Violation> validate() { |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/UrlConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class UrlConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_url";
private static final String VALID = "http://www.blablacar.com";
private static final String NOT_VALID = "http://";
@Test
public void isValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/UrlConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class UrlConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_url";
private static final String VALID = "http://www.blablacar.com";
private static final String NOT_VALID = "http://";
@Test
public void isValid() throws Exception { | assertEmpty("is valid with String", new UrlConstraint(VALID, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/UrlConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class UrlConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_url";
private static final String VALID = "http://www.blablacar.com";
private static final String NOT_VALID = "http://";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new UrlConstraint(VALID, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText", new UrlConstraint(generateEditText(VALID), PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner", new UrlConstraint(generateSpinner(VALID), PROPERTY_NAME).validate());
}
@Test
public void isNotValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/UrlConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class UrlConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_url";
private static final String VALID = "http://www.blablacar.com";
private static final String NOT_VALID = "http://";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new UrlConstraint(VALID, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText", new UrlConstraint(generateEditText(VALID), PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner", new UrlConstraint(generateSpinner(VALID), PROPERTY_NAME).validate());
}
@Test
public void isNotValid() throws Exception { | assertNotEmpty("is not valid with String", new UrlConstraint(NOT_VALID, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/LengthConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.Violation;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class LengthConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_length";
private static final String VALUE = "valid";
@Test
public void isValid() throws Exception { | // Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/LengthConstraintTest.java
import com.comuto.validator.Violation;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class LengthConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_length";
private static final String VALUE = "valid";
@Test
public void isValid() throws Exception { | assertEmpty("is valid with String", validateConstraint(VALUE, 1, 8)); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/LengthConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.Violation;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class LengthConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_length";
private static final String VALUE = "valid";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", validateConstraint(VALUE, 1, 8));
assertEmpty("is valid with String", validateConstraint(VALUE, 5, 5));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 1, 8));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 5, 5));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 1, 8));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 5, 5));
}
@Test
public void isNotValid() throws Exception { | // Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/LengthConstraintTest.java
import com.comuto.validator.Violation;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class LengthConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_length";
private static final String VALUE = "valid";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", validateConstraint(VALUE, 1, 8));
assertEmpty("is valid with String", validateConstraint(VALUE, 5, 5));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 1, 8));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 5, 5));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 1, 8));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 5, 5));
}
@Test
public void isNotValid() throws Exception { | assertNotEmpty("is invalid with String", validateConstraint(VALUE, 6, 8)); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/LengthConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.Violation;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class LengthConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_length";
private static final String VALUE = "valid";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", validateConstraint(VALUE, 1, 8));
assertEmpty("is valid with String", validateConstraint(VALUE, 5, 5));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 1, 8));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 5, 5));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 1, 8));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 5, 5));
}
@Test
public void isNotValid() throws Exception {
assertNotEmpty("is invalid with String", validateConstraint(VALUE, 6, 8));
assertNotEmpty("is invalid with String", validateConstraint(VALUE, 1, 3));
assertNotEmpty("is invalid with EditText", validateConstraint(generateEditText(VALUE), 6, 8));
assertNotEmpty("is invalid with EditText", validateConstraint(generateEditText(VALUE), 1, 3));
assertNotEmpty("is invalid with Spinner", validateConstraint(generateSpinner(VALUE), 6, 8));
assertNotEmpty("is invalid with Spinner", validateConstraint(generateSpinner(VALUE), 1, 3));
}
| // Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/LengthConstraintTest.java
import com.comuto.validator.Violation;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class LengthConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_length";
private static final String VALUE = "valid";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", validateConstraint(VALUE, 1, 8));
assertEmpty("is valid with String", validateConstraint(VALUE, 5, 5));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 1, 8));
assertEmpty("is valid with EditText", validateConstraint(generateEditText(VALUE), 5, 5));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 1, 8));
assertEmpty("is valid with Spinner", validateConstraint(generateSpinner(VALUE), 5, 5));
}
@Test
public void isNotValid() throws Exception {
assertNotEmpty("is invalid with String", validateConstraint(VALUE, 6, 8));
assertNotEmpty("is invalid with String", validateConstraint(VALUE, 1, 3));
assertNotEmpty("is invalid with EditText", validateConstraint(generateEditText(VALUE), 6, 8));
assertNotEmpty("is invalid with EditText", validateConstraint(generateEditText(VALUE), 1, 3));
assertNotEmpty("is invalid with Spinner", validateConstraint(generateSpinner(VALUE), 6, 8));
assertNotEmpty("is invalid with Spinner", validateConstraint(generateSpinner(VALUE), 1, 3));
}
| private Set<Violation> validateConstraint(final Object object, final double min, final double max) { |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/NameConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class NameConstraintTest {
private static final String VALID = "Peter Canvas";
private static final String INVALID = "()Test";
@Test
public void isValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/NameConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class NameConstraintTest {
private static final String VALID = "Peter Canvas";
private static final String INVALID = "()Test";
@Test
public void isValid() throws Exception { | assertEmpty("is valid", new NameConstraint(VALID, "string").validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/NameConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class NameConstraintTest {
private static final String VALID = "Peter Canvas";
private static final String INVALID = "()Test";
@Test
public void isValid() throws Exception {
assertEmpty("is valid", new NameConstraint(VALID, "string").validate());
}
@Test
public void isInValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/NameConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class NameConstraintTest {
private static final String VALID = "Peter Canvas";
private static final String INVALID = "()Test";
@Test
public void isValid() throws Exception {
assertEmpty("is valid", new NameConstraint(VALID, "string").validate());
}
@Test
public void isInValid() throws Exception { | assertNotEmpty("is invalid", new NameConstraint(INVALID, "string").validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/BlankConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class BlankConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_name";
private static final String NOT_BLANK = "not_blank";
@Test
public void isValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/BlankConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class BlankConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_name";
private static final String NOT_BLANK = "not_blank";
@Test
public void isValid() throws Exception { | assertEmpty("is valid with String", new BlankConstraint(BLANK, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/BlankConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class BlankConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_name";
private static final String NOT_BLANK = "not_blank";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new BlankConstraint(BLANK, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText", new BlankConstraint(generateEditText(BLANK), PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner", new BlankConstraint(generateSpinner(BLANK), PROPERTY_NAME).validate());
}
@Test
public void isInvalidWithNotBlank() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/BlankConstraintTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class BlankConstraintTest
extends BaseConstraintTest {
private static final String PROPERTY_NAME = "property_name";
private static final String NOT_BLANK = "not_blank";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new BlankConstraint(BLANK, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText", new BlankConstraint(generateEditText(BLANK), PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner", new BlankConstraint(generateSpinner(BLANK), PROPERTY_NAME).validate());
}
@Test
public void isInvalidWithNotBlank() throws Exception { | assertNotEmpty("is invalid with String", new BlankConstraint(NOT_BLANK, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/EqualsConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = VALID;
public static final String NOT_EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception { | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/EqualsConstraintTest.java
import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = VALID;
public static final String NOT_EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception { | assertEmpty("is valid with String", new EqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/EqualsConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = VALID;
public static final String NOT_EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new EqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new EqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new EqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception { | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/EqualsConstraintTest.java
import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = VALID;
public static final String NOT_EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new EqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new EqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new EqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception { | assertNotEmpty("is invalid with String", |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/EqualsConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = VALID;
public static final String NOT_EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new EqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new EqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new EqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception {
assertNotEmpty("is invalid with String",
new EqualsConstraint(VALID, NOT_EXPECTED_VALUE, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with EditText",
new EqualsConstraint(generateEditText(VALID), NOT_EXPECTED_VALUE, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with Spinner",
new EqualsConstraint(generateSpinner(VALID), NOT_EXPECTED_VALUE, PROPERTY_NAME).validate());
}
| // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/EqualsConstraintTest.java
import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class EqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = VALID;
public static final String NOT_EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new EqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new EqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new EqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception {
assertNotEmpty("is invalid with String",
new EqualsConstraint(VALID, NOT_EXPECTED_VALUE, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with EditText",
new EqualsConstraint(generateEditText(VALID), NOT_EXPECTED_VALUE, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with Spinner",
new EqualsConstraint(generateSpinner(VALID), NOT_EXPECTED_VALUE, PROPERTY_NAME).validate());
}
| @Test(expected = UnsupportedException.class) |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/IsCheckedConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate a view to be checked.
* @param <T> Object should extends from View.
*/
public class IsCheckedConstraint<T extends View> extends Constraint<T> {
/**
* Constant pass to Violation when object is not check.
*/
public static final String ERROR_CODE_IS_NOT_CHECKED = "ERROR_CODE_IS_NOT_CHECKED";
protected String message = "This should have at least one checked choice.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public IsCheckedConstraint(@NonNull T object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the object view is checked.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/IsCheckedConstraint.java
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate a view to be checked.
* @param <T> Object should extends from View.
*/
public class IsCheckedConstraint<T extends View> extends Constraint<T> {
/**
* Constant pass to Violation when object is not check.
*/
public static final String ERROR_CODE_IS_NOT_CHECKED = "ERROR_CODE_IS_NOT_CHECKED";
protected String message = "This should have at least one checked choice.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public IsCheckedConstraint(@NonNull T object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the object view is checked.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/IsCheckedConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate a view to be checked.
* @param <T> Object should extends from View.
*/
public class IsCheckedConstraint<T extends View> extends Constraint<T> {
/**
* Constant pass to Violation when object is not check.
*/
public static final String ERROR_CODE_IS_NOT_CHECKED = "ERROR_CODE_IS_NOT_CHECKED";
protected String message = "This should have at least one checked choice.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public IsCheckedConstraint(@NonNull T object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the object view is checked.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/IsCheckedConstraint.java
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate a view to be checked.
* @param <T> Object should extends from View.
*/
public class IsCheckedConstraint<T extends View> extends Constraint<T> {
/**
* Constant pass to Violation when object is not check.
*/
public static final String ERROR_CODE_IS_NOT_CHECKED = "ERROR_CODE_IS_NOT_CHECKED";
protected String message = "This should have at least one checked choice.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public IsCheckedConstraint(@NonNull T object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the object view is checked.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/ImageConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.Utils;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowBitmapFactory;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {
ShadowBitmapFactory.class
})
public class ImageConstraintTest {
private File file;
@Before
public void setUp() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/ImageConstraintTest.java
import com.comuto.validator.Utils;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowBitmapFactory;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {
ShadowBitmapFactory.class
})
public class ImageConstraintTest {
private File file;
@Before
public void setUp() throws Exception { | this.file = Utils.getFileFromResource(this, "test-file.png"); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/ImageConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.Utils;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowBitmapFactory;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {
ShadowBitmapFactory.class
})
public class ImageConstraintTest {
private File file;
@Before
public void setUp() throws Exception {
this.file = Utils.getFileFromResource(this, "test-file.png");
}
@Test
public void validateIsValid() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/ImageConstraintTest.java
import com.comuto.validator.Utils;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowBitmapFactory;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {
ShadowBitmapFactory.class
})
public class ImageConstraintTest {
private File file;
@Before
public void setUp() throws Exception {
this.file = Utils.getFileFromResource(this, "test-file.png");
}
@Test
public void validateIsValid() throws Exception { | assertEmpty("Is valid", getImageConstraint(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/ImageConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.Utils;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowBitmapFactory;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {
ShadowBitmapFactory.class
})
public class ImageConstraintTest {
private File file;
@Before
public void setUp() throws Exception {
this.file = Utils.getFileFromResource(this, "test-file.png");
}
@Test
public void validateIsValid() throws Exception {
assertEmpty("Is valid", getImageConstraint(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE).validate());
}
@Test
public void validateWithMinWidthConstraint() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/ImageConstraintTest.java
import com.comuto.validator.Utils;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowBitmapFactory;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {
ShadowBitmapFactory.class
})
public class ImageConstraintTest {
private File file;
@Before
public void setUp() throws Exception {
this.file = Utils.getFileFromResource(this, "test-file.png");
}
@Test
public void validateIsValid() throws Exception {
assertEmpty("Is valid", getImageConstraint(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE).validate());
}
@Test
public void validateWithMinWidthConstraint() throws Exception { | assertNotEmpty("Is invalid", getImageConstraint(400, 0, Integer.MAX_VALUE, Integer.MAX_VALUE).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/IsCheckedConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class IsCheckedConstraintTest {
@SuppressWarnings("ResourceType")
@Test
public void isValid() throws Exception {
RadioGroup radioGroup = new RadioGroup(RuntimeEnvironment.application);
radioGroup.check(1); | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/IsCheckedConstraintTest.java
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class IsCheckedConstraintTest {
@SuppressWarnings("ResourceType")
@Test
public void isValid() throws Exception {
RadioGroup radioGroup = new RadioGroup(RuntimeEnvironment.application);
radioGroup.check(1); | assertEmpty("is valid with RadioGroup", new IsCheckedConstraint<View>(radioGroup, "radioGroup").validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/IsCheckedConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class IsCheckedConstraintTest {
@SuppressWarnings("ResourceType")
@Test
public void isValid() throws Exception {
RadioGroup radioGroup = new RadioGroup(RuntimeEnvironment.application);
radioGroup.check(1);
assertEmpty("is valid with RadioGroup", new IsCheckedConstraint<View>(radioGroup, "radioGroup").validate());
RadioButton radioButton = new RadioButton(RuntimeEnvironment.application);
radioButton.setChecked(true);
assertEmpty("is valid with RadioButton", new IsCheckedConstraint<View>(radioButton, "radioButton").validate());
}
@SuppressWarnings("ResourceType")
@Test
public void isInValid() throws Exception {
RadioGroup radioGroup = new RadioGroup(RuntimeEnvironment.application); | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/IsCheckedConstraintTest.java
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class IsCheckedConstraintTest {
@SuppressWarnings("ResourceType")
@Test
public void isValid() throws Exception {
RadioGroup radioGroup = new RadioGroup(RuntimeEnvironment.application);
radioGroup.check(1);
assertEmpty("is valid with RadioGroup", new IsCheckedConstraint<View>(radioGroup, "radioGroup").validate());
RadioButton radioButton = new RadioButton(RuntimeEnvironment.application);
radioButton.setChecked(true);
assertEmpty("is valid with RadioButton", new IsCheckedConstraint<View>(radioButton, "radioButton").validate());
}
@SuppressWarnings("ResourceType")
@Test
public void isInValid() throws Exception {
RadioGroup radioGroup = new RadioGroup(RuntimeEnvironment.application); | assertNotEmpty("is invalid with RadioGroup", new IsCheckedConstraint<View>(radioGroup, "radioGroup").validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/NotEqualsConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotEqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception { | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/NotEqualsConstraintTest.java
import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotEqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception { | assertEmpty("is valid with String", new NotEqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/NotEqualsConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotEqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new NotEqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new NotEqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new NotEqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception { | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/NotEqualsConstraintTest.java
import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotEqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new NotEqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new NotEqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new NotEqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception { | assertNotEmpty("is invalid with String", new NotEqualsConstraint(VALID, VALID, PROPERTY_NAME).validate()); |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/NotEqualsConstraintTest.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotEqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new NotEqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new NotEqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new NotEqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception {
assertNotEmpty("is invalid with String", new NotEqualsConstraint(VALID, VALID, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with EditText",
new NotEqualsConstraint(generateEditText(VALID), VALID, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with Spinner",
new NotEqualsConstraint(generateSpinner(VALID), VALID, PROPERTY_NAME).validate());
}
| // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/NotEqualsConstraintTest.java
import com.comuto.validator.UnsupportedException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
@RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class NotEqualsConstraintTest
extends BaseConstraintTest {
private static final String VALID = "test";
public static final String EXPECTED_VALUE = "not";
private static final String PROPERTY_NAME = "property_not_equals";
@Test
public void isValid() throws Exception {
assertEmpty("is valid with String", new NotEqualsConstraint(VALID, EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with EditText",
new NotEqualsConstraint(generateEditText(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
assertEmpty("is valid with Spinner",
new NotEqualsConstraint(generateSpinner(VALID), EXPECTED_VALUE, PROPERTY_NAME).validate());
}
@Test
public void isInvalid() throws Exception {
assertNotEmpty("is invalid with String", new NotEqualsConstraint(VALID, VALID, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with EditText",
new NotEqualsConstraint(generateEditText(VALID), VALID, PROPERTY_NAME).validate());
assertNotEmpty("is invalid with Spinner",
new NotEqualsConstraint(generateSpinner(VALID), VALID, PROPERTY_NAME).validate());
}
| @Test(expected = UnsupportedException.class) |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/DateConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate the object value to be a date, with a defined format.
*
* Default format is: yyyy-MM-dd
*/
public class DateConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when date is invalid.
*/
public static final String ERROR_CODE_DATE_INVALID = "ERROR_CODE_DATE_INVALID";
private static final String DEFAULT_FORMAT = "yyyy-MM-dd";
private String message = "This value is not a valid date.";
private String format;
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName) {
this(object, propertyName, DEFAULT_FORMAT);
}
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
* @param format the format of the date.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName, @NonNull String format) {
super(object, propertyName);
this.format = format;
}
/**
* Validate if the value is a date.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/DateConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate the object value to be a date, with a defined format.
*
* Default format is: yyyy-MM-dd
*/
public class DateConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when date is invalid.
*/
public static final String ERROR_CODE_DATE_INVALID = "ERROR_CODE_DATE_INVALID";
private static final String DEFAULT_FORMAT = "yyyy-MM-dd";
private String message = "This value is not a valid date.";
private String format;
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName) {
this(object, propertyName, DEFAULT_FORMAT);
}
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
* @param format the format of the date.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName, @NonNull String format) {
super(object, propertyName);
this.format = format;
}
/**
* Validate if the value is a date.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/DateConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate the object value to be a date, with a defined format.
*
* Default format is: yyyy-MM-dd
*/
public class DateConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when date is invalid.
*/
public static final String ERROR_CODE_DATE_INVALID = "ERROR_CODE_DATE_INVALID";
private static final String DEFAULT_FORMAT = "yyyy-MM-dd";
private String message = "This value is not a valid date.";
private String format;
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName) {
this(object, propertyName, DEFAULT_FORMAT);
}
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
* @param format the format of the date.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName, @NonNull String format) {
super(object, propertyName);
this.format = format;
}
/**
* Validate if the value is a date.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/DateConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate the object value to be a date, with a defined format.
*
* Default format is: yyyy-MM-dd
*/
public class DateConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when date is invalid.
*/
public static final String ERROR_CODE_DATE_INVALID = "ERROR_CODE_DATE_INVALID";
private static final String DEFAULT_FORMAT = "yyyy-MM-dd";
private String message = "This value is not a valid date.";
private String format;
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName) {
this(object, propertyName, DEFAULT_FORMAT);
}
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
* @param format the format of the date.
*/
public DateConstraint(@NonNull Object object, @NonNull String propertyName, @NonNull String format) {
super(object, propertyName);
this.format = format;
}
/**
* Validate if the value is a date.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/test/java/com/comuto/validator/ValidatorTest.java | // Path: library/src/main/java/com/comuto/validator/constraint/NotBlankConstraint.java
// public class NotBlankConstraint extends Constraint<Object> {
// /**
// * Constant pass to Violation when the value is blank.
// */
// public static final String ERROR_CODE_IS_BLANK = "ERROR_CODE_IS_BLANK";
//
// protected String message = "This value should not be blank.";
//
// /**
// * Constructor of the constraint
// *
// * @param object the object to validate through this constraint.
// * @param propertyName the property name of your field, this allow you to have the name of the field in violation.
// */
// public NotBlankConstraint(@NonNull Object object, @NonNull String propertyName) {
// super(object, propertyName);
// }
//
// /**
// * Validate if the value is not null and not empty.
// *
// * @return a non-null set of violation. If there is no violations, this set will be empty.
// * @throws UnsupportedException when an constraint object to validate is not supported.
// */
// @NonNull
// @Override
// public Set<Violation> validate() throws UnsupportedException {
// final Set<Violation> violations = new HashSet<>();
// final String value = getStringFromObject(object, propertyName);
//
// if (null == value || 0 == value.trim().length()) {
// violations.add(new Violation(propertyName, value, message, ERROR_CODE_IS_BLANK));
// }
//
// return violations;
// }
//
// /**
// * Set error message when value violate the constraint
// *
// * @param message String message.
// */
// public void setMessage(String message) {
// this.message = message;
// }
// }
| import com.comuto.validator.constraint.NotBlankConstraint;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static junit.framework.Assert.assertEquals; | package com.comuto.validator;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ValidatorTest {
@Test
public void validateWithoutViolations() throws Exception {
Validator validator = new Validator(); | // Path: library/src/main/java/com/comuto/validator/constraint/NotBlankConstraint.java
// public class NotBlankConstraint extends Constraint<Object> {
// /**
// * Constant pass to Violation when the value is blank.
// */
// public static final String ERROR_CODE_IS_BLANK = "ERROR_CODE_IS_BLANK";
//
// protected String message = "This value should not be blank.";
//
// /**
// * Constructor of the constraint
// *
// * @param object the object to validate through this constraint.
// * @param propertyName the property name of your field, this allow you to have the name of the field in violation.
// */
// public NotBlankConstraint(@NonNull Object object, @NonNull String propertyName) {
// super(object, propertyName);
// }
//
// /**
// * Validate if the value is not null and not empty.
// *
// * @return a non-null set of violation. If there is no violations, this set will be empty.
// * @throws UnsupportedException when an constraint object to validate is not supported.
// */
// @NonNull
// @Override
// public Set<Violation> validate() throws UnsupportedException {
// final Set<Violation> violations = new HashSet<>();
// final String value = getStringFromObject(object, propertyName);
//
// if (null == value || 0 == value.trim().length()) {
// violations.add(new Violation(propertyName, value, message, ERROR_CODE_IS_BLANK));
// }
//
// return violations;
// }
//
// /**
// * Set error message when value violate the constraint
// *
// * @param message String message.
// */
// public void setMessage(String message) {
// this.message = message;
// }
// }
// Path: library/src/test/java/com/comuto/validator/ValidatorTest.java
import com.comuto.validator.constraint.NotBlankConstraint;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static junit.framework.Assert.assertEquals;
package com.comuto.validator;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class ValidatorTest {
@Test
public void validateWithoutViolations() throws Exception {
Validator validator = new Validator(); | validator.add(new NotBlankConstraint("Test", "string")); |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/NotBlankConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate the object value to be not null and not empty.
*/
public class NotBlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when the value is blank.
*/
public static final String ERROR_CODE_IS_BLANK = "ERROR_CODE_IS_BLANK";
protected String message = "This value should not be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public NotBlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is not null and not empty.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/NotBlankConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate the object value to be not null and not empty.
*/
public class NotBlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when the value is blank.
*/
public static final String ERROR_CODE_IS_BLANK = "ERROR_CODE_IS_BLANK";
protected String message = "This value should not be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public NotBlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is not null and not empty.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/NotBlankConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set; | package com.comuto.validator.constraint;
/**
* Validate the object value to be not null and not empty.
*/
public class NotBlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when the value is blank.
*/
public static final String ERROR_CODE_IS_BLANK = "ERROR_CODE_IS_BLANK";
protected String message = "This value should not be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public NotBlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is not null and not empty.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/NotBlankConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
package com.comuto.validator.constraint;
/**
* Validate the object value to be not null and not empty.
*/
public class NotBlankConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when the value is blank.
*/
public static final String ERROR_CODE_IS_BLANK = "ERROR_CODE_IS_BLANK";
protected String message = "This value should not be blank.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public NotBlankConstraint(@NonNull Object object, @NonNull String propertyName) {
super(object, propertyName);
}
/**
* Validate if the value is not null and not empty.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/MatchConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern; | package com.comuto.validator.constraint;
/**
* Validate the object value to reach the good pattern.
*/
public class MatchConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when not match the pattern.
*/
public static final String ERROR_CODE_NOT_MATCH = "ERROR_CODE_NOT_MATCH";
protected final Pattern pattern;
protected String message = "This value is not valid.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param pattern the Pattern to validate.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public MatchConstraint(@NonNull Object object, @NonNull Pattern pattern, @NonNull String propertyName) {
super(object, propertyName);
this.pattern = pattern;
}
/**
* Validate if the value respect the pattern.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/MatchConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
package com.comuto.validator.constraint;
/**
* Validate the object value to reach the good pattern.
*/
public class MatchConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when not match the pattern.
*/
public static final String ERROR_CODE_NOT_MATCH = "ERROR_CODE_NOT_MATCH";
protected final Pattern pattern;
protected String message = "This value is not valid.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param pattern the Pattern to validate.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public MatchConstraint(@NonNull Object object, @NonNull Pattern pattern, @NonNull String propertyName) {
super(object, propertyName);
this.pattern = pattern;
}
/**
* Validate if the value respect the pattern.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/main/java/com/comuto/validator/constraint/MatchConstraint.java | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
| import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern; | package com.comuto.validator.constraint;
/**
* Validate the object value to reach the good pattern.
*/
public class MatchConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when not match the pattern.
*/
public static final String ERROR_CODE_NOT_MATCH = "ERROR_CODE_NOT_MATCH";
protected final Pattern pattern;
protected String message = "This value is not valid.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param pattern the Pattern to validate.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public MatchConstraint(@NonNull Object object, @NonNull Pattern pattern, @NonNull String propertyName) {
super(object, propertyName);
this.pattern = pattern;
}
/**
* Validate if the value respect the pattern.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | // Path: library/src/main/java/com/comuto/validator/UnsupportedException.java
// public class UnsupportedException extends RuntimeException {
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified detail message.
// *
// * @param constraint the constraint for this exception.
// * @param o the object invalid value;
// * @param propertyName the property.
// */
// public UnsupportedException(Constraint constraint, Object o, String propertyName) {
// super("Constraint: "
// + constraint.getClass().getSimpleName()
// + " cannot handle "
// + o.getClass().getName()
// + "on property: "
// + propertyName
// + ". If you want to validate a custom Object, you can create a custom Constraint which extends this one and override validate().");
// }
// }
//
// Path: library/src/main/java/com/comuto/validator/Violation.java
// public class Violation {
// private final String propertyName;
// private final Object invalidValue;
// private final String message;
// private final String code;
//
// /**
// * Construct the violation with final values.
// *
// * @param propertyName The name of the field. This is defined by the user.
// * @param invalidValue The invalid which have violate the constraint.
// * @param message The interpolated message.
// * @param code The Error code of the constraint.
// */
// public Violation(String propertyName, Object invalidValue, String message, String code) {
// this.propertyName = propertyName;
// this.invalidValue = invalidValue;
// this.message = message;
// this.code = code;
// }
//
// /**
// * @return the interpolated error message for this constraint violation
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * Returns the value failing to pass the constraint.
// * For cross-parameter constraints, an {@code Object[]} representing
// * the method invocation arguments is returned.
// *
// * @return the value failing to pass the constraint
// */
// public Object getInvalidValue() {
// return invalidValue;
// }
//
// /**
// * Returns the name of the property.
// *
// * @return the property name.
// */
// public String getPropertyName() {
// return propertyName;
// }
//
// /**
// * Returns a machine-digestible error code for the violation.
// *
// * @return String The error code.
// */
// public String getCode() {
// return code;
// }
// }
// Path: library/src/main/java/com/comuto/validator/constraint/MatchConstraint.java
import android.support.annotation.NonNull;
import com.comuto.validator.UnsupportedException;
import com.comuto.validator.Violation;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
package com.comuto.validator.constraint;
/**
* Validate the object value to reach the good pattern.
*/
public class MatchConstraint extends Constraint<Object> {
/**
* Constant pass to Violation when not match the pattern.
*/
public static final String ERROR_CODE_NOT_MATCH = "ERROR_CODE_NOT_MATCH";
protected final Pattern pattern;
protected String message = "This value is not valid.";
/**
* Constructor of the constraint
*
* @param object the object to validate through this constraint.
* @param pattern the Pattern to validate.
* @param propertyName the property name of your field, this allow you to have the name of the field in violation.
*/
public MatchConstraint(@NonNull Object object, @NonNull Pattern pattern, @NonNull String propertyName) {
super(object, propertyName);
this.pattern = pattern;
}
/**
* Validate if the value respect the pattern.
*
* @return a non-null set of violation. If there is no violations, this set will be empty.
* @throws UnsupportedException when an constraint object to validate is not supported.
*/
@NonNull
@Override | public Set<Violation> validate() throws UnsupportedException { |
blablacar/android-validator | library/src/test/java/com/comuto/validator/constraint/FileConstraintTest.java | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
| import com.comuto.validator.Utils;
import org.junit.Before;
import org.junit.Test;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty; | package com.comuto.validator.constraint;
public class FileConstraintTest {
private java.io.File file;
@Before
public void setUp() throws Exception { | // Path: library/src/test/java/com/comuto/validator/Utils.java
// public class Utils {
// public static File getFileFromResource(Object obj, String resourceName) throws IOException {
// TemporaryFolder folder = new TemporaryFolder();
// folder.create();
// File file = folder.newFile(resourceName);
//
// InputStream stream = obj.getClass().getClassLoader().getResourceAsStream(resourceName);
//
// byte[] buffer = new byte[stream.available()];
// stream.read(buffer);
//
// OutputStream outStream = new FileOutputStream(file);
// outStream.write(buffer);
//
// return file;
// }
//
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
//
// private static void failNotEmpty(
// String message, String actual) {
// failWithMessage(message, "expected to be empty, but contained: <"
// + actual + ">");
// }
//
// private static void failEmpty(String message) {
// failWithMessage(message, "expected not to be empty, but was");
// }
//
// private static void failWithMessage(String userMessage, String ourMessage) {
// Assert.fail((userMessage == null)
// ? ourMessage
// : userMessage + ' ' + ourMessage);
// }
//
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertEmpty(String message, Iterable<?> iterable) {
// if (iterable.iterator().hasNext()) {
// failNotEmpty(message, iterable.toString());
// }
// }
//
// Path: library/src/test/java/com/comuto/validator/Utils.java
// public static void assertNotEmpty(String message, Iterable<?> iterable) {
// if (!iterable.iterator().hasNext()) {
// failEmpty(message);
// }
// }
// Path: library/src/test/java/com/comuto/validator/constraint/FileConstraintTest.java
import com.comuto.validator.Utils;
import org.junit.Before;
import org.junit.Test;
import static com.comuto.validator.Utils.assertEmpty;
import static com.comuto.validator.Utils.assertNotEmpty;
package com.comuto.validator.constraint;
public class FileConstraintTest {
private java.io.File file;
@Before
public void setUp() throws Exception { | file = Utils.getFileFromResource(this, "test-file.png"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.